babylon.viewer.max.js 6.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751
  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 = 15);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(18); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(19); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(20); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture 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.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * 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)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * 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)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * 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)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * 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)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * 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)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * 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)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * 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)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * 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)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * 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)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * 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)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * 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)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * 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)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * 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.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = 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. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. this.x = x;
  2299. this.y = y;
  2300. }
  2301. /**
  2302. * Gets a string with the Vector2 coordinates
  2303. * @returns a string with the Vector2 coordinates
  2304. */
  2305. Vector2.prototype.toString = function () {
  2306. return "{X: " + this.x + " Y:" + this.y + "}";
  2307. };
  2308. /**
  2309. * Gets class name
  2310. * @returns the string "Vector2"
  2311. */
  2312. Vector2.prototype.getClassName = function () {
  2313. return "Vector2";
  2314. };
  2315. /**
  2316. * Gets current vector hash code
  2317. * @returns the Vector2 hash code as a number
  2318. */
  2319. Vector2.prototype.getHashCode = function () {
  2320. var hash = this.x || 0;
  2321. hash = (hash * 397) ^ (this.y || 0);
  2322. return hash;
  2323. };
  2324. // Operators
  2325. /**
  2326. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2327. * @param array defines the source array
  2328. * @param index defines the offset in source array
  2329. * @returns the current Vector2
  2330. */
  2331. Vector2.prototype.toArray = function (array, index) {
  2332. if (index === void 0) { index = 0; }
  2333. array[index] = this.x;
  2334. array[index + 1] = this.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Copy the current vector to an array
  2339. * @returns a new array with 2 elements: the Vector2 coordinates.
  2340. */
  2341. Vector2.prototype.asArray = function () {
  2342. var result = new Array();
  2343. this.toArray(result, 0);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2348. * @param source defines the source Vector2
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.copyFrom = function (source) {
  2352. this.x = source.x;
  2353. this.y = source.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Sets the Vector2 coordinates with the given floats
  2358. * @param x defines the first coordinate
  2359. * @param y defines the second coordinate
  2360. * @returns the current updated Vector2
  2361. */
  2362. Vector2.prototype.copyFromFloats = function (x, y) {
  2363. this.x = x;
  2364. this.y = y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the given floats
  2369. * @param x defines the first coordinate
  2370. * @param y defines the second coordinate
  2371. * @returns the current updated Vector2
  2372. */
  2373. Vector2.prototype.set = function (x, y) {
  2374. return this.copyFromFloats(x, y);
  2375. };
  2376. /**
  2377. * Add another vector with the current one
  2378. * @param otherVector defines the other vector
  2379. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2380. */
  2381. Vector2.prototype.add = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @param result defines the target vector
  2388. * @returns the unmodified current Vector2
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns the current updated Vector2
  2399. */
  2400. Vector2.prototype.addInPlace = function (otherVector) {
  2401. this.x += otherVector.x;
  2402. this.y += otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2407. * @param otherVector defines the other vector
  2408. * @returns a new Vector2
  2409. */
  2410. Vector2.prototype.addVector3 = function (otherVector) {
  2411. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2412. };
  2413. /**
  2414. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2415. * @param otherVector defines the other vector
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.subtract = function (otherVector) {
  2419. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2423. * @param otherVector defines the other vector
  2424. * @param result defines the target vector
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2428. result.x = this.x - otherVector.x;
  2429. result.y = this.y - otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.subtractInPlace = function (otherVector) {
  2438. this.x -= otherVector.x;
  2439. this.y -= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Multiplies in place the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2448. this.x *= otherVector.x;
  2449. this.y *= otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2454. * @param otherVector defines the other vector
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.multiply = function (otherVector) {
  2458. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2459. };
  2460. /**
  2461. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2462. * @param otherVector defines the other vector
  2463. * @param result defines the target vector
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2467. result.x = this.x * otherVector.x;
  2468. result.y = this.y * otherVector.y;
  2469. return this;
  2470. };
  2471. /**
  2472. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2473. * @param x defines the first coordinate
  2474. * @param y defines the second coordinate
  2475. * @returns a new Vector2
  2476. */
  2477. Vector2.prototype.multiplyByFloats = function (x, y) {
  2478. return new Vector2(this.x * x, this.y * y);
  2479. };
  2480. /**
  2481. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2482. * @param otherVector defines the other vector
  2483. * @returns a new Vector2
  2484. */
  2485. Vector2.prototype.divide = function (otherVector) {
  2486. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2487. };
  2488. /**
  2489. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2490. * @param otherVector defines the other vector
  2491. * @param result defines the target vector
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.divideToRef = function (otherVector, result) {
  2495. result.x = this.x / otherVector.x;
  2496. result.y = this.y / otherVector.y;
  2497. return this;
  2498. };
  2499. /**
  2500. * Divides the current Vector3 coordinates by the given ones
  2501. * @param otherVector defines the other vector
  2502. * @returns the current updated Vector2
  2503. */
  2504. Vector2.prototype.divideInPlace = function (otherVector) {
  2505. return this.divideToRef(otherVector, this);
  2506. };
  2507. /**
  2508. * Gets a new Vector2 with current Vector2 negated coordinates
  2509. * @returns a new Vector2
  2510. */
  2511. Vector2.prototype.negate = function () {
  2512. return new Vector2(-this.x, -this.y);
  2513. };
  2514. /**
  2515. * Multiply the Vector2 coordinates by scale
  2516. * @param scale defines the scaling factor
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.scaleInPlace = function (scale) {
  2520. this.x *= scale;
  2521. this.y *= scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2526. * @param scale defines the scaling factor
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.prototype.scale = function (scale) {
  2530. var result = new Vector2(0, 0);
  2531. this.scaleToRef(scale, result);
  2532. return result;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleToRef = function (scale, result) {
  2541. result.x = this.x * scale;
  2542. result.y = this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2547. * @param scale defines the scale factor
  2548. * @param result defines the Vector2 object where to store the result
  2549. * @returns the unmodified current Vector2
  2550. */
  2551. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2552. result.x += this.x * scale;
  2553. result.y += this.y * scale;
  2554. return this;
  2555. };
  2556. /**
  2557. * Gets a boolean if two vectors are equals
  2558. * @param otherVector defines the other vector
  2559. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2560. */
  2561. Vector2.prototype.equals = function (otherVector) {
  2562. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2563. };
  2564. /**
  2565. * Gets a boolean if two vectors are equals (using an epsilon value)
  2566. * @param otherVector defines the other vector
  2567. * @param epsilon defines the minimal distance to consider equality
  2568. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2569. */
  2570. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2571. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2572. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2573. };
  2574. // Properties
  2575. /**
  2576. * Gets the length of the vector
  2577. * @returns the vector length (float)
  2578. */
  2579. Vector2.prototype.length = function () {
  2580. return Math.sqrt(this.x * this.x + this.y * this.y);
  2581. };
  2582. /**
  2583. * Gets the vector squared length
  2584. * @returns the vector squared length (float)
  2585. */
  2586. Vector2.prototype.lengthSquared = function () {
  2587. return (this.x * this.x + this.y * this.y);
  2588. };
  2589. // Methods
  2590. /**
  2591. * Normalize the vector
  2592. * @returns the current updated Vector2
  2593. */
  2594. Vector2.prototype.normalize = function () {
  2595. var len = this.length();
  2596. if (len === 0)
  2597. return this;
  2598. var num = 1.0 / len;
  2599. this.x *= num;
  2600. this.y *= num;
  2601. return this;
  2602. };
  2603. /**
  2604. * Gets a new Vector2 copied from the Vector2
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.prototype.clone = function () {
  2608. return new Vector2(this.x, this.y);
  2609. };
  2610. // Statics
  2611. /**
  2612. * Gets a new Vector2(0, 0)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.Zero = function () {
  2616. return new Vector2(0, 0);
  2617. };
  2618. /**
  2619. * Gets a new Vector2(1, 1)
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.One = function () {
  2623. return new Vector2(1, 1);
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set from the given index element of the given array
  2627. * @param array defines the data source
  2628. * @param offset defines the offset in the data source
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.FromArray = function (array, offset) {
  2632. if (offset === void 0) { offset = 0; }
  2633. return new Vector2(array[offset], array[offset + 1]);
  2634. };
  2635. /**
  2636. * Sets "result" from the given index element of the given array
  2637. * @param array defines the data source
  2638. * @param offset defines the offset in the data source
  2639. * @param result defines the target vector
  2640. */
  2641. Vector2.FromArrayToRef = function (array, offset, result) {
  2642. result.x = array[offset];
  2643. result.y = array[offset + 1];
  2644. };
  2645. /**
  2646. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2647. * @param value1 defines 1st point of control
  2648. * @param value2 defines 2nd point of control
  2649. * @param value3 defines 3rd point of control
  2650. * @param value4 defines 4th point of control
  2651. * @param amount defines the interpolation factor
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2655. var squared = amount * amount;
  2656. var cubed = amount * squared;
  2657. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2658. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2659. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2660. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2661. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2662. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * 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".
  2667. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2668. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2669. * @param value defines the value to clamp
  2670. * @param min defines the lower limit
  2671. * @param max defines the upper limit
  2672. * @returns a new Vector2
  2673. */
  2674. Vector2.Clamp = function (value, min, max) {
  2675. var x = value.x;
  2676. x = (x > max.x) ? max.x : x;
  2677. x = (x < min.x) ? min.x : x;
  2678. var y = value.y;
  2679. y = (y > max.y) ? max.y : y;
  2680. y = (y < min.y) ? min.y : y;
  2681. return new Vector2(x, y);
  2682. };
  2683. /**
  2684. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2685. * @param value1 defines the 1st control point
  2686. * @param tangent1 defines the outgoing tangent
  2687. * @param value2 defines the 2nd control point
  2688. * @param tangent2 defines the incoming tangent
  2689. * @param amount defines the interpolation factor
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2693. var squared = amount * amount;
  2694. var cubed = amount * squared;
  2695. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2696. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2697. var part3 = (cubed - (2.0 * squared)) + amount;
  2698. var part4 = cubed - squared;
  2699. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2700. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2701. return new Vector2(x, y);
  2702. };
  2703. /**
  2704. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2705. * @param start defines the start vector
  2706. * @param end defines the end vector
  2707. * @param amount defines the interpolation factor
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Lerp = function (start, end, amount) {
  2711. var x = start.x + ((end.x - start.x) * amount);
  2712. var y = start.y + ((end.y - start.y) * amount);
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Gets the dot product of the vector "left" and the vector "right"
  2717. * @param left defines first vector
  2718. * @param right defines second vector
  2719. * @returns the dot product (float)
  2720. */
  2721. Vector2.Dot = function (left, right) {
  2722. return left.x * right.x + left.y * right.y;
  2723. };
  2724. /**
  2725. * Returns a new Vector2 equal to the normalized given vector
  2726. * @param vector defines the vector to normalize
  2727. * @returns a new Vector2
  2728. */
  2729. Vector2.Normalize = function (vector) {
  2730. var newVector = vector.clone();
  2731. newVector.normalize();
  2732. return newVector;
  2733. };
  2734. /**
  2735. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2736. * @param left defines 1st vector
  2737. * @param right defines 2nd vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Minimize = function (left, right) {
  2741. var x = (left.x < right.x) ? left.x : right.x;
  2742. var y = (left.y < right.y) ? left.y : right.y;
  2743. return new Vector2(x, y);
  2744. };
  2745. /**
  2746. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2747. * @param left defines 1st vector
  2748. * @param right defines 2nd vector
  2749. * @returns a new Vector2
  2750. */
  2751. Vector2.Maximize = function (left, right) {
  2752. var x = (left.x > right.x) ? left.x : right.x;
  2753. var y = (left.y > right.y) ? left.y : right.y;
  2754. return new Vector2(x, y);
  2755. };
  2756. /**
  2757. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2758. * @param vector defines the vector to transform
  2759. * @param transformation defines the matrix to apply
  2760. * @returns a new Vector2
  2761. */
  2762. Vector2.Transform = function (vector, transformation) {
  2763. var r = Vector2.Zero();
  2764. Vector2.TransformToRef(vector, transformation, r);
  2765. return r;
  2766. };
  2767. /**
  2768. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2769. * @param vector defines the vector to transform
  2770. * @param transformation defines the matrix to apply
  2771. * @param result defines the target vector
  2772. */
  2773. Vector2.TransformToRef = function (vector, transformation, result) {
  2774. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2775. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2776. result.x = x;
  2777. result.y = y;
  2778. };
  2779. /**
  2780. * Determines if a given vector is included in a triangle
  2781. * @param p defines the vector to test
  2782. * @param p0 defines 1st triangle point
  2783. * @param p1 defines 2nd triangle point
  2784. * @param p2 defines 3rd triangle point
  2785. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2786. */
  2787. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2788. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2789. var sign = a < 0 ? -1 : 1;
  2790. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2791. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2792. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2793. };
  2794. /**
  2795. * Gets the distance between the vectors "value1" and "value2"
  2796. * @param value1 defines first vector
  2797. * @param value2 defines second vector
  2798. * @returns the distance between vectors
  2799. */
  2800. Vector2.Distance = function (value1, value2) {
  2801. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2802. };
  2803. /**
  2804. * Returns the squared distance between the vectors "value1" and "value2"
  2805. * @param value1 defines first vector
  2806. * @param value2 defines second vector
  2807. * @returns the squared distance between vectors
  2808. */
  2809. Vector2.DistanceSquared = function (value1, value2) {
  2810. var x = value1.x - value2.x;
  2811. var y = value1.y - value2.y;
  2812. return (x * x) + (y * y);
  2813. };
  2814. /**
  2815. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2816. * @param value1 defines first vector
  2817. * @param value2 defines second vector
  2818. * @returns a new Vector2
  2819. */
  2820. Vector2.Center = function (value1, value2) {
  2821. var center = value1.add(value2);
  2822. center.scaleInPlace(0.5);
  2823. return center;
  2824. };
  2825. /**
  2826. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2827. * @param p defines the middle point
  2828. * @param segA defines one point of the segment
  2829. * @param segB defines the other point of the segment
  2830. * @returns the shortest distance
  2831. */
  2832. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2833. var l2 = Vector2.DistanceSquared(segA, segB);
  2834. if (l2 === 0.0) {
  2835. return Vector2.Distance(p, segA);
  2836. }
  2837. var v = segB.subtract(segA);
  2838. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2839. var proj = segA.add(v.multiplyByFloats(t, t));
  2840. return Vector2.Distance(p, proj);
  2841. };
  2842. return Vector2;
  2843. }());
  2844. BABYLON.Vector2 = Vector2;
  2845. /**
  2846. * Classed used to store (x,y,z) vector representation
  2847. * A Vector3 is the main object used in 3D geometry
  2848. * It can represent etiher the coordinates of a point the space, either a direction
  2849. * Reminder: Babylon.js uses a left handed forward facing system
  2850. */
  2851. var Vector3 = /** @class */ (function () {
  2852. /**
  2853. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2854. * @param x defines the first coordinates (on X axis)
  2855. * @param y defines the second coordinates (on Y axis)
  2856. * @param z defines the third coordinates (on Z axis)
  2857. */
  2858. function Vector3(
  2859. /**
  2860. * Defines the first coordinates (on X axis)
  2861. */
  2862. x,
  2863. /**
  2864. * Defines the second coordinates (on Y axis)
  2865. */
  2866. y,
  2867. /**
  2868. * Defines the third coordinates (on Z axis)
  2869. */
  2870. z) {
  2871. this.x = x;
  2872. this.y = y;
  2873. this.z = z;
  2874. }
  2875. /**
  2876. * Creates a string representation of the Vector3
  2877. * @returns a string with the Vector3 coordinates.
  2878. */
  2879. Vector3.prototype.toString = function () {
  2880. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2881. };
  2882. /**
  2883. * Gets the class name
  2884. * @returns the string "Vector3"
  2885. */
  2886. Vector3.prototype.getClassName = function () {
  2887. return "Vector3";
  2888. };
  2889. /**
  2890. * Creates the Vector3 hash code
  2891. * @returns a number which tends to be unique between Vector3 instances
  2892. */
  2893. Vector3.prototype.getHashCode = function () {
  2894. var hash = this.x || 0;
  2895. hash = (hash * 397) ^ (this.y || 0);
  2896. hash = (hash * 397) ^ (this.z || 0);
  2897. return hash;
  2898. };
  2899. // Operators
  2900. /**
  2901. * Creates an array containing three elements : the coordinates of the Vector3
  2902. * @returns a new array of numbers
  2903. */
  2904. Vector3.prototype.asArray = function () {
  2905. var result = [];
  2906. this.toArray(result, 0);
  2907. return result;
  2908. };
  2909. /**
  2910. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2911. * @param array defines the destination array
  2912. * @param index defines the offset in the destination array
  2913. * @returns the current Vector3
  2914. */
  2915. Vector3.prototype.toArray = function (array, index) {
  2916. if (index === void 0) { index = 0; }
  2917. array[index] = this.x;
  2918. array[index + 1] = this.y;
  2919. array[index + 2] = this.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2924. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2925. */
  2926. Vector3.prototype.toQuaternion = function () {
  2927. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2928. };
  2929. /**
  2930. * Adds the given vector to the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.addInPlace = function (otherVector) {
  2935. this.x += otherVector.x;
  2936. this.y += otherVector.y;
  2937. this.z += otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.add = function (otherVector) {
  2946. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2947. };
  2948. /**
  2949. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.addToRef = function (otherVector, result) {
  2955. result.x = this.x + otherVector.x;
  2956. result.y = this.y + otherVector.y;
  2957. result.z = this.z + otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Subtract the given vector from the current Vector3
  2962. * @param otherVector defines the second operand
  2963. * @returns the current updated Vector3
  2964. */
  2965. Vector3.prototype.subtractInPlace = function (otherVector) {
  2966. this.x -= otherVector.x;
  2967. this.y -= otherVector.y;
  2968. this.z -= otherVector.z;
  2969. return this;
  2970. };
  2971. /**
  2972. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2973. * @param otherVector defines the second operand
  2974. * @returns the resulting Vector3
  2975. */
  2976. Vector3.prototype.subtract = function (otherVector) {
  2977. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2978. };
  2979. /**
  2980. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2981. * @param otherVector defines the second operand
  2982. * @param result defines the Vector3 object where to store the result
  2983. * @returns the current Vector3
  2984. */
  2985. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2986. result.x = this.x - otherVector.x;
  2987. result.y = this.y - otherVector.y;
  2988. result.z = this.z - otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2993. * @param x defines the x coordinate of the operand
  2994. * @param y defines the y coordinate of the operand
  2995. * @param z defines the z coordinate of the operand
  2996. * @returns the resulting Vector3
  2997. */
  2998. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2999. return new Vector3(this.x - x, this.y - y, this.z - z);
  3000. };
  3001. /**
  3002. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3010. result.x = this.x - x;
  3011. result.y = this.y - y;
  3012. result.z = this.z - z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3017. * @returns a new Vector3
  3018. */
  3019. Vector3.prototype.negate = function () {
  3020. return new Vector3(-this.x, -this.y, -this.z);
  3021. };
  3022. /**
  3023. * Multiplies the Vector3 coordinates by the float "scale"
  3024. * @param scale defines the multiplier factor
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.scaleInPlace = function (scale) {
  3028. this.x *= scale;
  3029. this.y *= scale;
  3030. this.z *= scale;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3035. * @param scale defines the multiplier factor
  3036. * @returns a new Vector3
  3037. */
  3038. Vector3.prototype.scale = function (scale) {
  3039. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3043. * @param scale defines the multiplier factor
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.scaleToRef = function (scale, result) {
  3048. result.x = this.x * scale;
  3049. result.y = this.y * scale;
  3050. result.z = this.z * scale;
  3051. return this;
  3052. };
  3053. /**
  3054. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3055. * @param scale defines the scale factor
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the unmodified current Vector3
  3058. */
  3059. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3060. result.x += this.x * scale;
  3061. result.y += this.y * scale;
  3062. result.z += this.z * scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3067. * @param otherVector defines the second operand
  3068. * @returns true if both vectors are equals
  3069. */
  3070. Vector3.prototype.equals = function (otherVector) {
  3071. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3075. * @param otherVector defines the second operand
  3076. * @param epsilon defines the minimal distance to define values as equals
  3077. * @returns true if both vectors are distant less than epsilon
  3078. */
  3079. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3081. 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);
  3082. };
  3083. /**
  3084. * Returns true if the current Vector3 coordinates equals the given floats
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns true if both vectors are equals
  3089. */
  3090. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3091. return this.x === x && this.y === y && this.z === z;
  3092. };
  3093. /**
  3094. * Multiplies the current Vector3 coordinates by the given ones
  3095. * @param otherVector defines the second operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3099. this.x *= otherVector.x;
  3100. this.y *= otherVector.y;
  3101. this.z *= otherVector.z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3106. * @param otherVector defines the second operand
  3107. * @returns the new Vector3
  3108. */
  3109. Vector3.prototype.multiply = function (otherVector) {
  3110. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3111. };
  3112. /**
  3113. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3114. * @param otherVector defines the second operand
  3115. * @param result defines the Vector3 object where to store the result
  3116. * @returns the current Vector3
  3117. */
  3118. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3119. result.x = this.x * otherVector.x;
  3120. result.y = this.y * otherVector.y;
  3121. result.z = this.z * otherVector.z;
  3122. return this;
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3126. * @param x defines the x coordinate of the operand
  3127. * @param y defines the y coordinate of the operand
  3128. * @param z defines the z coordinate of the operand
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3132. return new Vector3(this.x * x, this.y * y, this.z * z);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3136. * @param otherVector defines the second operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.divide = function (otherVector) {
  3140. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3141. };
  3142. /**
  3143. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3144. * @param otherVector defines the second operand
  3145. * @param result defines the Vector3 object where to store the result
  3146. * @returns the current Vector3
  3147. */
  3148. Vector3.prototype.divideToRef = function (otherVector, result) {
  3149. result.x = this.x / otherVector.x;
  3150. result.y = this.y / otherVector.y;
  3151. result.z = this.z / otherVector.z;
  3152. return this;
  3153. };
  3154. /**
  3155. * Divides the current Vector3 coordinates by the given ones.
  3156. * @param otherVector defines the second operand
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.divideInPlace = function (otherVector) {
  3160. return this.divideToRef(otherVector, this);
  3161. };
  3162. /**
  3163. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3164. * @param other defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.minimizeInPlace = function (other) {
  3168. if (other.x < this.x)
  3169. this.x = other.x;
  3170. if (other.y < this.y)
  3171. this.y = other.y;
  3172. if (other.z < this.z)
  3173. this.z = other.z;
  3174. return this;
  3175. };
  3176. /**
  3177. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3178. * @param other defines the second operand
  3179. * @returns the current updated Vector3
  3180. */
  3181. Vector3.prototype.maximizeInPlace = function (other) {
  3182. if (other.x > this.x)
  3183. this.x = other.x;
  3184. if (other.y > this.y)
  3185. this.y = other.y;
  3186. if (other.z > this.z)
  3187. this.z = other.z;
  3188. return this;
  3189. };
  3190. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3191. /**
  3192. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3193. */
  3194. get: function () {
  3195. var absX = Math.abs(this.x);
  3196. var absY = Math.abs(this.y);
  3197. if (absX !== absY) {
  3198. return true;
  3199. }
  3200. var absZ = Math.abs(this.z);
  3201. if (absX !== absZ) {
  3202. return true;
  3203. }
  3204. if (absY !== absZ) {
  3205. return true;
  3206. }
  3207. return false;
  3208. },
  3209. enumerable: true,
  3210. configurable: true
  3211. });
  3212. // Properties
  3213. /**
  3214. * Gets the length of the Vector3
  3215. * @returns the length of the Vecto3
  3216. */
  3217. Vector3.prototype.length = function () {
  3218. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Gets the squared length of the Vector3
  3222. * @returns squared length of the Vector3
  3223. */
  3224. Vector3.prototype.lengthSquared = function () {
  3225. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3226. };
  3227. /**
  3228. * Normalize the current Vector3.
  3229. * Please note that this is an in place operation.
  3230. * @returns the current updated Vector3
  3231. */
  3232. Vector3.prototype.normalize = function () {
  3233. var len = this.length();
  3234. if (len === 0 || len === 1.0)
  3235. return this;
  3236. var num = 1.0 / len;
  3237. this.x *= num;
  3238. this.y *= num;
  3239. this.z *= num;
  3240. return this;
  3241. };
  3242. /**
  3243. * Normalize the current Vector3 to a new vector
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.prototype.normalizeToNew = function () {
  3247. var normalized = new Vector3(0, 0, 0);
  3248. this.normalizeToRef(normalized);
  3249. return normalized;
  3250. };
  3251. /**
  3252. * Normalize the current Vector3 to the reference
  3253. * @param reference define the Vector3 to update
  3254. * @returns the updated Vector3
  3255. */
  3256. Vector3.prototype.normalizeToRef = function (reference) {
  3257. var len = this.length();
  3258. if (len === 0 || len === 1.0) {
  3259. reference.set(this.x, this.y, this.z);
  3260. return reference;
  3261. }
  3262. var scale = 1.0 / len;
  3263. this.scaleToRef(scale, reference);
  3264. return reference;
  3265. };
  3266. /**
  3267. * Creates a new Vector3 copied from the current Vector3
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.prototype.clone = function () {
  3271. return new Vector3(this.x, this.y, this.z);
  3272. };
  3273. /**
  3274. * Copies the given vector coordinates to the current Vector3 ones
  3275. * @param source defines the source Vector3
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.copyFrom = function (source) {
  3279. this.x = source.x;
  3280. this.y = source.y;
  3281. this.z = source.z;
  3282. return this;
  3283. };
  3284. /**
  3285. * Copies the given floats to the current Vector3 coordinates
  3286. * @param x defines the x coordinate of the operand
  3287. * @param y defines the y coordinate of the operand
  3288. * @param z defines the z coordinate of the operand
  3289. * @returns the current updated Vector3
  3290. */
  3291. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. return this;
  3296. };
  3297. /**
  3298. * Copies the given floats to the current Vector3 coordinates
  3299. * @param x defines the x coordinate of the operand
  3300. * @param y defines the y coordinate of the operand
  3301. * @param z defines the z coordinate of the operand
  3302. * @returns the current updated Vector3
  3303. */
  3304. Vector3.prototype.set = function (x, y, z) {
  3305. return this.copyFromFloats(x, y, z);
  3306. };
  3307. // Statics
  3308. /**
  3309. * Get the clip factor between two vectors
  3310. * @param vector0 defines the first operand
  3311. * @param vector1 defines the second operand
  3312. * @param axis defines the axis to use
  3313. * @param size defines the size along the axis
  3314. * @returns the clip factor
  3315. */
  3316. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3317. var d0 = Vector3.Dot(vector0, axis) - size;
  3318. var d1 = Vector3.Dot(vector1, axis) - size;
  3319. var s = d0 / (d0 - d1);
  3320. return s;
  3321. };
  3322. /**
  3323. * Get angle between two vectors
  3324. * @param vector0 angle between vector0 and vector1
  3325. * @param vector1 angle between vector0 and vector1
  3326. * @param normal direction of the normal
  3327. * @return the angle between vector0 and vector1
  3328. */
  3329. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3330. var v0 = vector0.clone().normalize();
  3331. var v1 = vector1.clone().normalize();
  3332. var dot = Vector3.Dot(v0, v1);
  3333. var n = Vector3.Cross(v0, v1);
  3334. if (Vector3.Dot(n, normal) > 0) {
  3335. return Math.acos(dot);
  3336. }
  3337. return -Math.acos(dot);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set from the index "offset" of the given array
  3341. * @param array defines the source array
  3342. * @param offset defines the offset in the source array
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.FromArray = function (array, offset) {
  3346. if (!offset) {
  3347. offset = 0;
  3348. }
  3349. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3353. * This function is deprecated. Use FromArray instead
  3354. * @param array defines the source array
  3355. * @param offset defines the offset in the source array
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.FromFloatArray = function (array, offset) {
  3359. return Vector3.FromArray(array, offset);
  3360. };
  3361. /**
  3362. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3363. * @param array defines the source array
  3364. * @param offset defines the offset in the source array
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.FromArrayToRef = function (array, offset, result) {
  3368. result.x = array[offset];
  3369. result.y = array[offset + 1];
  3370. result.z = array[offset + 2];
  3371. };
  3372. /**
  3373. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3374. * This function is deprecated. Use FromArrayToRef instead.
  3375. * @param array defines the source array
  3376. * @param offset defines the offset in the source array
  3377. * @param result defines the Vector3 where to store the result
  3378. */
  3379. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3380. return Vector3.FromArrayToRef(array, offset, result);
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the given floats.
  3384. * @param x defines the x coordinate of the source
  3385. * @param y defines the y coordinate of the source
  3386. * @param z defines the z coordinate of the source
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3390. result.x = x;
  3391. result.y = y;
  3392. result.z = z;
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3396. * @returns a new empty Vector3
  3397. */
  3398. Vector3.Zero = function () {
  3399. return new Vector3(0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3403. * @returns a new unit Vector3
  3404. */
  3405. Vector3.One = function () {
  3406. return new Vector3(1.0, 1.0, 1.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3410. * @returns a new up Vector3
  3411. */
  3412. Vector3.Up = function () {
  3413. return new Vector3(0.0, 1.0, 0.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3417. * @returns a new down Vector3
  3418. */
  3419. Vector3.Down = function () {
  3420. return new Vector3(0.0, -1.0, 0.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3424. * @returns a new forward Vector3
  3425. */
  3426. Vector3.Forward = function () {
  3427. return new Vector3(0.0, 0.0, 1.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3431. * @returns a new right Vector3
  3432. */
  3433. Vector3.Right = function () {
  3434. return new Vector3(1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3438. * @returns a new left Vector3
  3439. */
  3440. Vector3.Left = function () {
  3441. return new Vector3(-1.0, 0.0, 0.0);
  3442. };
  3443. /**
  3444. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3445. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3446. * @param vector defines the Vector3 to transform
  3447. * @param transformation defines the transformation matrix
  3448. * @returns the transformed Vector3
  3449. */
  3450. Vector3.TransformCoordinates = function (vector, transformation) {
  3451. var result = Vector3.Zero();
  3452. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3453. return result;
  3454. };
  3455. /**
  3456. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3457. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3458. * @param vector defines the Vector3 to transform
  3459. * @param transformation defines the transformation matrix
  3460. * @param result defines the Vector3 where to store the result
  3461. */
  3462. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3463. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3464. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3465. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3466. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3467. result.x = x / w;
  3468. result.y = y / w;
  3469. result.z = z / w;
  3470. };
  3471. /**
  3472. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3473. * This method computes tranformed coordinates only, not transformed direction vectors
  3474. * @param x define the x coordinate of the source vector
  3475. * @param y define the y coordinate of the source vector
  3476. * @param z define the z coordinate of the source vector
  3477. * @param transformation defines the transformation matrix
  3478. * @param result defines the Vector3 where to store the result
  3479. */
  3480. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3481. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3482. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3483. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3484. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3485. result.x = rx / rw;
  3486. result.y = ry / rw;
  3487. result.z = rz / rw;
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3491. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3492. * @param vector defines the Vector3 to transform
  3493. * @param transformation defines the transformation matrix
  3494. * @returns the new Vector3
  3495. */
  3496. Vector3.TransformNormal = function (vector, transformation) {
  3497. var result = Vector3.Zero();
  3498. Vector3.TransformNormalToRef(vector, transformation, result);
  3499. return result;
  3500. };
  3501. /**
  3502. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3503. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3504. * @param vector defines the Vector3 to transform
  3505. * @param transformation defines the transformation matrix
  3506. * @param result defines the Vector3 where to store the result
  3507. */
  3508. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3509. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3510. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3511. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3512. result.x = x;
  3513. result.y = y;
  3514. result.z = z;
  3515. };
  3516. /**
  3517. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3518. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3519. * @param x define the x coordinate of the source vector
  3520. * @param y define the y coordinate of the source vector
  3521. * @param z define the z coordinate of the source vector
  3522. * @param transformation defines the transformation matrix
  3523. * @param result defines the Vector3 where to store the result
  3524. */
  3525. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3526. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3527. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3528. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3532. * @param value1 defines the first control point
  3533. * @param value2 defines the second control point
  3534. * @param value3 defines the third control point
  3535. * @param value4 defines the fourth control point
  3536. * @param amount defines the amount on the spline to use
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3540. var squared = amount * amount;
  3541. var cubed = amount * squared;
  3542. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3543. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3544. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3545. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3546. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3547. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3548. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3549. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3550. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3551. return new Vector3(x, y, z);
  3552. };
  3553. /**
  3554. * 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"
  3555. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3556. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3557. * @param value defines the current value
  3558. * @param min defines the lower range value
  3559. * @param max defines the upper range value
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Clamp = function (value, min, max) {
  3563. var x = value.x;
  3564. x = (x > max.x) ? max.x : x;
  3565. x = (x < min.x) ? min.x : x;
  3566. var y = value.y;
  3567. y = (y > max.y) ? max.y : y;
  3568. y = (y < min.y) ? min.y : y;
  3569. var z = value.z;
  3570. z = (z > max.z) ? max.z : z;
  3571. z = (z < min.z) ? min.z : z;
  3572. return new Vector3(x, y, z);
  3573. };
  3574. /**
  3575. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3576. * @param value1 defines the first control point
  3577. * @param tangent1 defines the first tangent vector
  3578. * @param value2 defines the second control point
  3579. * @param tangent2 defines the second tangent vector
  3580. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3581. * @returns the new Vector3
  3582. */
  3583. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3584. var squared = amount * amount;
  3585. var cubed = amount * squared;
  3586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3588. var part3 = (cubed - (2.0 * squared)) + amount;
  3589. var part4 = cubed - squared;
  3590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3592. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3593. return new Vector3(x, y, z);
  3594. };
  3595. /**
  3596. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3597. * @param start defines the start value
  3598. * @param end defines the end value
  3599. * @param amount max defines amount between both (between 0 and 1)
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Lerp = function (start, end, amount) {
  3603. var result = new Vector3(0, 0, 0);
  3604. Vector3.LerpToRef(start, end, amount, result);
  3605. return result;
  3606. };
  3607. /**
  3608. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3609. * @param start defines the start value
  3610. * @param end defines the end value
  3611. * @param amount max defines amount between both (between 0 and 1)
  3612. * @param result defines the Vector3 where to store the result
  3613. */
  3614. Vector3.LerpToRef = function (start, end, amount, result) {
  3615. result.x = start.x + ((end.x - start.x) * amount);
  3616. result.y = start.y + ((end.y - start.y) * amount);
  3617. result.z = start.z + ((end.z - start.z) * amount);
  3618. };
  3619. /**
  3620. * Returns the dot product (float) between the vectors "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @returns the dot product
  3624. */
  3625. Vector3.Dot = function (left, right) {
  3626. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3627. };
  3628. /**
  3629. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3630. * The cross product is then orthogonal to both "left" and "right"
  3631. * @param left defines the left operand
  3632. * @param right defines the right operand
  3633. * @returns the cross product
  3634. */
  3635. Vector3.Cross = function (left, right) {
  3636. var result = Vector3.Zero();
  3637. Vector3.CrossToRef(left, right, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the cross product of "left" and "right"
  3642. * The cross product is then orthogonal to both "left" and "right"
  3643. * @param left defines the left operand
  3644. * @param right defines the right operand
  3645. * @param result defines the Vector3 where to store the result
  3646. */
  3647. Vector3.CrossToRef = function (left, right, result) {
  3648. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3649. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3650. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3651. result.copyFrom(MathTmp.Vector3[0]);
  3652. };
  3653. /**
  3654. * Returns a new Vector3 as the normalization of the given vector
  3655. * @param vector defines the Vector3 to normalize
  3656. * @returns the new Vector3
  3657. */
  3658. Vector3.Normalize = function (vector) {
  3659. var result = Vector3.Zero();
  3660. Vector3.NormalizeToRef(vector, result);
  3661. return result;
  3662. };
  3663. /**
  3664. * Sets the given vector "result" with the normalization of the given first vector
  3665. * @param vector defines the Vector3 to normalize
  3666. * @param result defines the Vector3 where to store the result
  3667. */
  3668. Vector3.NormalizeToRef = function (vector, result) {
  3669. result.copyFrom(vector);
  3670. result.normalize();
  3671. };
  3672. /**
  3673. * Project a Vector3 onto screen space
  3674. * @param vector defines the Vector3 to project
  3675. * @param world defines the world matrix to use
  3676. * @param transform defines the transform (view x projection) matrix to use
  3677. * @param viewport defines the screen viewport to use
  3678. * @returns the new Vector3
  3679. */
  3680. Vector3.Project = function (vector, world, transform, viewport) {
  3681. var cw = viewport.width;
  3682. var ch = viewport.height;
  3683. var cx = viewport.x;
  3684. var cy = viewport.y;
  3685. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3686. 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);
  3687. var matrix = MathTmp.Matrix[0];
  3688. world.multiplyToRef(transform, matrix);
  3689. matrix.multiplyToRef(viewportMatrix, matrix);
  3690. return Vector3.TransformCoordinates(vector, matrix);
  3691. };
  3692. /**
  3693. * Unproject from screen space to object space
  3694. * @param source defines the screen space Vector3 to use
  3695. * @param viewportWidth defines the current width of the viewport
  3696. * @param viewportHeight defines the current height of the viewport
  3697. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3698. * @param transform defines the transform (view x projection) matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3702. var matrix = MathTmp.Matrix[0];
  3703. world.multiplyToRef(transform, matrix);
  3704. matrix.invert();
  3705. source.x = source.x / viewportWidth * 2 - 1;
  3706. source.y = -(source.y / viewportHeight * 2 - 1);
  3707. var vector = Vector3.TransformCoordinates(source, matrix);
  3708. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3709. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3710. vector = vector.scale(1.0 / num);
  3711. }
  3712. return vector;
  3713. };
  3714. /**
  3715. * Unproject from screen space to object space
  3716. * @param source defines the screen space Vector3 to use
  3717. * @param viewportWidth defines the current width of the viewport
  3718. * @param viewportHeight defines the current height of the viewport
  3719. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3720. * @param view defines the view matrix to use
  3721. * @param projection defines the projection matrix to use
  3722. * @returns the new Vector3
  3723. */
  3724. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3725. var result = Vector3.Zero();
  3726. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3727. return result;
  3728. };
  3729. /**
  3730. * Unproject from screen space to object space
  3731. * @param source defines the screen space Vector3 to use
  3732. * @param viewportWidth defines the current width of the viewport
  3733. * @param viewportHeight defines the current height of the viewport
  3734. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3735. * @param view defines the view matrix to use
  3736. * @param projection defines the projection matrix to use
  3737. * @param result defines the Vector3 where to store the result
  3738. */
  3739. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3740. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3741. };
  3742. /**
  3743. * Unproject from screen space to object space
  3744. * @param sourceX defines the screen space x coordinate to use
  3745. * @param sourceY defines the screen space y coordinate to use
  3746. * @param sourceZ defines the screen space z coordinate to use
  3747. * @param viewportWidth defines the current width of the viewport
  3748. * @param viewportHeight defines the current height of the viewport
  3749. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3750. * @param view defines the view matrix to use
  3751. * @param projection defines the projection matrix to use
  3752. * @param result defines the Vector3 where to store the result
  3753. */
  3754. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3755. var matrix = MathTmp.Matrix[0];
  3756. world.multiplyToRef(view, matrix);
  3757. matrix.multiplyToRef(projection, matrix);
  3758. matrix.invert();
  3759. var screenSource = MathTmp.Vector3[0];
  3760. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3761. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3762. screenSource.z = 2 * sourceZ - 1.0;
  3763. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3764. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3765. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3766. result.scaleInPlace(1.0 / num);
  3767. }
  3768. };
  3769. /**
  3770. * Gets the minimal coordinate values between two Vector3
  3771. * @param left defines the first operand
  3772. * @param right defines the second operand
  3773. * @returns the new Vector3
  3774. */
  3775. Vector3.Minimize = function (left, right) {
  3776. var min = left.clone();
  3777. min.minimizeInPlace(right);
  3778. return min;
  3779. };
  3780. /**
  3781. * Gets the maximal coordinate values between two Vector3
  3782. * @param left defines the first operand
  3783. * @param right defines the second operand
  3784. * @returns the new Vector3
  3785. */
  3786. Vector3.Maximize = function (left, right) {
  3787. var max = left.clone();
  3788. max.maximizeInPlace(right);
  3789. return max;
  3790. };
  3791. /**
  3792. * Returns the distance between the vectors "value1" and "value2"
  3793. * @param value1 defines the first operand
  3794. * @param value2 defines the second operand
  3795. * @returns the distance
  3796. */
  3797. Vector3.Distance = function (value1, value2) {
  3798. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3799. };
  3800. /**
  3801. * Returns the squared distance between the vectors "value1" and "value2"
  3802. * @param value1 defines the first operand
  3803. * @param value2 defines the second operand
  3804. * @returns the squared distance
  3805. */
  3806. Vector3.DistanceSquared = function (value1, value2) {
  3807. var x = value1.x - value2.x;
  3808. var y = value1.y - value2.y;
  3809. var z = value1.z - value2.z;
  3810. return (x * x) + (y * y) + (z * z);
  3811. };
  3812. /**
  3813. * Returns a new Vector3 located at the center between "value1" and "value2"
  3814. * @param value1 defines the first operand
  3815. * @param value2 defines the second operand
  3816. * @returns the new Vector3
  3817. */
  3818. Vector3.Center = function (value1, value2) {
  3819. var center = value1.add(value2);
  3820. center.scaleInPlace(0.5);
  3821. return center;
  3822. };
  3823. /**
  3824. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3825. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3826. * to something in order to rotate it from its local system to the given target system
  3827. * Note: axis1, axis2 and axis3 are normalized during this operation
  3828. * @param axis1 defines the first axis
  3829. * @param axis2 defines the second axis
  3830. * @param axis3 defines the third axis
  3831. * @returns a new Vector3
  3832. */
  3833. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3834. var rotation = Vector3.Zero();
  3835. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3836. return rotation;
  3837. };
  3838. /**
  3839. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3840. * @param axis1 defines the first axis
  3841. * @param axis2 defines the second axis
  3842. * @param axis3 defines the third axis
  3843. * @param ref defines the Vector3 where to store the result
  3844. */
  3845. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3846. var quat = MathTmp.Quaternion[0];
  3847. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3848. quat.toEulerAnglesToRef(ref);
  3849. };
  3850. return Vector3;
  3851. }());
  3852. BABYLON.Vector3 = Vector3;
  3853. //Vector4 class created for EulerAngle class conversion to Quaternion
  3854. var Vector4 = /** @class */ (function () {
  3855. /**
  3856. * Creates a Vector4 object from the given floats.
  3857. */
  3858. function Vector4(x, y, z, w) {
  3859. this.x = x;
  3860. this.y = y;
  3861. this.z = z;
  3862. this.w = w;
  3863. }
  3864. /**
  3865. * Returns the string with the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.toString = function () {
  3868. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3869. };
  3870. /**
  3871. * Returns the string "Vector4".
  3872. */
  3873. Vector4.prototype.getClassName = function () {
  3874. return "Vector4";
  3875. };
  3876. /**
  3877. * Returns the Vector4 hash code.
  3878. */
  3879. Vector4.prototype.getHashCode = function () {
  3880. var hash = this.x || 0;
  3881. hash = (hash * 397) ^ (this.y || 0);
  3882. hash = (hash * 397) ^ (this.z || 0);
  3883. hash = (hash * 397) ^ (this.w || 0);
  3884. return hash;
  3885. };
  3886. // Operators
  3887. /**
  3888. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3889. */
  3890. Vector4.prototype.asArray = function () {
  3891. var result = new Array();
  3892. this.toArray(result, 0);
  3893. return result;
  3894. };
  3895. /**
  3896. * Populates the given array from the given index with the Vector4 coordinates.
  3897. * Returns the Vector4.
  3898. */
  3899. Vector4.prototype.toArray = function (array, index) {
  3900. if (index === undefined) {
  3901. index = 0;
  3902. }
  3903. array[index] = this.x;
  3904. array[index + 1] = this.y;
  3905. array[index + 2] = this.z;
  3906. array[index + 3] = this.w;
  3907. return this;
  3908. };
  3909. /**
  3910. * Adds the given vector to the current Vector4.
  3911. * Returns the updated Vector4.
  3912. */
  3913. Vector4.prototype.addInPlace = function (otherVector) {
  3914. this.x += otherVector.x;
  3915. this.y += otherVector.y;
  3916. this.z += otherVector.z;
  3917. this.w += otherVector.w;
  3918. return this;
  3919. };
  3920. /**
  3921. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3922. */
  3923. Vector4.prototype.add = function (otherVector) {
  3924. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3925. };
  3926. /**
  3927. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3928. * Returns the current Vector4.
  3929. */
  3930. Vector4.prototype.addToRef = function (otherVector, result) {
  3931. result.x = this.x + otherVector.x;
  3932. result.y = this.y + otherVector.y;
  3933. result.z = this.z + otherVector.z;
  3934. result.w = this.w + otherVector.w;
  3935. return this;
  3936. };
  3937. /**
  3938. * Subtract in place the given vector from the current Vector4.
  3939. * Returns the updated Vector4.
  3940. */
  3941. Vector4.prototype.subtractInPlace = function (otherVector) {
  3942. this.x -= otherVector.x;
  3943. this.y -= otherVector.y;
  3944. this.z -= otherVector.z;
  3945. this.w -= otherVector.w;
  3946. return this;
  3947. };
  3948. /**
  3949. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3950. */
  3951. Vector4.prototype.subtract = function (otherVector) {
  3952. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3953. };
  3954. /**
  3955. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3956. * Returns the current Vector4.
  3957. */
  3958. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3959. result.x = this.x - otherVector.x;
  3960. result.y = this.y - otherVector.y;
  3961. result.z = this.z - otherVector.z;
  3962. result.w = this.w - otherVector.w;
  3963. return this;
  3964. };
  3965. /**
  3966. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3967. */
  3968. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3969. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3970. };
  3971. /**
  3972. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3973. * Returns the current Vector4.
  3974. */
  3975. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3976. result.x = this.x - x;
  3977. result.y = this.y - y;
  3978. result.z = this.z - z;
  3979. result.w = this.w - w;
  3980. return this;
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3984. */
  3985. Vector4.prototype.negate = function () {
  3986. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3987. };
  3988. /**
  3989. * Multiplies the current Vector4 coordinates by scale (float).
  3990. * Returns the updated Vector4.
  3991. */
  3992. Vector4.prototype.scaleInPlace = function (scale) {
  3993. this.x *= scale;
  3994. this.y *= scale;
  3995. this.z *= scale;
  3996. this.w *= scale;
  3997. return this;
  3998. };
  3999. /**
  4000. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4001. */
  4002. Vector4.prototype.scale = function (scale) {
  4003. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4004. };
  4005. /**
  4006. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4007. * Returns the current Vector4.
  4008. */
  4009. Vector4.prototype.scaleToRef = function (scale, result) {
  4010. result.x = this.x * scale;
  4011. result.y = this.y * scale;
  4012. result.z = this.z * scale;
  4013. result.w = this.w * scale;
  4014. return this;
  4015. };
  4016. /**
  4017. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4018. * @param scale defines the scale factor
  4019. * @param result defines the Vector4 object where to store the result
  4020. * @returns the unmodified current Vector4
  4021. */
  4022. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4023. result.x += this.x * scale;
  4024. result.y += this.y * scale;
  4025. result.z += this.z * scale;
  4026. result.w += this.w * scale;
  4027. return this;
  4028. };
  4029. /**
  4030. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4031. */
  4032. Vector4.prototype.equals = function (otherVector) {
  4033. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4034. };
  4035. /**
  4036. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4037. */
  4038. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4039. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4040. return otherVector
  4041. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4042. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4043. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4044. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4045. };
  4046. /**
  4047. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4048. */
  4049. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4050. return this.x === x && this.y === y && this.z === z && this.w === w;
  4051. };
  4052. /**
  4053. * Multiplies in place the current Vector4 by the given one.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4057. this.x *= otherVector.x;
  4058. this.y *= otherVector.y;
  4059. this.z *= otherVector.z;
  4060. this.w *= otherVector.w;
  4061. return this;
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4065. */
  4066. Vector4.prototype.multiply = function (otherVector) {
  4067. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4074. result.x = this.x * otherVector.x;
  4075. result.y = this.y * otherVector.y;
  4076. result.z = this.z * otherVector.z;
  4077. result.w = this.w * otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4082. */
  4083. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4084. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4085. };
  4086. /**
  4087. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4088. */
  4089. Vector4.prototype.divide = function (otherVector) {
  4090. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4091. };
  4092. /**
  4093. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4094. * Returns the current Vector4.
  4095. */
  4096. Vector4.prototype.divideToRef = function (otherVector, result) {
  4097. result.x = this.x / otherVector.x;
  4098. result.y = this.y / otherVector.y;
  4099. result.z = this.z / otherVector.z;
  4100. result.w = this.w / otherVector.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Divides the current Vector3 coordinates by the given ones.
  4105. * @returns the updated Vector3.
  4106. */
  4107. Vector4.prototype.divideInPlace = function (otherVector) {
  4108. return this.divideToRef(otherVector, this);
  4109. };
  4110. /**
  4111. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4112. * @param other defines the second operand
  4113. * @returns the current updated Vector4
  4114. */
  4115. Vector4.prototype.minimizeInPlace = function (other) {
  4116. if (other.x < this.x)
  4117. this.x = other.x;
  4118. if (other.y < this.y)
  4119. this.y = other.y;
  4120. if (other.z < this.z)
  4121. this.z = other.z;
  4122. if (other.w < this.w)
  4123. this.w = other.w;
  4124. return this;
  4125. };
  4126. /**
  4127. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4128. * @param other defines the second operand
  4129. * @returns the current updated Vector4
  4130. */
  4131. Vector4.prototype.maximizeInPlace = function (other) {
  4132. if (other.x > this.x)
  4133. this.x = other.x;
  4134. if (other.y > this.y)
  4135. this.y = other.y;
  4136. if (other.z > this.z)
  4137. this.z = other.z;
  4138. if (other.w > this.w)
  4139. this.w = other.w;
  4140. return this;
  4141. };
  4142. // Properties
  4143. /**
  4144. * Returns the Vector4 length (float).
  4145. */
  4146. Vector4.prototype.length = function () {
  4147. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4148. };
  4149. /**
  4150. * Returns the Vector4 squared length (float).
  4151. */
  4152. Vector4.prototype.lengthSquared = function () {
  4153. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4154. };
  4155. // Methods
  4156. /**
  4157. * Normalizes in place the Vector4.
  4158. * Returns the updated Vector4.
  4159. */
  4160. Vector4.prototype.normalize = function () {
  4161. var len = this.length();
  4162. if (len === 0)
  4163. return this;
  4164. var num = 1.0 / len;
  4165. this.x *= num;
  4166. this.y *= num;
  4167. this.z *= num;
  4168. this.w *= num;
  4169. return this;
  4170. };
  4171. /**
  4172. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4173. */
  4174. Vector4.prototype.toVector3 = function () {
  4175. return new Vector3(this.x, this.y, this.z);
  4176. };
  4177. /**
  4178. * Returns a new Vector4 copied from the current one.
  4179. */
  4180. Vector4.prototype.clone = function () {
  4181. return new Vector4(this.x, this.y, this.z, this.w);
  4182. };
  4183. /**
  4184. * Updates the current Vector4 with the given one coordinates.
  4185. * Returns the updated Vector4.
  4186. */
  4187. Vector4.prototype.copyFrom = function (source) {
  4188. this.x = source.x;
  4189. this.y = source.y;
  4190. this.z = source.z;
  4191. this.w = source.w;
  4192. return this;
  4193. };
  4194. /**
  4195. * Updates the current Vector4 coordinates with the given floats.
  4196. * Returns the updated Vector4.
  4197. */
  4198. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4199. this.x = x;
  4200. this.y = y;
  4201. this.z = z;
  4202. this.w = w;
  4203. return this;
  4204. };
  4205. /**
  4206. * Updates the current Vector4 coordinates with the given floats.
  4207. * Returns the updated Vector4.
  4208. */
  4209. Vector4.prototype.set = function (x, y, z, w) {
  4210. return this.copyFromFloats(x, y, z, w);
  4211. };
  4212. // Statics
  4213. /**
  4214. * Returns a new Vector4 set from the starting index of the given array.
  4215. */
  4216. Vector4.FromArray = function (array, offset) {
  4217. if (!offset) {
  4218. offset = 0;
  4219. }
  4220. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given array.
  4224. */
  4225. Vector4.FromArrayToRef = function (array, offset, result) {
  4226. result.x = array[offset];
  4227. result.y = array[offset + 1];
  4228. result.z = array[offset + 2];
  4229. result.w = array[offset + 3];
  4230. };
  4231. /**
  4232. * Updates the given vector "result" from the starting index of the given Float32Array.
  4233. */
  4234. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4235. Vector4.FromArrayToRef(array, offset, result);
  4236. };
  4237. /**
  4238. * Updates the given vector "result" coordinates from the given floats.
  4239. */
  4240. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4241. result.x = x;
  4242. result.y = y;
  4243. result.z = z;
  4244. result.w = w;
  4245. };
  4246. /**
  4247. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4248. */
  4249. Vector4.Zero = function () {
  4250. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4251. };
  4252. /**
  4253. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4254. */
  4255. Vector4.One = function () {
  4256. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4257. };
  4258. /**
  4259. * Returns a new normalized Vector4 from the given one.
  4260. */
  4261. Vector4.Normalize = function (vector) {
  4262. var result = Vector4.Zero();
  4263. Vector4.NormalizeToRef(vector, result);
  4264. return result;
  4265. };
  4266. /**
  4267. * Updates the given vector "result" from the normalization of the given one.
  4268. */
  4269. Vector4.NormalizeToRef = function (vector, result) {
  4270. result.copyFrom(vector);
  4271. result.normalize();
  4272. };
  4273. Vector4.Minimize = function (left, right) {
  4274. var min = left.clone();
  4275. min.minimizeInPlace(right);
  4276. return min;
  4277. };
  4278. Vector4.Maximize = function (left, right) {
  4279. var max = left.clone();
  4280. max.maximizeInPlace(right);
  4281. return max;
  4282. };
  4283. /**
  4284. * Returns the distance (float) between the vectors "value1" and "value2".
  4285. */
  4286. Vector4.Distance = function (value1, value2) {
  4287. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4288. };
  4289. /**
  4290. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4291. */
  4292. Vector4.DistanceSquared = function (value1, value2) {
  4293. var x = value1.x - value2.x;
  4294. var y = value1.y - value2.y;
  4295. var z = value1.z - value2.z;
  4296. var w = value1.w - value2.w;
  4297. return (x * x) + (y * y) + (z * z) + (w * w);
  4298. };
  4299. /**
  4300. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4301. */
  4302. Vector4.Center = function (value1, value2) {
  4303. var center = value1.add(value2);
  4304. center.scaleInPlace(0.5);
  4305. return center;
  4306. };
  4307. /**
  4308. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormal = function (vector, transformation) {
  4312. var result = Vector4.Zero();
  4313. Vector4.TransformNormalToRef(vector, transformation, result);
  4314. return result;
  4315. };
  4316. /**
  4317. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4318. * This methods computes transformed normalized direction vectors only.
  4319. */
  4320. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4321. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4322. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4323. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4324. result.x = x;
  4325. result.y = y;
  4326. result.z = z;
  4327. result.w = vector.w;
  4328. };
  4329. /**
  4330. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4331. * This methods computes transformed normalized direction vectors only.
  4332. */
  4333. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4334. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4335. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4336. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4337. result.w = w;
  4338. };
  4339. return Vector4;
  4340. }());
  4341. BABYLON.Vector4 = Vector4;
  4342. var Size = /** @class */ (function () {
  4343. /**
  4344. * Creates a Size object from the given width and height (floats).
  4345. */
  4346. function Size(width, height) {
  4347. this.width = width;
  4348. this.height = height;
  4349. }
  4350. // Returns a string with the Size width and height.
  4351. Size.prototype.toString = function () {
  4352. return "{W: " + this.width + ", H: " + this.height + "}";
  4353. };
  4354. /**
  4355. * Returns the string "Size"
  4356. */
  4357. Size.prototype.getClassName = function () {
  4358. return "Size";
  4359. };
  4360. /**
  4361. * Returns the Size hash code.
  4362. */
  4363. Size.prototype.getHashCode = function () {
  4364. var hash = this.width || 0;
  4365. hash = (hash * 397) ^ (this.height || 0);
  4366. return hash;
  4367. };
  4368. /**
  4369. * Updates the current size from the given one.
  4370. * Returns the updated Size.
  4371. */
  4372. Size.prototype.copyFrom = function (src) {
  4373. this.width = src.width;
  4374. this.height = src.height;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.copyFromFloats = function (width, height) {
  4381. this.width = width;
  4382. this.height = height;
  4383. return this;
  4384. };
  4385. /**
  4386. * Updates in place the current Size from the given floats.
  4387. * Returns the updated Size.
  4388. */
  4389. Size.prototype.set = function (width, height) {
  4390. return this.copyFromFloats(width, height);
  4391. };
  4392. /**
  4393. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4394. */
  4395. Size.prototype.multiplyByFloats = function (w, h) {
  4396. return new Size(this.width * w, this.height * h);
  4397. };
  4398. /**
  4399. * Returns a new Size copied from the given one.
  4400. */
  4401. Size.prototype.clone = function () {
  4402. return new Size(this.width, this.height);
  4403. };
  4404. /**
  4405. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4406. */
  4407. Size.prototype.equals = function (other) {
  4408. if (!other) {
  4409. return false;
  4410. }
  4411. return (this.width === other.width) && (this.height === other.height);
  4412. };
  4413. Object.defineProperty(Size.prototype, "surface", {
  4414. /**
  4415. * Returns the surface of the Size : width * height (float).
  4416. */
  4417. get: function () {
  4418. return this.width * this.height;
  4419. },
  4420. enumerable: true,
  4421. configurable: true
  4422. });
  4423. /**
  4424. * Returns a new Size set to (0.0, 0.0)
  4425. */
  4426. Size.Zero = function () {
  4427. return new Size(0.0, 0.0);
  4428. };
  4429. /**
  4430. * Returns a new Size set as the addition result of the current Size and the given one.
  4431. */
  4432. Size.prototype.add = function (otherSize) {
  4433. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4434. return r;
  4435. };
  4436. /**
  4437. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4438. */
  4439. Size.prototype.subtract = function (otherSize) {
  4440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4441. return r;
  4442. };
  4443. /**
  4444. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4445. */
  4446. Size.Lerp = function (start, end, amount) {
  4447. var w = start.width + ((end.width - start.width) * amount);
  4448. var h = start.height + ((end.height - start.height) * amount);
  4449. return new Size(w, h);
  4450. };
  4451. return Size;
  4452. }());
  4453. BABYLON.Size = Size;
  4454. /**
  4455. * Class used to store quaternion data
  4456. * @see https://en.wikipedia.org/wiki/Quaternion
  4457. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4458. */
  4459. var Quaternion = /** @class */ (function () {
  4460. /**
  4461. * Creates a new Quaternion from the given floats
  4462. * @param x defines the first component (0 by default)
  4463. * @param y defines the second component (0 by default)
  4464. * @param z defines the third component (0 by default)
  4465. * @param w defines the fourth component (1.0 by default)
  4466. */
  4467. function Quaternion(
  4468. /** defines the first component (0 by default) */
  4469. x,
  4470. /** defines the second component (0 by default) */
  4471. y,
  4472. /** defines the third component (0 by default) */
  4473. z,
  4474. /** defines the fourth component (1.0 by default) */
  4475. w) {
  4476. if (x === void 0) { x = 0.0; }
  4477. if (y === void 0) { y = 0.0; }
  4478. if (z === void 0) { z = 0.0; }
  4479. if (w === void 0) { w = 1.0; }
  4480. this.x = x;
  4481. this.y = y;
  4482. this.z = z;
  4483. this.w = w;
  4484. }
  4485. /**
  4486. * Gets a string representation for the current quaternion
  4487. * @returns a string with the Quaternion coordinates
  4488. */
  4489. Quaternion.prototype.toString = function () {
  4490. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4491. };
  4492. /**
  4493. * Gets the class name of the quaternion
  4494. * @returns the string "Quaternion"
  4495. */
  4496. Quaternion.prototype.getClassName = function () {
  4497. return "Quaternion";
  4498. };
  4499. /**
  4500. * Gets a hash code for this quaternion
  4501. * @returns the quaternion hash code
  4502. */
  4503. Quaternion.prototype.getHashCode = function () {
  4504. var hash = this.x || 0;
  4505. hash = (hash * 397) ^ (this.y || 0);
  4506. hash = (hash * 397) ^ (this.z || 0);
  4507. hash = (hash * 397) ^ (this.w || 0);
  4508. return hash;
  4509. };
  4510. /**
  4511. * Copy the quaternion to an array
  4512. * @returns a new array populated with 4 elements from the quaternion coordinates
  4513. */
  4514. Quaternion.prototype.asArray = function () {
  4515. return [this.x, this.y, this.z, this.w];
  4516. };
  4517. /**
  4518. * Check if two quaternions are equals
  4519. * @param otherQuaternion defines the second operand
  4520. * @return true if the current quaternion and the given one coordinates are strictly equals
  4521. */
  4522. Quaternion.prototype.equals = function (otherQuaternion) {
  4523. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4524. };
  4525. /**
  4526. * Clone the current quaternion
  4527. * @returns a new quaternion copied from the current one
  4528. */
  4529. Quaternion.prototype.clone = function () {
  4530. return new Quaternion(this.x, this.y, this.z, this.w);
  4531. };
  4532. /**
  4533. * Copy a quaternion to the current one
  4534. * @param other defines the other quaternion
  4535. * @returns the updated current quaternion
  4536. */
  4537. Quaternion.prototype.copyFrom = function (other) {
  4538. this.x = other.x;
  4539. this.y = other.y;
  4540. this.z = other.z;
  4541. this.w = other.w;
  4542. return this;
  4543. };
  4544. /**
  4545. * Updates the current quaternion with the given float coordinates
  4546. * @param x defines the x coordinate
  4547. * @param y defines the y coordinate
  4548. * @param z defines the z coordinate
  4549. * @param w defines the w coordinate
  4550. * @returns the updated current quaternion
  4551. */
  4552. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4553. this.x = x;
  4554. this.y = y;
  4555. this.z = z;
  4556. this.w = w;
  4557. return this;
  4558. };
  4559. /**
  4560. * Updates the current quaternion from the given float coordinates
  4561. * @param x defines the x coordinate
  4562. * @param y defines the y coordinate
  4563. * @param z defines the z coordinate
  4564. * @param w defines the w coordinate
  4565. * @returns the updated current quaternion
  4566. */
  4567. Quaternion.prototype.set = function (x, y, z, w) {
  4568. return this.copyFromFloats(x, y, z, w);
  4569. };
  4570. /**
  4571. * Adds two quaternions
  4572. * @param other defines the second operand
  4573. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4574. */
  4575. Quaternion.prototype.add = function (other) {
  4576. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4577. };
  4578. /**
  4579. * Add a quaternion to the current one
  4580. * @param other defines the quaternion to add
  4581. * @returns the current quaternion
  4582. */
  4583. Quaternion.prototype.addInPlace = function (other) {
  4584. this.x += other.x;
  4585. this.y += other.y;
  4586. this.z += other.z;
  4587. this.w += other.w;
  4588. return this;
  4589. };
  4590. /**
  4591. * Subtract two quaternions
  4592. * @param other defines the second operand
  4593. * @returns a new quaternion as the subtraction result of the given one from the current one
  4594. */
  4595. Quaternion.prototype.subtract = function (other) {
  4596. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4597. };
  4598. /**
  4599. * Multiplies the current quaternion by a scale factor
  4600. * @param value defines the scale factor
  4601. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4602. */
  4603. Quaternion.prototype.scale = function (value) {
  4604. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4605. };
  4606. /**
  4607. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4608. * @param scale defines the scale factor
  4609. * @param result defines the Quaternion object where to store the result
  4610. * @returns the unmodified current quaternion
  4611. */
  4612. Quaternion.prototype.scaleToRef = function (scale, result) {
  4613. result.x = this.x * scale;
  4614. result.y = this.y * scale;
  4615. result.z = this.z * scale;
  4616. result.w = this.w * scale;
  4617. return this;
  4618. };
  4619. /**
  4620. * Multiplies in place the current quaternion by a scale factor
  4621. * @param value defines the scale factor
  4622. * @returns the current modified quaternion
  4623. */
  4624. Quaternion.prototype.scaleInPlace = function (value) {
  4625. this.x *= value;
  4626. this.y *= value;
  4627. this.z *= value;
  4628. this.w *= value;
  4629. return this;
  4630. };
  4631. /**
  4632. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4633. * @param scale defines the scale factor
  4634. * @param result defines the Quaternion object where to store the result
  4635. * @returns the unmodified current quaternion
  4636. */
  4637. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4638. result.x += this.x * scale;
  4639. result.y += this.y * scale;
  4640. result.z += this.z * scale;
  4641. result.w += this.w * scale;
  4642. return this;
  4643. };
  4644. /**
  4645. * Multiplies two quaternions
  4646. * @param q1 defines the second operand
  4647. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4648. */
  4649. Quaternion.prototype.multiply = function (q1) {
  4650. var result = new Quaternion(0, 0, 0, 1.0);
  4651. this.multiplyToRef(q1, result);
  4652. return result;
  4653. };
  4654. /**
  4655. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4656. * @param q1 defines the second operand
  4657. * @param result defines the target quaternion
  4658. * @returns the current quaternion
  4659. */
  4660. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4661. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4662. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4663. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4664. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4665. result.copyFromFloats(x, y, z, w);
  4666. return this;
  4667. };
  4668. /**
  4669. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4670. * @param q1 defines the second operand
  4671. * @returns the currentupdated quaternion
  4672. */
  4673. Quaternion.prototype.multiplyInPlace = function (q1) {
  4674. this.multiplyToRef(q1, this);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4679. * @param ref defines the target quaternion
  4680. * @returns the current quaternion
  4681. */
  4682. Quaternion.prototype.conjugateToRef = function (ref) {
  4683. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4684. return this;
  4685. };
  4686. /**
  4687. * Conjugates in place (1-q) the current quaternion
  4688. * @returns the current updated quaternion
  4689. */
  4690. Quaternion.prototype.conjugateInPlace = function () {
  4691. this.x *= -1;
  4692. this.y *= -1;
  4693. this.z *= -1;
  4694. return this;
  4695. };
  4696. /**
  4697. * Conjugates in place (1-q) the current quaternion
  4698. * @returns a new quaternion
  4699. */
  4700. Quaternion.prototype.conjugate = function () {
  4701. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4702. return result;
  4703. };
  4704. /**
  4705. * Gets length of current quaternion
  4706. * @returns the quaternion length (float)
  4707. */
  4708. Quaternion.prototype.length = function () {
  4709. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4710. };
  4711. /**
  4712. * Normalize in place the current quaternion
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.normalize = function () {
  4716. var length = 1.0 / this.length();
  4717. this.x *= length;
  4718. this.y *= length;
  4719. this.z *= length;
  4720. this.w *= length;
  4721. return this;
  4722. };
  4723. /**
  4724. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4725. * @param order is a reserved parameter and is ignore for now
  4726. * @returns a new Vector3 containing the Euler angles
  4727. */
  4728. Quaternion.prototype.toEulerAngles = function (order) {
  4729. if (order === void 0) { order = "YZX"; }
  4730. var result = Vector3.Zero();
  4731. this.toEulerAnglesToRef(result, order);
  4732. return result;
  4733. };
  4734. /**
  4735. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4736. * @param result defines the vector which will be filled with the Euler angles
  4737. * @param order is a reserved parameter and is ignore for now
  4738. * @returns the current unchanged quaternion
  4739. */
  4740. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4741. if (order === void 0) { order = "YZX"; }
  4742. var qz = this.z;
  4743. var qx = this.x;
  4744. var qy = this.y;
  4745. var qw = this.w;
  4746. var sqw = qw * qw;
  4747. var sqz = qz * qz;
  4748. var sqx = qx * qx;
  4749. var sqy = qy * qy;
  4750. var zAxisY = qy * qz - qx * qw;
  4751. var limit = .4999999;
  4752. if (zAxisY < -limit) {
  4753. result.y = 2 * Math.atan2(qy, qw);
  4754. result.x = Math.PI / 2;
  4755. result.z = 0;
  4756. }
  4757. else if (zAxisY > limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = -Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else {
  4763. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4764. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4765. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4766. }
  4767. return this;
  4768. };
  4769. /**
  4770. * Updates the given rotation matrix with the current quaternion values
  4771. * @param result defines the target matrix
  4772. * @returns the current unchanged quaternion
  4773. */
  4774. Quaternion.prototype.toRotationMatrix = function (result) {
  4775. var xx = this.x * this.x;
  4776. var yy = this.y * this.y;
  4777. var zz = this.z * this.z;
  4778. var xy = this.x * this.y;
  4779. var zw = this.z * this.w;
  4780. var zx = this.z * this.x;
  4781. var yw = this.y * this.w;
  4782. var yz = this.y * this.z;
  4783. var xw = this.x * this.w;
  4784. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4785. result.m[1] = 2.0 * (xy + zw);
  4786. result.m[2] = 2.0 * (zx - yw);
  4787. result.m[3] = 0;
  4788. result.m[4] = 2.0 * (xy - zw);
  4789. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4790. result.m[6] = 2.0 * (yz + xw);
  4791. result.m[7] = 0;
  4792. result.m[8] = 2.0 * (zx + yw);
  4793. result.m[9] = 2.0 * (yz - xw);
  4794. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4795. result.m[11] = 0;
  4796. result.m[12] = 0;
  4797. result.m[13] = 0;
  4798. result.m[14] = 0;
  4799. result.m[15] = 1.0;
  4800. result._markAsUpdated();
  4801. return this;
  4802. };
  4803. /**
  4804. * Updates the current quaternion from the given rotation matrix values
  4805. * @param matrix defines the source matrix
  4806. * @returns the current updated quaternion
  4807. */
  4808. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4809. Quaternion.FromRotationMatrixToRef(matrix, this);
  4810. return this;
  4811. };
  4812. // Statics
  4813. /**
  4814. * Creates a new quaternion from a rotation matrix
  4815. * @param matrix defines the source matrix
  4816. * @returns a new quaternion created from the given rotation matrix values
  4817. */
  4818. Quaternion.FromRotationMatrix = function (matrix) {
  4819. var result = new Quaternion();
  4820. Quaternion.FromRotationMatrixToRef(matrix, result);
  4821. return result;
  4822. };
  4823. /**
  4824. * Updates the given quaternion with the given rotation matrix values
  4825. * @param matrix defines the source matrix
  4826. * @param result defines the target quaternion
  4827. */
  4828. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4829. var data = matrix.m;
  4830. var m11 = data[0], m12 = data[4], m13 = data[8];
  4831. var m21 = data[1], m22 = data[5], m23 = data[9];
  4832. var m31 = data[2], m32 = data[6], m33 = data[10];
  4833. var trace = m11 + m22 + m33;
  4834. var s;
  4835. if (trace > 0) {
  4836. s = 0.5 / Math.sqrt(trace + 1.0);
  4837. result.w = 0.25 / s;
  4838. result.x = (m32 - m23) * s;
  4839. result.y = (m13 - m31) * s;
  4840. result.z = (m21 - m12) * s;
  4841. }
  4842. else if (m11 > m22 && m11 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4844. result.w = (m32 - m23) / s;
  4845. result.x = 0.25 * s;
  4846. result.y = (m12 + m21) / s;
  4847. result.z = (m13 + m31) / s;
  4848. }
  4849. else if (m22 > m33) {
  4850. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4851. result.w = (m13 - m31) / s;
  4852. result.x = (m12 + m21) / s;
  4853. result.y = 0.25 * s;
  4854. result.z = (m23 + m32) / s;
  4855. }
  4856. else {
  4857. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4858. result.w = (m21 - m12) / s;
  4859. result.x = (m13 + m31) / s;
  4860. result.y = (m23 + m32) / s;
  4861. result.z = 0.25 * s;
  4862. }
  4863. };
  4864. /**
  4865. * Returns the dot product (float) between the quaternions "left" and "right"
  4866. * @param left defines the left operand
  4867. * @param right defines the right operand
  4868. * @returns the dot product
  4869. */
  4870. Quaternion.Dot = function (left, right) {
  4871. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4872. };
  4873. /**
  4874. * Checks if the two quaternions are close to each other
  4875. * @param quat0 defines the first quaternion to check
  4876. * @param quat1 defines the second quaternion to check
  4877. * @returns true if the two quaternions are close to each other
  4878. */
  4879. Quaternion.AreClose = function (quat0, quat1) {
  4880. var dot = Quaternion.Dot(quat0, quat1);
  4881. return dot >= 0;
  4882. };
  4883. /**
  4884. * Creates an empty quaternion
  4885. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4886. */
  4887. Quaternion.Zero = function () {
  4888. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4889. };
  4890. /**
  4891. * Inverse a given quaternion
  4892. * @param q defines the source quaternion
  4893. * @returns a new quaternion as the inverted current quaternion
  4894. */
  4895. Quaternion.Inverse = function (q) {
  4896. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4897. };
  4898. /**
  4899. * Creates an identity quaternion
  4900. * @returns the identity quaternion
  4901. */
  4902. Quaternion.Identity = function () {
  4903. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4904. };
  4905. /**
  4906. * Gets a boolean indicating if the given quaternion is identity
  4907. * @param quaternion defines the quaternion to check
  4908. * @returns true if the quaternion is identity
  4909. */
  4910. Quaternion.IsIdentity = function (quaternion) {
  4911. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4912. };
  4913. /**
  4914. * Creates a quaternion from a rotation around an axis
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4918. */
  4919. Quaternion.RotationAxis = function (axis, angle) {
  4920. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4921. };
  4922. /**
  4923. * Creates a rotation around an axis and stores it into the given quaternion
  4924. * @param axis defines the axis to use
  4925. * @param angle defines the angle to use
  4926. * @param result defines the target quaternion
  4927. * @returns the target quaternion
  4928. */
  4929. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4930. var sin = Math.sin(angle / 2);
  4931. axis.normalize();
  4932. result.w = Math.cos(angle / 2);
  4933. result.x = axis.x * sin;
  4934. result.y = axis.y * sin;
  4935. result.z = axis.z * sin;
  4936. return result;
  4937. };
  4938. /**
  4939. * Creates a new quaternion from data stored into an array
  4940. * @param array defines the data source
  4941. * @param offset defines the offset in the source array where the data starts
  4942. * @returns a new quaternion
  4943. */
  4944. Quaternion.FromArray = function (array, offset) {
  4945. if (!offset) {
  4946. offset = 0;
  4947. }
  4948. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4949. };
  4950. /**
  4951. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4952. * @param yaw defines the rotation around Y axis
  4953. * @param pitch defines the rotation around X axis
  4954. * @param roll defines the rotation around Z axis
  4955. * @returns the new quaternion
  4956. */
  4957. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4958. var q = new Quaternion();
  4959. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4960. return q;
  4961. };
  4962. /**
  4963. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4964. * @param yaw defines the rotation around Y axis
  4965. * @param pitch defines the rotation around X axis
  4966. * @param roll defines the rotation around Z axis
  4967. * @param result defines the target quaternion
  4968. */
  4969. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4970. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4971. var halfRoll = roll * 0.5;
  4972. var halfPitch = pitch * 0.5;
  4973. var halfYaw = yaw * 0.5;
  4974. var sinRoll = Math.sin(halfRoll);
  4975. var cosRoll = Math.cos(halfRoll);
  4976. var sinPitch = Math.sin(halfPitch);
  4977. var cosPitch = Math.cos(halfPitch);
  4978. var sinYaw = Math.sin(halfYaw);
  4979. var cosYaw = Math.cos(halfYaw);
  4980. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4981. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4982. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4983. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4984. };
  4985. /**
  4986. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4987. * @param alpha defines the rotation around first axis
  4988. * @param beta defines the rotation around second axis
  4989. * @param gamma defines the rotation around third axis
  4990. * @returns the new quaternion
  4991. */
  4992. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4993. var result = new Quaternion();
  4994. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4995. return result;
  4996. };
  4997. /**
  4998. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4999. * @param alpha defines the rotation around first axis
  5000. * @param beta defines the rotation around second axis
  5001. * @param gamma defines the rotation around third axis
  5002. * @param result defines the target quaternion
  5003. */
  5004. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5005. // Produces a quaternion from Euler angles in the z-x-z orientation
  5006. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5007. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5008. var halfBeta = beta * 0.5;
  5009. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5010. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5011. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5012. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5013. };
  5014. /**
  5015. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5016. * @param axis1 defines the first axis
  5017. * @param axis2 defines the second axis
  5018. * @param axis3 defines the third axis
  5019. * @returns the new quaternion
  5020. */
  5021. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5022. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5023. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5024. return quat;
  5025. };
  5026. /**
  5027. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5028. * @param axis1 defines the first axis
  5029. * @param axis2 defines the second axis
  5030. * @param axis3 defines the third axis
  5031. * @param ref defines the target quaternion
  5032. */
  5033. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5034. var rotMat = MathTmp.Matrix[0];
  5035. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5036. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5037. };
  5038. /**
  5039. * Interpolates between two quaternions
  5040. * @param left defines first quaternion
  5041. * @param right defines second quaternion
  5042. * @param amount defines the gradient to use
  5043. * @returns the new interpolated quaternion
  5044. */
  5045. Quaternion.Slerp = function (left, right, amount) {
  5046. var result = Quaternion.Identity();
  5047. Quaternion.SlerpToRef(left, right, amount, result);
  5048. return result;
  5049. };
  5050. /**
  5051. * Interpolates between two quaternions and stores it into a target quaternion
  5052. * @param left defines first quaternion
  5053. * @param right defines second quaternion
  5054. * @param amount defines the gradient to use
  5055. * @param result defines the target quaternion
  5056. */
  5057. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5058. var num2;
  5059. var num3;
  5060. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5061. var flag = false;
  5062. if (num4 < 0) {
  5063. flag = true;
  5064. num4 = -num4;
  5065. }
  5066. if (num4 > 0.999999) {
  5067. num3 = 1 - amount;
  5068. num2 = flag ? -amount : amount;
  5069. }
  5070. else {
  5071. var num5 = Math.acos(num4);
  5072. var num6 = (1.0 / Math.sin(num5));
  5073. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5074. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5075. }
  5076. result.x = (num3 * left.x) + (num2 * right.x);
  5077. result.y = (num3 * left.y) + (num2 * right.y);
  5078. result.z = (num3 * left.z) + (num2 * right.z);
  5079. result.w = (num3 * left.w) + (num2 * right.w);
  5080. };
  5081. /**
  5082. * Interpolate between two quaternions using Hermite interpolation
  5083. * @param value1 defines first quaternion
  5084. * @param tangent1 defines the incoming tangent
  5085. * @param value2 defines second quaternion
  5086. * @param tangent2 defines the outgoing tangent
  5087. * @param amount defines the target quaternion
  5088. * @returns the new interpolated quaternion
  5089. */
  5090. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5091. var squared = amount * amount;
  5092. var cubed = amount * squared;
  5093. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5094. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5095. var part3 = (cubed - (2.0 * squared)) + amount;
  5096. var part4 = cubed - squared;
  5097. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5098. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5099. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5100. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5101. return new Quaternion(x, y, z, w);
  5102. };
  5103. return Quaternion;
  5104. }());
  5105. BABYLON.Quaternion = Quaternion;
  5106. /**
  5107. * Class used to store matrix data (4x4)
  5108. */
  5109. var Matrix = /** @class */ (function () {
  5110. /**
  5111. * Creates an empty matrix (filled with zeros)
  5112. */
  5113. function Matrix() {
  5114. this._isIdentity = false;
  5115. this._isIdentityDirty = true;
  5116. /**
  5117. * Gets or sets the internal data of the matrix
  5118. */
  5119. this.m = new Float32Array(16);
  5120. this._markAsUpdated();
  5121. }
  5122. /** @hidden */
  5123. Matrix.prototype._markAsUpdated = function () {
  5124. this.updateFlag = Matrix._updateFlagSeed++;
  5125. this._isIdentityDirty = true;
  5126. };
  5127. // Properties
  5128. /**
  5129. * Check if the current matrix is indentity
  5130. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5131. * @returns true is the matrix is the identity matrix
  5132. */
  5133. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5134. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5135. if (this._isIdentityDirty) {
  5136. this._isIdentityDirty = false;
  5137. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5138. this._isIdentity = false;
  5139. }
  5140. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5141. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5142. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5143. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5144. this._isIdentity = false;
  5145. }
  5146. else {
  5147. this._isIdentity = true;
  5148. }
  5149. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5150. this._isIdentity = false;
  5151. }
  5152. }
  5153. return this._isIdentity;
  5154. };
  5155. /**
  5156. * Gets the determinant of the matrix
  5157. * @returns the matrix determinant
  5158. */
  5159. Matrix.prototype.determinant = function () {
  5160. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5161. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5162. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5163. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5164. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5165. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5166. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5167. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5168. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5169. };
  5170. // Methods
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array
  5174. */
  5175. Matrix.prototype.toArray = function () {
  5176. return this.m;
  5177. };
  5178. /**
  5179. * Returns the matrix as a Float32Array
  5180. * @returns the matrix underlying array.
  5181. */
  5182. Matrix.prototype.asArray = function () {
  5183. return this.toArray();
  5184. };
  5185. /**
  5186. * Inverts the current matrix in place
  5187. * @returns the current inverted matrix
  5188. */
  5189. Matrix.prototype.invert = function () {
  5190. this.invertToRef(this);
  5191. return this;
  5192. };
  5193. /**
  5194. * Sets all the matrix elements to zero
  5195. * @returns the current matrix
  5196. */
  5197. Matrix.prototype.reset = function () {
  5198. for (var index = 0; index < 16; index++) {
  5199. this.m[index] = 0.0;
  5200. }
  5201. this._markAsUpdated();
  5202. return this;
  5203. };
  5204. /**
  5205. * Adds the current matrix with a second one
  5206. * @param other defines the matrix to add
  5207. * @returns a new matrix as the addition of the current matrix and the given one
  5208. */
  5209. Matrix.prototype.add = function (other) {
  5210. var result = new Matrix();
  5211. this.addToRef(other, result);
  5212. return result;
  5213. };
  5214. /**
  5215. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5216. * @param other defines the matrix to add
  5217. * @param result defines the target matrix
  5218. * @returns the current matrix
  5219. */
  5220. Matrix.prototype.addToRef = function (other, result) {
  5221. for (var index = 0; index < 16; index++) {
  5222. result.m[index] = this.m[index] + other.m[index];
  5223. }
  5224. result._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Adds in place the given matrix to the current matrix
  5229. * @param other defines the second operand
  5230. * @returns the current updated matrix
  5231. */
  5232. Matrix.prototype.addToSelf = function (other) {
  5233. for (var index = 0; index < 16; index++) {
  5234. this.m[index] += other.m[index];
  5235. }
  5236. this._markAsUpdated();
  5237. return this;
  5238. };
  5239. /**
  5240. * Sets the given matrix to the current inverted Matrix
  5241. * @param other defines the target matrix
  5242. * @returns the unmodified current matrix
  5243. */
  5244. Matrix.prototype.invertToRef = function (other) {
  5245. var l1 = this.m[0];
  5246. var l2 = this.m[1];
  5247. var l3 = this.m[2];
  5248. var l4 = this.m[3];
  5249. var l5 = this.m[4];
  5250. var l6 = this.m[5];
  5251. var l7 = this.m[6];
  5252. var l8 = this.m[7];
  5253. var l9 = this.m[8];
  5254. var l10 = this.m[9];
  5255. var l11 = this.m[10];
  5256. var l12 = this.m[11];
  5257. var l13 = this.m[12];
  5258. var l14 = this.m[13];
  5259. var l15 = this.m[14];
  5260. var l16 = this.m[15];
  5261. var l17 = (l11 * l16) - (l12 * l15);
  5262. var l18 = (l10 * l16) - (l12 * l14);
  5263. var l19 = (l10 * l15) - (l11 * l14);
  5264. var l20 = (l9 * l16) - (l12 * l13);
  5265. var l21 = (l9 * l15) - (l11 * l13);
  5266. var l22 = (l9 * l14) - (l10 * l13);
  5267. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5268. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5269. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5270. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5271. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5272. var l28 = (l7 * l16) - (l8 * l15);
  5273. var l29 = (l6 * l16) - (l8 * l14);
  5274. var l30 = (l6 * l15) - (l7 * l14);
  5275. var l31 = (l5 * l16) - (l8 * l13);
  5276. var l32 = (l5 * l15) - (l7 * l13);
  5277. var l33 = (l5 * l14) - (l6 * l13);
  5278. var l34 = (l7 * l12) - (l8 * l11);
  5279. var l35 = (l6 * l12) - (l8 * l10);
  5280. var l36 = (l6 * l11) - (l7 * l10);
  5281. var l37 = (l5 * l12) - (l8 * l9);
  5282. var l38 = (l5 * l11) - (l7 * l9);
  5283. var l39 = (l5 * l10) - (l6 * l9);
  5284. other.m[0] = l23 * l27;
  5285. other.m[4] = l24 * l27;
  5286. other.m[8] = l25 * l27;
  5287. other.m[12] = l26 * l27;
  5288. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5289. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5290. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5291. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5292. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5293. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5294. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5295. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5296. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5297. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5298. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5299. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5300. other._markAsUpdated();
  5301. return this;
  5302. };
  5303. /**
  5304. * Inserts the translation vector (using 3 floats) in the current matrix
  5305. * @param x defines the 1st component of the translation
  5306. * @param y defines the 2nd component of the translation
  5307. * @param z defines the 3rd component of the translation
  5308. * @returns the current updated matrix
  5309. */
  5310. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5311. this.m[12] = x;
  5312. this.m[13] = y;
  5313. this.m[14] = z;
  5314. this._markAsUpdated();
  5315. return this;
  5316. };
  5317. /**
  5318. * Inserts the translation vector in the current matrix
  5319. * @param vector3 defines the translation to insert
  5320. * @returns the current updated matrix
  5321. */
  5322. Matrix.prototype.setTranslation = function (vector3) {
  5323. this.m[12] = vector3.x;
  5324. this.m[13] = vector3.y;
  5325. this.m[14] = vector3.z;
  5326. this._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Gets the translation value of the current matrix
  5331. * @returns a new Vector3 as the extracted translation from the matrix
  5332. */
  5333. Matrix.prototype.getTranslation = function () {
  5334. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5335. };
  5336. /**
  5337. * Fill a Vector3 with the extracted translation from the matrix
  5338. * @param result defines the Vector3 where to store the translation
  5339. * @returns the current matrix
  5340. */
  5341. Matrix.prototype.getTranslationToRef = function (result) {
  5342. result.x = this.m[12];
  5343. result.y = this.m[13];
  5344. result.z = this.m[14];
  5345. return this;
  5346. };
  5347. /**
  5348. * Remove rotation and scaling part from the matrix
  5349. * @returns the updated matrix
  5350. */
  5351. Matrix.prototype.removeRotationAndScaling = function () {
  5352. this.setRowFromFloats(0, 1, 0, 0, 0);
  5353. this.setRowFromFloats(1, 0, 1, 0, 0);
  5354. this.setRowFromFloats(2, 0, 0, 1, 0);
  5355. return this;
  5356. };
  5357. /**
  5358. * Multiply two matrices
  5359. * @param other defines the second operand
  5360. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5361. */
  5362. Matrix.prototype.multiply = function (other) {
  5363. var result = new Matrix();
  5364. this.multiplyToRef(other, result);
  5365. return result;
  5366. };
  5367. /**
  5368. * Copy the current matrix from the given one
  5369. * @param other defines the source matrix
  5370. * @returns the current updated matrix
  5371. */
  5372. Matrix.prototype.copyFrom = function (other) {
  5373. for (var index = 0; index < 16; index++) {
  5374. this.m[index] = other.m[index];
  5375. }
  5376. this._markAsUpdated();
  5377. return this;
  5378. };
  5379. /**
  5380. * Populates the given array from the starting index with the current matrix values
  5381. * @param array defines the target array
  5382. * @param offset defines the offset in the target array where to start storing values
  5383. * @returns the current matrix
  5384. */
  5385. Matrix.prototype.copyToArray = function (array, offset) {
  5386. if (offset === void 0) { offset = 0; }
  5387. for (var index = 0; index < 16; index++) {
  5388. array[offset + index] = this.m[index];
  5389. }
  5390. return this;
  5391. };
  5392. /**
  5393. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5394. * @param other defines the second operand
  5395. * @param result defines the matrix where to store the multiplication
  5396. * @returns the current matrix
  5397. */
  5398. Matrix.prototype.multiplyToRef = function (other, result) {
  5399. this.multiplyToArray(other, result.m, 0);
  5400. result._markAsUpdated();
  5401. return this;
  5402. };
  5403. /**
  5404. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5405. * @param other defines the second operand
  5406. * @param result defines the array where to store the multiplication
  5407. * @param offset defines the offset in the target array where to start storing values
  5408. * @returns the current matrix
  5409. */
  5410. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5411. var tm0 = this.m[0];
  5412. var tm1 = this.m[1];
  5413. var tm2 = this.m[2];
  5414. var tm3 = this.m[3];
  5415. var tm4 = this.m[4];
  5416. var tm5 = this.m[5];
  5417. var tm6 = this.m[6];
  5418. var tm7 = this.m[7];
  5419. var tm8 = this.m[8];
  5420. var tm9 = this.m[9];
  5421. var tm10 = this.m[10];
  5422. var tm11 = this.m[11];
  5423. var tm12 = this.m[12];
  5424. var tm13 = this.m[13];
  5425. var tm14 = this.m[14];
  5426. var tm15 = this.m[15];
  5427. var om0 = other.m[0];
  5428. var om1 = other.m[1];
  5429. var om2 = other.m[2];
  5430. var om3 = other.m[3];
  5431. var om4 = other.m[4];
  5432. var om5 = other.m[5];
  5433. var om6 = other.m[6];
  5434. var om7 = other.m[7];
  5435. var om8 = other.m[8];
  5436. var om9 = other.m[9];
  5437. var om10 = other.m[10];
  5438. var om11 = other.m[11];
  5439. var om12 = other.m[12];
  5440. var om13 = other.m[13];
  5441. var om14 = other.m[14];
  5442. var om15 = other.m[15];
  5443. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5444. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5445. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5446. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5447. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5448. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5449. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5450. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5451. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5452. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5453. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5454. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5455. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5456. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5457. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5458. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5459. return this;
  5460. };
  5461. /**
  5462. * Check equality between this matrix and a second one
  5463. * @param value defines the second matrix to compare
  5464. * @returns true is the current matrix and the given one values are strictly equal
  5465. */
  5466. Matrix.prototype.equals = function (value) {
  5467. return value &&
  5468. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5469. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5470. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5471. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5472. };
  5473. /**
  5474. * Clone the current matrix
  5475. * @returns a new matrix from the current matrix
  5476. */
  5477. Matrix.prototype.clone = function () {
  5478. 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]);
  5479. };
  5480. /**
  5481. * Returns the name of the current matrix class
  5482. * @returns the string "Matrix"
  5483. */
  5484. Matrix.prototype.getClassName = function () {
  5485. return "Matrix";
  5486. };
  5487. /**
  5488. * Gets the hash code of the current matrix
  5489. * @returns the hash code
  5490. */
  5491. Matrix.prototype.getHashCode = function () {
  5492. var hash = this.m[0] || 0;
  5493. for (var i = 1; i < 16; i++) {
  5494. hash = (hash * 397) ^ (this.m[i] || 0);
  5495. }
  5496. return hash;
  5497. };
  5498. /**
  5499. * Decomposes the current Matrix into a translation, rotation and scaling components
  5500. * @param scale defines the scale vector3 given as a reference to update
  5501. * @param rotation defines the rotation quaternion given as a reference to update
  5502. * @param translation defines the translation vector3 given as a reference to update
  5503. * @returns true if operation was successful
  5504. */
  5505. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5506. if (translation) {
  5507. translation.x = this.m[12];
  5508. translation.y = this.m[13];
  5509. translation.z = this.m[14];
  5510. }
  5511. scale = scale || MathTmp.Vector3[0];
  5512. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5513. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5514. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5515. if (this.determinant() <= 0) {
  5516. scale.y *= -1;
  5517. }
  5518. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5519. if (rotation) {
  5520. rotation.x = 0;
  5521. rotation.y = 0;
  5522. rotation.z = 0;
  5523. rotation.w = 1;
  5524. }
  5525. return false;
  5526. }
  5527. if (rotation) {
  5528. 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]);
  5529. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5530. }
  5531. return true;
  5532. };
  5533. /**
  5534. * Gets specific row of the matrix
  5535. * @param index defines the number of the row to get
  5536. * @returns the index-th row of the current matrix as a new Vector4
  5537. */
  5538. Matrix.prototype.getRow = function (index) {
  5539. if (index < 0 || index > 3) {
  5540. return null;
  5541. }
  5542. var i = index * 4;
  5543. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5544. };
  5545. /**
  5546. * Sets the index-th row of the current matrix to the vector4 values
  5547. * @param index defines the number of the row to set
  5548. * @param row defines the target vector4
  5549. * @returns the updated current matrix
  5550. */
  5551. Matrix.prototype.setRow = function (index, row) {
  5552. if (index < 0 || index > 3) {
  5553. return this;
  5554. }
  5555. var i = index * 4;
  5556. this.m[i + 0] = row.x;
  5557. this.m[i + 1] = row.y;
  5558. this.m[i + 2] = row.z;
  5559. this.m[i + 3] = row.w;
  5560. this._markAsUpdated();
  5561. return this;
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix
  5565. * @returns the new transposed matrix
  5566. */
  5567. Matrix.prototype.transpose = function () {
  5568. return Matrix.Transpose(this);
  5569. };
  5570. /**
  5571. * Compute the transpose of the matrix and store it in a given matrix
  5572. * @param result defines the target matrix
  5573. * @returns the current matrix
  5574. */
  5575. Matrix.prototype.transposeToRef = function (result) {
  5576. Matrix.TransposeToRef(this, result);
  5577. return this;
  5578. };
  5579. /**
  5580. * Sets the index-th row of the current matrix with the given 4 x float values
  5581. * @param index defines the row index
  5582. * @param x defines the x component to set
  5583. * @param y defines the y component to set
  5584. * @param z defines the z component to set
  5585. * @param w defines the w component to set
  5586. * @returns the updated current matrix
  5587. */
  5588. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5589. if (index < 0 || index > 3) {
  5590. return this;
  5591. }
  5592. var i = index * 4;
  5593. this.m[i + 0] = x;
  5594. this.m[i + 1] = y;
  5595. this.m[i + 2] = z;
  5596. this.m[i + 3] = w;
  5597. this._markAsUpdated();
  5598. return this;
  5599. };
  5600. /**
  5601. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5602. * @param scale defines the scale factor
  5603. * @returns a new matrix
  5604. */
  5605. Matrix.prototype.scale = function (scale) {
  5606. var result = new Matrix();
  5607. this.scaleToRef(scale, result);
  5608. return result;
  5609. };
  5610. /**
  5611. * Scale the current matrix values by a factor to a given result matrix
  5612. * @param scale defines the scale factor
  5613. * @param result defines the matrix to store the result
  5614. * @returns the current matrix
  5615. */
  5616. Matrix.prototype.scaleToRef = function (scale, result) {
  5617. for (var index = 0; index < 16; index++) {
  5618. result.m[index] = this.m[index] * scale;
  5619. }
  5620. result._markAsUpdated();
  5621. return this;
  5622. };
  5623. /**
  5624. * Scale the current matrix values by a factor and add the result to a given matrix
  5625. * @param scale defines the scale factor
  5626. * @param result defines the Matrix to store the result
  5627. * @returns the current matrix
  5628. */
  5629. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5630. for (var index = 0; index < 16; index++) {
  5631. result.m[index] += this.m[index] * scale;
  5632. }
  5633. result._markAsUpdated();
  5634. return this;
  5635. };
  5636. /**
  5637. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5638. * @param ref matrix to store the result
  5639. */
  5640. Matrix.prototype.toNormalMatrix = function (ref) {
  5641. this.invertToRef(ref);
  5642. ref.transpose();
  5643. var m = ref.m;
  5644. 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);
  5645. };
  5646. /**
  5647. * Gets only rotation part of the current matrix
  5648. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5649. */
  5650. Matrix.prototype.getRotationMatrix = function () {
  5651. var result = Matrix.Identity();
  5652. this.getRotationMatrixToRef(result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5657. * @param result defines the target matrix to store data to
  5658. * @returns the current matrix
  5659. */
  5660. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5661. var m = this.m;
  5662. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5663. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5664. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5665. if (this.determinant() <= 0) {
  5666. sy *= -1;
  5667. }
  5668. if (sx === 0 || sy === 0 || sz === 0) {
  5669. Matrix.IdentityToRef(result);
  5670. }
  5671. else {
  5672. 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);
  5673. }
  5674. return this;
  5675. };
  5676. // Statics
  5677. /**
  5678. * Creates a matrix from an array
  5679. * @param array defines the source array
  5680. * @param offset defines an offset in the source array
  5681. * @returns a new Matrix set from the starting index of the given array
  5682. */
  5683. Matrix.FromArray = function (array, offset) {
  5684. var result = new Matrix();
  5685. if (!offset) {
  5686. offset = 0;
  5687. }
  5688. Matrix.FromArrayToRef(array, offset, result);
  5689. return result;
  5690. };
  5691. /**
  5692. * Copy the content of an array into a given matrix
  5693. * @param array defines the source array
  5694. * @param offset defines an offset in the source array
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.FromArrayToRef = function (array, offset, result) {
  5698. for (var index = 0; index < 16; index++) {
  5699. result.m[index] = array[index + offset];
  5700. }
  5701. result._markAsUpdated();
  5702. };
  5703. /**
  5704. * Stores an array into a matrix after having multiplied each component by a given factor
  5705. * @param array defines the source array
  5706. * @param offset defines the offset in the source array
  5707. * @param scale defines the scaling factor
  5708. * @param result defines the target matrix
  5709. */
  5710. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5711. for (var index = 0; index < 16; index++) {
  5712. result.m[index] = array[index + offset] * scale;
  5713. }
  5714. result._markAsUpdated();
  5715. };
  5716. /**
  5717. * Stores a list of values (16) inside a given matrix
  5718. * @param initialM11 defines 1st value of 1st row
  5719. * @param initialM12 defines 2nd value of 1st row
  5720. * @param initialM13 defines 3rd value of 1st row
  5721. * @param initialM14 defines 4th value of 1st row
  5722. * @param initialM21 defines 1st value of 2nd row
  5723. * @param initialM22 defines 2nd value of 2nd row
  5724. * @param initialM23 defines 3rd value of 2nd row
  5725. * @param initialM24 defines 4th value of 2nd row
  5726. * @param initialM31 defines 1st value of 3rd row
  5727. * @param initialM32 defines 2nd value of 3rd row
  5728. * @param initialM33 defines 3rd value of 3rd row
  5729. * @param initialM34 defines 4th value of 3rd row
  5730. * @param initialM41 defines 1st value of 4th row
  5731. * @param initialM42 defines 2nd value of 4th row
  5732. * @param initialM43 defines 3rd value of 4th row
  5733. * @param initialM44 defines 4th value of 4th row
  5734. * @param result defines the target matrix
  5735. */
  5736. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5737. result.m[0] = initialM11;
  5738. result.m[1] = initialM12;
  5739. result.m[2] = initialM13;
  5740. result.m[3] = initialM14;
  5741. result.m[4] = initialM21;
  5742. result.m[5] = initialM22;
  5743. result.m[6] = initialM23;
  5744. result.m[7] = initialM24;
  5745. result.m[8] = initialM31;
  5746. result.m[9] = initialM32;
  5747. result.m[10] = initialM33;
  5748. result.m[11] = initialM34;
  5749. result.m[12] = initialM41;
  5750. result.m[13] = initialM42;
  5751. result.m[14] = initialM43;
  5752. result.m[15] = initialM44;
  5753. result._markAsUpdated();
  5754. };
  5755. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5756. /**
  5757. * Gets an identity matrix that must not be updated
  5758. */
  5759. get: function () {
  5760. return Matrix._identityReadOnly;
  5761. },
  5762. enumerable: true,
  5763. configurable: true
  5764. });
  5765. /**
  5766. * Creates new matrix from a list of values (16)
  5767. * @param initialM11 defines 1st value of 1st row
  5768. * @param initialM12 defines 2nd value of 1st row
  5769. * @param initialM13 defines 3rd value of 1st row
  5770. * @param initialM14 defines 4th value of 1st row
  5771. * @param initialM21 defines 1st value of 2nd row
  5772. * @param initialM22 defines 2nd value of 2nd row
  5773. * @param initialM23 defines 3rd value of 2nd row
  5774. * @param initialM24 defines 4th value of 2nd row
  5775. * @param initialM31 defines 1st value of 3rd row
  5776. * @param initialM32 defines 2nd value of 3rd row
  5777. * @param initialM33 defines 3rd value of 3rd row
  5778. * @param initialM34 defines 4th value of 3rd row
  5779. * @param initialM41 defines 1st value of 4th row
  5780. * @param initialM42 defines 2nd value of 4th row
  5781. * @param initialM43 defines 3rd value of 4th row
  5782. * @param initialM44 defines 4th value of 4th row
  5783. * @returns the new matrix
  5784. */
  5785. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5786. var result = new Matrix();
  5787. result.m[0] = initialM11;
  5788. result.m[1] = initialM12;
  5789. result.m[2] = initialM13;
  5790. result.m[3] = initialM14;
  5791. result.m[4] = initialM21;
  5792. result.m[5] = initialM22;
  5793. result.m[6] = initialM23;
  5794. result.m[7] = initialM24;
  5795. result.m[8] = initialM31;
  5796. result.m[9] = initialM32;
  5797. result.m[10] = initialM33;
  5798. result.m[11] = initialM34;
  5799. result.m[12] = initialM41;
  5800. result.m[13] = initialM42;
  5801. result.m[14] = initialM43;
  5802. result.m[15] = initialM44;
  5803. return result;
  5804. };
  5805. /**
  5806. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5807. * @param scale defines the scale vector3
  5808. * @param rotation defines the rotation quaternion
  5809. * @param translation defines the translation vector3
  5810. * @returns a new matrix
  5811. */
  5812. Matrix.Compose = function (scale, rotation, translation) {
  5813. var result = Matrix.Identity();
  5814. Matrix.ComposeToRef(scale, rotation, translation, result);
  5815. return result;
  5816. };
  5817. /**
  5818. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5819. * @param scale defines the scale vector3
  5820. * @param rotation defines the rotation quaternion
  5821. * @param translation defines the translation vector3
  5822. * @param result defines the target matrix
  5823. */
  5824. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5825. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5826. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5827. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5828. result.setTranslation(translation);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix
  5832. * @returns a new identity matrix
  5833. */
  5834. Matrix.Identity = function () {
  5835. 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);
  5836. };
  5837. /**
  5838. * Creates a new identity matrix and stores the result in a given matrix
  5839. * @param result defines the target matrix
  5840. */
  5841. Matrix.IdentityToRef = function (result) {
  5842. 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);
  5843. };
  5844. /**
  5845. * Creates a new zero matrix
  5846. * @returns a new zero matrix
  5847. */
  5848. Matrix.Zero = function () {
  5849. 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);
  5850. };
  5851. /**
  5852. * Creates a new rotation matrix for "angle" radians around the X axis
  5853. * @param angle defines the angle (in radians) to use
  5854. * @return the new matrix
  5855. */
  5856. Matrix.RotationX = function (angle) {
  5857. var result = new Matrix();
  5858. Matrix.RotationXToRef(angle, result);
  5859. return result;
  5860. };
  5861. /**
  5862. * Creates a new matrix as the invert of a given matrix
  5863. * @param source defines the source matrix
  5864. * @returns the new matrix
  5865. */
  5866. Matrix.Invert = function (source) {
  5867. var result = new Matrix();
  5868. source.invertToRef(result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5873. * @param angle defines the angle (in radians) to use
  5874. * @param result defines the target matrix
  5875. */
  5876. Matrix.RotationXToRef = function (angle, result) {
  5877. var s = Math.sin(angle);
  5878. var c = Math.cos(angle);
  5879. result.m[0] = 1.0;
  5880. result.m[15] = 1.0;
  5881. result.m[5] = c;
  5882. result.m[10] = c;
  5883. result.m[9] = -s;
  5884. result.m[6] = s;
  5885. result.m[1] = 0.0;
  5886. result.m[2] = 0.0;
  5887. result.m[3] = 0.0;
  5888. result.m[4] = 0.0;
  5889. result.m[7] = 0.0;
  5890. result.m[8] = 0.0;
  5891. result.m[11] = 0.0;
  5892. result.m[12] = 0.0;
  5893. result.m[13] = 0.0;
  5894. result.m[14] = 0.0;
  5895. result._markAsUpdated();
  5896. };
  5897. /**
  5898. * Creates a new rotation matrix for "angle" radians around the Y axis
  5899. * @param angle defines the angle (in radians) to use
  5900. * @return the new matrix
  5901. */
  5902. Matrix.RotationY = function (angle) {
  5903. var result = new Matrix();
  5904. Matrix.RotationYToRef(angle, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5909. * @param angle defines the angle (in radians) to use
  5910. * @param result defines the target matrix
  5911. */
  5912. Matrix.RotationYToRef = function (angle, result) {
  5913. var s = Math.sin(angle);
  5914. var c = Math.cos(angle);
  5915. result.m[5] = 1.0;
  5916. result.m[15] = 1.0;
  5917. result.m[0] = c;
  5918. result.m[2] = -s;
  5919. result.m[8] = s;
  5920. result.m[10] = c;
  5921. result.m[1] = 0.0;
  5922. result.m[3] = 0.0;
  5923. result.m[4] = 0.0;
  5924. result.m[6] = 0.0;
  5925. result.m[7] = 0.0;
  5926. result.m[9] = 0.0;
  5927. result.m[11] = 0.0;
  5928. result.m[12] = 0.0;
  5929. result.m[13] = 0.0;
  5930. result.m[14] = 0.0;
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Creates a new rotation matrix for "angle" radians around the Z axis
  5935. * @param angle defines the angle (in radians) to use
  5936. * @return the new matrix
  5937. */
  5938. Matrix.RotationZ = function (angle) {
  5939. var result = new Matrix();
  5940. Matrix.RotationZToRef(angle, result);
  5941. return result;
  5942. };
  5943. /**
  5944. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5945. * @param angle defines the angle (in radians) to use
  5946. * @param result defines the target matrix
  5947. */
  5948. Matrix.RotationZToRef = function (angle, result) {
  5949. var s = Math.sin(angle);
  5950. var c = Math.cos(angle);
  5951. result.m[10] = 1.0;
  5952. result.m[15] = 1.0;
  5953. result.m[0] = c;
  5954. result.m[1] = s;
  5955. result.m[4] = -s;
  5956. result.m[5] = c;
  5957. result.m[2] = 0.0;
  5958. result.m[3] = 0.0;
  5959. result.m[6] = 0.0;
  5960. result.m[7] = 0.0;
  5961. result.m[8] = 0.0;
  5962. result.m[9] = 0.0;
  5963. result.m[11] = 0.0;
  5964. result.m[12] = 0.0;
  5965. result.m[13] = 0.0;
  5966. result.m[14] = 0.0;
  5967. result._markAsUpdated();
  5968. };
  5969. /**
  5970. * Creates a new rotation matrix for "angle" radians around the given axis
  5971. * @param axis defines the axis to use
  5972. * @param angle defines the angle (in radians) to use
  5973. * @return the new matrix
  5974. */
  5975. Matrix.RotationAxis = function (axis, angle) {
  5976. var result = Matrix.Zero();
  5977. Matrix.RotationAxisToRef(axis, angle, result);
  5978. return result;
  5979. };
  5980. /**
  5981. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5982. * @param axis defines the axis to use
  5983. * @param angle defines the angle (in radians) to use
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5987. var s = Math.sin(-angle);
  5988. var c = Math.cos(-angle);
  5989. var c1 = 1 - c;
  5990. axis.normalize();
  5991. result.m[0] = (axis.x * axis.x) * c1 + c;
  5992. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5993. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5994. result.m[3] = 0.0;
  5995. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5996. result.m[5] = (axis.y * axis.y) * c1 + c;
  5997. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5998. result.m[7] = 0.0;
  5999. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6000. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6001. result.m[10] = (axis.z * axis.z) * c1 + c;
  6002. result.m[11] = 0.0;
  6003. result.m[15] = 1.0;
  6004. result._markAsUpdated();
  6005. };
  6006. /**
  6007. * Creates a rotation matrix
  6008. * @param yaw defines the yaw angle in radians (Y axis)
  6009. * @param pitch defines the pitch angle in radians (X axis)
  6010. * @param roll defines the roll angle in radians (X axis)
  6011. * @returns the new rotation matrix
  6012. */
  6013. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6014. var result = new Matrix();
  6015. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6016. return result;
  6017. };
  6018. /**
  6019. * Creates a rotation matrix and stores it in a given matrix
  6020. * @param yaw defines the yaw angle in radians (Y axis)
  6021. * @param pitch defines the pitch angle in radians (X axis)
  6022. * @param roll defines the roll angle in radians (X axis)
  6023. * @param result defines the target matrix
  6024. */
  6025. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6026. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6027. this._tempQuaternion.toRotationMatrix(result);
  6028. };
  6029. /**
  6030. * Creates a scaling matrix
  6031. * @param x defines the scale factor on X axis
  6032. * @param y defines the scale factor on Y axis
  6033. * @param z defines the scale factor on Z axis
  6034. * @returns the new matrix
  6035. */
  6036. Matrix.Scaling = function (x, y, z) {
  6037. var result = Matrix.Zero();
  6038. Matrix.ScalingToRef(x, y, z, result);
  6039. return result;
  6040. };
  6041. /**
  6042. * Creates a scaling matrix and stores it in a given matrix
  6043. * @param x defines the scale factor on X axis
  6044. * @param y defines the scale factor on Y axis
  6045. * @param z defines the scale factor on Z axis
  6046. * @param result defines the target matrix
  6047. */
  6048. Matrix.ScalingToRef = function (x, y, z, result) {
  6049. result.m[0] = x;
  6050. result.m[1] = 0.0;
  6051. result.m[2] = 0.0;
  6052. result.m[3] = 0.0;
  6053. result.m[4] = 0.0;
  6054. result.m[5] = y;
  6055. result.m[6] = 0.0;
  6056. result.m[7] = 0.0;
  6057. result.m[8] = 0.0;
  6058. result.m[9] = 0.0;
  6059. result.m[10] = z;
  6060. result.m[11] = 0.0;
  6061. result.m[12] = 0.0;
  6062. result.m[13] = 0.0;
  6063. result.m[14] = 0.0;
  6064. result.m[15] = 1.0;
  6065. result._markAsUpdated();
  6066. };
  6067. /**
  6068. * Creates a translation matrix
  6069. * @param x defines the translation on X axis
  6070. * @param y defines the translation on Y axis
  6071. * @param z defines the translationon Z axis
  6072. * @returns the new matrix
  6073. */
  6074. Matrix.Translation = function (x, y, z) {
  6075. var result = Matrix.Identity();
  6076. Matrix.TranslationToRef(x, y, z, result);
  6077. return result;
  6078. };
  6079. /**
  6080. * Creates a translation matrix and stores it in a given matrix
  6081. * @param x defines the translation on X axis
  6082. * @param y defines the translation on Y axis
  6083. * @param z defines the translationon Z axis
  6084. * @param result defines the target matrix
  6085. */
  6086. Matrix.TranslationToRef = function (x, y, z, result) {
  6087. 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);
  6088. };
  6089. /**
  6090. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6091. * @param startValue defines the start value
  6092. * @param endValue defines the end value
  6093. * @param gradient defines the gradient factor
  6094. * @returns the new matrix
  6095. */
  6096. Matrix.Lerp = function (startValue, endValue, gradient) {
  6097. var result = Matrix.Zero();
  6098. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6099. return result;
  6100. };
  6101. /**
  6102. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6103. * @param startValue defines the start value
  6104. * @param endValue defines the end value
  6105. * @param gradient defines the gradient factor
  6106. * @param result defines the Matrix object where to store data
  6107. */
  6108. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6109. for (var index = 0; index < 16; index++) {
  6110. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6111. }
  6112. result._markAsUpdated();
  6113. };
  6114. /**
  6115. * Builds a new matrix whose values are computed by:
  6116. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6117. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6118. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6119. * @param startValue defines the first matrix
  6120. * @param endValue defines the second matrix
  6121. * @param gradient defines the gradient between the two matrices
  6122. * @returns the new matrix
  6123. */
  6124. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6125. var result = Matrix.Zero();
  6126. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6127. return result;
  6128. };
  6129. /**
  6130. * Update a matrix to values which are computed by:
  6131. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6132. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6133. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6134. * @param startValue defines the first matrix
  6135. * @param endValue defines the second matrix
  6136. * @param gradient defines the gradient between the two matrices
  6137. * @param result defines the target matrix
  6138. */
  6139. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6140. var startScale = MathTmp.Vector3[0];
  6141. var startRotation = MathTmp.Quaternion[0];
  6142. var startTranslation = MathTmp.Vector3[1];
  6143. startValue.decompose(startScale, startRotation, startTranslation);
  6144. var endScale = MathTmp.Vector3[2];
  6145. var endRotation = MathTmp.Quaternion[1];
  6146. var endTranslation = MathTmp.Vector3[3];
  6147. endValue.decompose(endScale, endRotation, endTranslation);
  6148. var resultScale = MathTmp.Vector3[4];
  6149. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6150. var resultRotation = MathTmp.Quaternion[2];
  6151. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6152. var resultTranslation = MathTmp.Vector3[5];
  6153. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6154. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6155. };
  6156. /**
  6157. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6158. * This function works in left handed mode
  6159. * @param eye defines the final position of the entity
  6160. * @param target defines where the entity should look at
  6161. * @param up defines the up vector for the entity
  6162. * @returns the new matrix
  6163. */
  6164. Matrix.LookAtLH = function (eye, target, up) {
  6165. var result = Matrix.Zero();
  6166. Matrix.LookAtLHToRef(eye, target, up, result);
  6167. return result;
  6168. };
  6169. /**
  6170. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6171. * This function works in left handed mode
  6172. * @param eye defines the final position of the entity
  6173. * @param target defines where the entity should look at
  6174. * @param up defines the up vector for the entity
  6175. * @param result defines the target matrix
  6176. */
  6177. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6178. // Z axis
  6179. target.subtractToRef(eye, this._zAxis);
  6180. this._zAxis.normalize();
  6181. // X axis
  6182. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6183. if (this._xAxis.lengthSquared() === 0) {
  6184. this._xAxis.x = 1.0;
  6185. }
  6186. else {
  6187. this._xAxis.normalize();
  6188. }
  6189. // Y axis
  6190. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6191. this._yAxis.normalize();
  6192. // Eye angles
  6193. var ex = -Vector3.Dot(this._xAxis, eye);
  6194. var ey = -Vector3.Dot(this._yAxis, eye);
  6195. var ez = -Vector3.Dot(this._zAxis, eye);
  6196. 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);
  6197. };
  6198. /**
  6199. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6200. * This function works in right handed mode
  6201. * @param eye defines the final position of the entity
  6202. * @param target defines where the entity should look at
  6203. * @param up defines the up vector for the entity
  6204. * @returns the new matrix
  6205. */
  6206. Matrix.LookAtRH = function (eye, target, up) {
  6207. var result = Matrix.Zero();
  6208. Matrix.LookAtRHToRef(eye, target, up, result);
  6209. return result;
  6210. };
  6211. /**
  6212. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6213. * This function works in right handed mode
  6214. * @param eye defines the final position of the entity
  6215. * @param target defines where the entity should look at
  6216. * @param up defines the up vector for the entity
  6217. * @param result defines the target matrix
  6218. */
  6219. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6220. // Z axis
  6221. eye.subtractToRef(target, this._zAxis);
  6222. this._zAxis.normalize();
  6223. // X axis
  6224. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6225. if (this._xAxis.lengthSquared() === 0) {
  6226. this._xAxis.x = 1.0;
  6227. }
  6228. else {
  6229. this._xAxis.normalize();
  6230. }
  6231. // Y axis
  6232. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6233. this._yAxis.normalize();
  6234. // Eye angles
  6235. var ex = -Vector3.Dot(this._xAxis, eye);
  6236. var ey = -Vector3.Dot(this._yAxis, eye);
  6237. var ez = -Vector3.Dot(this._zAxis, eye);
  6238. 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);
  6239. };
  6240. /**
  6241. * Create a left-handed orthographic projection matrix
  6242. * @param width defines the viewport width
  6243. * @param height defines the viewport height
  6244. * @param znear defines the near clip plane
  6245. * @param zfar defines the far clip plane
  6246. * @returns a new matrix as a left-handed orthographic projection matrix
  6247. */
  6248. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6249. var matrix = Matrix.Zero();
  6250. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6251. return matrix;
  6252. };
  6253. /**
  6254. * Store a left-handed orthographic projection to a given matrix
  6255. * @param width defines the viewport width
  6256. * @param height defines the viewport height
  6257. * @param znear defines the near clip plane
  6258. * @param zfar defines the far clip plane
  6259. * @param result defines the target matrix
  6260. */
  6261. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6262. var n = znear;
  6263. var f = zfar;
  6264. var a = 2.0 / width;
  6265. var b = 2.0 / height;
  6266. var c = 2.0 / (f - n);
  6267. var d = -(f + n) / (f - n);
  6268. 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);
  6269. };
  6270. /**
  6271. * Create a left-handed orthographic projection matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a left-handed orthographic projection matrix
  6279. */
  6280. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a left-handed orthographic projection into a given matrix
  6287. * @param left defines the viewport left coordinate
  6288. * @param right defines the viewport right coordinate
  6289. * @param bottom defines the viewport bottom coordinate
  6290. * @param top defines the viewport top coordinate
  6291. * @param znear defines the near clip plane
  6292. * @param zfar defines the far clip plane
  6293. * @param result defines the target matrix
  6294. */
  6295. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6296. var n = znear;
  6297. var f = zfar;
  6298. var a = 2.0 / (right - left);
  6299. var b = 2.0 / (top - bottom);
  6300. var c = 2.0 / (f - n);
  6301. var d = -(f + n) / (f - n);
  6302. var i0 = (left + right) / (left - right);
  6303. var i1 = (top + bottom) / (bottom - top);
  6304. 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);
  6305. };
  6306. /**
  6307. * Creates a right-handed orthographic projection matrix
  6308. * @param left defines the viewport left coordinate
  6309. * @param right defines the viewport right coordinate
  6310. * @param bottom defines the viewport bottom coordinate
  6311. * @param top defines the viewport top coordinate
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @returns a new matrix as a right-handed orthographic projection matrix
  6315. */
  6316. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6317. var matrix = Matrix.Zero();
  6318. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6319. return matrix;
  6320. };
  6321. /**
  6322. * Stores a right-handed orthographic projection into a given matrix
  6323. * @param left defines the viewport left coordinate
  6324. * @param right defines the viewport right coordinate
  6325. * @param bottom defines the viewport bottom coordinate
  6326. * @param top defines the viewport top coordinate
  6327. * @param znear defines the near clip plane
  6328. * @param zfar defines the far clip plane
  6329. * @param result defines the target matrix
  6330. */
  6331. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6332. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6333. result.m[10] *= -1.0;
  6334. };
  6335. /**
  6336. * Creates a left-handed perspective projection matrix
  6337. * @param width defines the viewport width
  6338. * @param height defines the viewport height
  6339. * @param znear defines the near clip plane
  6340. * @param zfar defines the far clip plane
  6341. * @returns a new matrix as a left-handed perspective projection matrix
  6342. */
  6343. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6344. var matrix = Matrix.Zero();
  6345. var n = znear;
  6346. var f = zfar;
  6347. var a = 2.0 * n / width;
  6348. var b = 2.0 * n / height;
  6349. var c = (f + n) / (f - n);
  6350. var d = -2.0 * f * n / (f - n);
  6351. 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);
  6352. return matrix;
  6353. };
  6354. /**
  6355. * Creates a left-handed perspective projection matrix
  6356. * @param fov defines the horizontal field of view
  6357. * @param aspect defines the aspect ratio
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @returns a new matrix as a left-handed perspective projection matrix
  6361. */
  6362. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6363. var matrix = Matrix.Zero();
  6364. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6365. return matrix;
  6366. };
  6367. /**
  6368. * Stores a left-handed perspective projection into a given matrix
  6369. * @param fov defines the horizontal field of view
  6370. * @param aspect defines the aspect ratio
  6371. * @param znear defines the near clip plane
  6372. * @param zfar defines the far clip plane
  6373. * @param result defines the target matrix
  6374. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6375. */
  6376. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6377. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6378. var n = znear;
  6379. var f = zfar;
  6380. var t = 1.0 / (Math.tan(fov * 0.5));
  6381. var a = isVerticalFovFixed ? (t / aspect) : t;
  6382. var b = isVerticalFovFixed ? t : (t * aspect);
  6383. var c = (f + n) / (f - n);
  6384. var d = -2.0 * f * n / (f - n);
  6385. 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);
  6386. };
  6387. /**
  6388. * Creates a right-handed perspective projection matrix
  6389. * @param fov defines the horizontal field of view
  6390. * @param aspect defines the aspect ratio
  6391. * @param znear defines the near clip plane
  6392. * @param zfar defines the far clip plane
  6393. * @returns a new matrix as a right-handed perspective projection matrix
  6394. */
  6395. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6396. var matrix = Matrix.Zero();
  6397. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6398. return matrix;
  6399. };
  6400. /**
  6401. * Stores a right-handed perspective projection into a given matrix
  6402. * @param fov defines the horizontal field of view
  6403. * @param aspect defines the aspect ratio
  6404. * @param znear defines the near clip plane
  6405. * @param zfar defines the far clip plane
  6406. * @param result defines the target matrix
  6407. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6408. */
  6409. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6410. //alternatively this could be expressed as:
  6411. // m = PerspectiveFovLHToRef
  6412. // m[10] *= -1.0;
  6413. // m[11] *= -1.0;
  6414. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6415. var n = znear;
  6416. var f = zfar;
  6417. var t = 1.0 / (Math.tan(fov * 0.5));
  6418. var a = isVerticalFovFixed ? (t / aspect) : t;
  6419. var b = isVerticalFovFixed ? t : (t * aspect);
  6420. var c = -(f + n) / (f - n);
  6421. var d = -2 * f * n / (f - n);
  6422. 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);
  6423. };
  6424. /**
  6425. * Stores a perspective projection for WebVR info a given matrix
  6426. * @param fov defines the field of view
  6427. * @param znear defines the near clip plane
  6428. * @param zfar defines the far clip plane
  6429. * @param result defines the target matrix
  6430. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6431. */
  6432. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6433. if (rightHanded === void 0) { rightHanded = false; }
  6434. var rightHandedFactor = rightHanded ? -1 : 1;
  6435. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6436. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6437. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6438. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6439. var xScale = 2.0 / (leftTan + rightTan);
  6440. var yScale = 2.0 / (upTan + downTan);
  6441. result.m[0] = xScale;
  6442. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6443. result.m[5] = yScale;
  6444. result.m[6] = result.m[7] = 0.0;
  6445. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6446. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6447. result.m[10] = -zfar / (znear - zfar);
  6448. result.m[11] = 1.0 * rightHandedFactor;
  6449. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6450. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6451. result._markAsUpdated();
  6452. };
  6453. /**
  6454. * Computes a complete transformation matrix
  6455. * @param viewport defines the viewport to use
  6456. * @param world defines the world matrix
  6457. * @param view defines the view matrix
  6458. * @param projection defines the projection matrix
  6459. * @param zmin defines the near clip plane
  6460. * @param zmax defines the far clip plane
  6461. * @returns the transformation matrix
  6462. */
  6463. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6464. var cw = viewport.width;
  6465. var ch = viewport.height;
  6466. var cx = viewport.x;
  6467. var cy = viewport.y;
  6468. 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);
  6469. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6470. };
  6471. /**
  6472. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6473. * @param matrix defines the matrix to use
  6474. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6475. */
  6476. Matrix.GetAsMatrix2x2 = function (matrix) {
  6477. return new Float32Array([
  6478. matrix.m[0], matrix.m[1],
  6479. matrix.m[4], matrix.m[5]
  6480. ]);
  6481. };
  6482. /**
  6483. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6484. * @param matrix defines the matrix to use
  6485. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6486. */
  6487. Matrix.GetAsMatrix3x3 = function (matrix) {
  6488. return new Float32Array([
  6489. matrix.m[0], matrix.m[1], matrix.m[2],
  6490. matrix.m[4], matrix.m[5], matrix.m[6],
  6491. matrix.m[8], matrix.m[9], matrix.m[10]
  6492. ]);
  6493. };
  6494. /**
  6495. * Compute the transpose of a given matrix
  6496. * @param matrix defines the matrix to transpose
  6497. * @returns the new matrix
  6498. */
  6499. Matrix.Transpose = function (matrix) {
  6500. var result = new Matrix();
  6501. Matrix.TransposeToRef(matrix, result);
  6502. return result;
  6503. };
  6504. /**
  6505. * Compute the transpose of a matrix and store it in a target matrix
  6506. * @param matrix defines the matrix to transpose
  6507. * @param result defines the target matrix
  6508. */
  6509. Matrix.TransposeToRef = function (matrix, result) {
  6510. result.m[0] = matrix.m[0];
  6511. result.m[1] = matrix.m[4];
  6512. result.m[2] = matrix.m[8];
  6513. result.m[3] = matrix.m[12];
  6514. result.m[4] = matrix.m[1];
  6515. result.m[5] = matrix.m[5];
  6516. result.m[6] = matrix.m[9];
  6517. result.m[7] = matrix.m[13];
  6518. result.m[8] = matrix.m[2];
  6519. result.m[9] = matrix.m[6];
  6520. result.m[10] = matrix.m[10];
  6521. result.m[11] = matrix.m[14];
  6522. result.m[12] = matrix.m[3];
  6523. result.m[13] = matrix.m[7];
  6524. result.m[14] = matrix.m[11];
  6525. result.m[15] = matrix.m[15];
  6526. };
  6527. /**
  6528. * Computes a reflection matrix from a plane
  6529. * @param plane defines the reflection plane
  6530. * @returns a new matrix
  6531. */
  6532. Matrix.Reflection = function (plane) {
  6533. var matrix = new Matrix();
  6534. Matrix.ReflectionToRef(plane, matrix);
  6535. return matrix;
  6536. };
  6537. /**
  6538. * Computes a reflection matrix from a plane
  6539. * @param plane defines the reflection plane
  6540. * @param result defines the target matrix
  6541. */
  6542. Matrix.ReflectionToRef = function (plane, result) {
  6543. plane.normalize();
  6544. var x = plane.normal.x;
  6545. var y = plane.normal.y;
  6546. var z = plane.normal.z;
  6547. var temp = -2 * x;
  6548. var temp2 = -2 * y;
  6549. var temp3 = -2 * z;
  6550. result.m[0] = (temp * x) + 1;
  6551. result.m[1] = temp2 * x;
  6552. result.m[2] = temp3 * x;
  6553. result.m[3] = 0.0;
  6554. result.m[4] = temp * y;
  6555. result.m[5] = (temp2 * y) + 1;
  6556. result.m[6] = temp3 * y;
  6557. result.m[7] = 0.0;
  6558. result.m[8] = temp * z;
  6559. result.m[9] = temp2 * z;
  6560. result.m[10] = (temp3 * z) + 1;
  6561. result.m[11] = 0.0;
  6562. result.m[12] = temp * plane.d;
  6563. result.m[13] = temp2 * plane.d;
  6564. result.m[14] = temp3 * plane.d;
  6565. result.m[15] = 1.0;
  6566. result._markAsUpdated();
  6567. };
  6568. /**
  6569. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6570. * @param xaxis defines the value of the 1st axis
  6571. * @param yaxis defines the value of the 2nd axis
  6572. * @param zaxis defines the value of the 3rd axis
  6573. * @param result defines the target matrix
  6574. */
  6575. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6576. result.m[0] = xaxis.x;
  6577. result.m[1] = xaxis.y;
  6578. result.m[2] = xaxis.z;
  6579. result.m[3] = 0.0;
  6580. result.m[4] = yaxis.x;
  6581. result.m[5] = yaxis.y;
  6582. result.m[6] = yaxis.z;
  6583. result.m[7] = 0.0;
  6584. result.m[8] = zaxis.x;
  6585. result.m[9] = zaxis.y;
  6586. result.m[10] = zaxis.z;
  6587. result.m[11] = 0.0;
  6588. result.m[12] = 0.0;
  6589. result.m[13] = 0.0;
  6590. result.m[14] = 0.0;
  6591. result.m[15] = 1.0;
  6592. result._markAsUpdated();
  6593. };
  6594. /**
  6595. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6596. * @param quat defines the quaternion to use
  6597. * @param result defines the target matrix
  6598. */
  6599. Matrix.FromQuaternionToRef = function (quat, result) {
  6600. var xx = quat.x * quat.x;
  6601. var yy = quat.y * quat.y;
  6602. var zz = quat.z * quat.z;
  6603. var xy = quat.x * quat.y;
  6604. var zw = quat.z * quat.w;
  6605. var zx = quat.z * quat.x;
  6606. var yw = quat.y * quat.w;
  6607. var yz = quat.y * quat.z;
  6608. var xw = quat.x * quat.w;
  6609. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6610. result.m[1] = 2.0 * (xy + zw);
  6611. result.m[2] = 2.0 * (zx - yw);
  6612. result.m[3] = 0.0;
  6613. result.m[4] = 2.0 * (xy - zw);
  6614. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6615. result.m[6] = 2.0 * (yz + xw);
  6616. result.m[7] = 0.0;
  6617. result.m[8] = 2.0 * (zx + yw);
  6618. result.m[9] = 2.0 * (yz - xw);
  6619. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6620. result.m[11] = 0.0;
  6621. result.m[12] = 0.0;
  6622. result.m[13] = 0.0;
  6623. result.m[14] = 0.0;
  6624. result.m[15] = 1.0;
  6625. result._markAsUpdated();
  6626. };
  6627. Matrix._tempQuaternion = new Quaternion();
  6628. Matrix._xAxis = Vector3.Zero();
  6629. Matrix._yAxis = Vector3.Zero();
  6630. Matrix._zAxis = Vector3.Zero();
  6631. Matrix._updateFlagSeed = 0;
  6632. Matrix._identityReadOnly = Matrix.Identity();
  6633. return Matrix;
  6634. }());
  6635. BABYLON.Matrix = Matrix;
  6636. var Plane = /** @class */ (function () {
  6637. /**
  6638. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6639. */
  6640. function Plane(a, b, c, d) {
  6641. this.normal = new Vector3(a, b, c);
  6642. this.d = d;
  6643. }
  6644. /**
  6645. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6646. */
  6647. Plane.prototype.asArray = function () {
  6648. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6649. };
  6650. // Methods
  6651. /**
  6652. * Returns a new plane copied from the current Plane.
  6653. */
  6654. Plane.prototype.clone = function () {
  6655. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6656. };
  6657. /**
  6658. * Returns the string "Plane".
  6659. */
  6660. Plane.prototype.getClassName = function () {
  6661. return "Plane";
  6662. };
  6663. /**
  6664. * Returns the Plane hash code.
  6665. */
  6666. Plane.prototype.getHashCode = function () {
  6667. var hash = this.normal.getHashCode();
  6668. hash = (hash * 397) ^ (this.d || 0);
  6669. return hash;
  6670. };
  6671. /**
  6672. * Normalize the current Plane in place.
  6673. * Returns the updated Plane.
  6674. */
  6675. Plane.prototype.normalize = function () {
  6676. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6677. var magnitude = 0.0;
  6678. if (norm !== 0) {
  6679. magnitude = 1.0 / norm;
  6680. }
  6681. this.normal.x *= magnitude;
  6682. this.normal.y *= magnitude;
  6683. this.normal.z *= magnitude;
  6684. this.d *= magnitude;
  6685. return this;
  6686. };
  6687. /**
  6688. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6689. */
  6690. Plane.prototype.transform = function (transformation) {
  6691. var transposedMatrix = Matrix.Transpose(transformation);
  6692. var x = this.normal.x;
  6693. var y = this.normal.y;
  6694. var z = this.normal.z;
  6695. var d = this.d;
  6696. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6697. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6698. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6699. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6700. return new Plane(normalX, normalY, normalZ, finalD);
  6701. };
  6702. /**
  6703. * Returns the dot product (float) of the point coordinates and the plane normal.
  6704. */
  6705. Plane.prototype.dotCoordinate = function (point) {
  6706. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6707. };
  6708. /**
  6709. * Updates the current Plane from the plane defined by the three given points.
  6710. * Returns the updated Plane.
  6711. */
  6712. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6713. var x1 = point2.x - point1.x;
  6714. var y1 = point2.y - point1.y;
  6715. var z1 = point2.z - point1.z;
  6716. var x2 = point3.x - point1.x;
  6717. var y2 = point3.y - point1.y;
  6718. var z2 = point3.z - point1.z;
  6719. var yz = (y1 * z2) - (z1 * y2);
  6720. var xz = (z1 * x2) - (x1 * z2);
  6721. var xy = (x1 * y2) - (y1 * x2);
  6722. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6723. var invPyth;
  6724. if (pyth !== 0) {
  6725. invPyth = 1.0 / pyth;
  6726. }
  6727. else {
  6728. invPyth = 0.0;
  6729. }
  6730. this.normal.x = yz * invPyth;
  6731. this.normal.y = xz * invPyth;
  6732. this.normal.z = xy * invPyth;
  6733. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6734. return this;
  6735. };
  6736. /**
  6737. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6738. */
  6739. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6740. var dot = Vector3.Dot(this.normal, direction);
  6741. return (dot <= epsilon);
  6742. };
  6743. /**
  6744. * Returns the signed distance (float) from the given point to the Plane.
  6745. */
  6746. Plane.prototype.signedDistanceTo = function (point) {
  6747. return Vector3.Dot(point, this.normal) + this.d;
  6748. };
  6749. // Statics
  6750. /**
  6751. * Returns a new Plane from the given array.
  6752. */
  6753. Plane.FromArray = function (array) {
  6754. return new Plane(array[0], array[1], array[2], array[3]);
  6755. };
  6756. /**
  6757. * Returns a new Plane defined by the three given points.
  6758. */
  6759. Plane.FromPoints = function (point1, point2, point3) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. result.copyFromPoints(point1, point2, point3);
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new Plane the normal vector to this plane at the given origin point.
  6766. * Note : the vector "normal" is updated because normalized.
  6767. */
  6768. Plane.FromPositionAndNormal = function (origin, normal) {
  6769. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6770. normal.normalize();
  6771. result.normal = normal;
  6772. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return result;
  6774. };
  6775. /**
  6776. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6777. */
  6778. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6779. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6780. return Vector3.Dot(point, normal) + d;
  6781. };
  6782. return Plane;
  6783. }());
  6784. BABYLON.Plane = Plane;
  6785. var Viewport = /** @class */ (function () {
  6786. /**
  6787. * Creates a Viewport object located at (x, y) and sized (width, height).
  6788. */
  6789. function Viewport(x, y, width, height) {
  6790. this.x = x;
  6791. this.y = y;
  6792. this.width = width;
  6793. this.height = height;
  6794. }
  6795. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6796. if (renderWidthOrEngine.getRenderWidth) {
  6797. var engine = renderWidthOrEngine;
  6798. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6799. }
  6800. var renderWidth = renderWidthOrEngine;
  6801. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6802. };
  6803. /**
  6804. * Returns a new Viewport copied from the current one.
  6805. */
  6806. Viewport.prototype.clone = function () {
  6807. return new Viewport(this.x, this.y, this.width, this.height);
  6808. };
  6809. return Viewport;
  6810. }());
  6811. BABYLON.Viewport = Viewport;
  6812. var Frustum = /** @class */ (function () {
  6813. function Frustum() {
  6814. }
  6815. /**
  6816. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6817. */
  6818. Frustum.GetPlanes = function (transform) {
  6819. var frustumPlanes = [];
  6820. for (var index = 0; index < 6; index++) {
  6821. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6822. }
  6823. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6824. return frustumPlanes;
  6825. };
  6826. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6828. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6829. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6830. frustumPlane.d = transform.m[15] + transform.m[14];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6835. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6836. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6837. frustumPlane.d = transform.m[15] - transform.m[14];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6842. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6843. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6844. frustumPlane.d = transform.m[15] + transform.m[12];
  6845. frustumPlane.normalize();
  6846. };
  6847. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6851. frustumPlane.d = transform.m[15] - transform.m[12];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6855. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6856. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6857. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6858. frustumPlane.d = transform.m[15] - transform.m[13];
  6859. frustumPlane.normalize();
  6860. };
  6861. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6862. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6863. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6864. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6865. frustumPlane.d = transform.m[15] + transform.m[13];
  6866. frustumPlane.normalize();
  6867. };
  6868. /**
  6869. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6870. */
  6871. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6872. // Near
  6873. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6874. // Far
  6875. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6876. // Left
  6877. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6878. // Right
  6879. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6880. // Top
  6881. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6882. // Bottom
  6883. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6884. };
  6885. return Frustum;
  6886. }());
  6887. BABYLON.Frustum = Frustum;
  6888. /** Defines supported spaces */
  6889. var Space;
  6890. (function (Space) {
  6891. /** Local (object) space */
  6892. Space[Space["LOCAL"] = 0] = "LOCAL";
  6893. /** World space */
  6894. Space[Space["WORLD"] = 1] = "WORLD";
  6895. /** Bone space */
  6896. Space[Space["BONE"] = 2] = "BONE";
  6897. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6898. /** Defines the 3 main axes */
  6899. var Axis = /** @class */ (function () {
  6900. function Axis() {
  6901. }
  6902. /** X axis */
  6903. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6904. /** Y axis */
  6905. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6906. /** Z axis */
  6907. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6908. return Axis;
  6909. }());
  6910. BABYLON.Axis = Axis;
  6911. ;
  6912. var BezierCurve = /** @class */ (function () {
  6913. function BezierCurve() {
  6914. }
  6915. /**
  6916. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6917. */
  6918. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6919. // Extract X (which is equal to time here)
  6920. var f0 = 1 - 3 * x2 + 3 * x1;
  6921. var f1 = 3 * x2 - 6 * x1;
  6922. var f2 = 3 * x1;
  6923. var refinedT = t;
  6924. for (var i = 0; i < 5; i++) {
  6925. var refinedT2 = refinedT * refinedT;
  6926. var refinedT3 = refinedT2 * refinedT;
  6927. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6928. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6929. refinedT -= (x - t) * slope;
  6930. refinedT = Math.min(1, Math.max(0, refinedT));
  6931. }
  6932. // Resolve cubic bezier for the given x
  6933. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6934. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6935. Math.pow(refinedT, 3);
  6936. };
  6937. return BezierCurve;
  6938. }());
  6939. BABYLON.BezierCurve = BezierCurve;
  6940. /**
  6941. * Defines potential orientation for back face culling
  6942. */
  6943. var Orientation;
  6944. (function (Orientation) {
  6945. /**
  6946. * Clockwise
  6947. */
  6948. Orientation[Orientation["CW"] = 0] = "CW";
  6949. /** Counter clockwise */
  6950. Orientation[Orientation["CCW"] = 1] = "CCW";
  6951. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6952. /**
  6953. * Defines angle representation
  6954. */
  6955. var Angle = /** @class */ (function () {
  6956. /**
  6957. * Creates an Angle object of "radians" radians (float).
  6958. */
  6959. function Angle(radians) {
  6960. this._radians = radians;
  6961. if (this._radians < 0.0)
  6962. this._radians += (2.0 * Math.PI);
  6963. }
  6964. /**
  6965. * Get value in degrees
  6966. * @returns the Angle value in degrees (float)
  6967. */
  6968. Angle.prototype.degrees = function () {
  6969. return this._radians * 180.0 / Math.PI;
  6970. };
  6971. /**
  6972. * Get value in radians
  6973. * @returns the Angle value in radians (float)
  6974. */
  6975. Angle.prototype.radians = function () {
  6976. return this._radians;
  6977. };
  6978. /**
  6979. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6980. * @param a defines first vector
  6981. * @param b defines second vector
  6982. * @returns a new Angle
  6983. */
  6984. Angle.BetweenTwoPoints = function (a, b) {
  6985. var delta = b.subtract(a);
  6986. var theta = Math.atan2(delta.y, delta.x);
  6987. return new Angle(theta);
  6988. };
  6989. /**
  6990. * Gets a new Angle object from the given float in radians
  6991. * @param radians defines the angle value in radians
  6992. * @returns a new Angle
  6993. */
  6994. Angle.FromRadians = function (radians) {
  6995. return new Angle(radians);
  6996. };
  6997. /**
  6998. * Gets a new Angle object from the given float in degrees
  6999. * @param degrees defines the angle value in degrees
  7000. * @returns a new Angle
  7001. */
  7002. Angle.FromDegrees = function (degrees) {
  7003. return new Angle(degrees * Math.PI / 180.0);
  7004. };
  7005. return Angle;
  7006. }());
  7007. BABYLON.Angle = Angle;
  7008. var Arc2 = /** @class */ (function () {
  7009. /**
  7010. * Creates an Arc object from the three given points : start, middle and end.
  7011. */
  7012. function Arc2(startPoint, midPoint, endPoint) {
  7013. this.startPoint = startPoint;
  7014. this.midPoint = midPoint;
  7015. this.endPoint = endPoint;
  7016. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7017. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7018. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7019. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7020. 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);
  7021. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7022. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7023. var a1 = this.startAngle.degrees();
  7024. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7025. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7026. // angles correction
  7027. if (a2 - a1 > +180.0)
  7028. a2 -= 360.0;
  7029. if (a2 - a1 < -180.0)
  7030. a2 += 360.0;
  7031. if (a3 - a2 > +180.0)
  7032. a3 -= 360.0;
  7033. if (a3 - a2 < -180.0)
  7034. a3 += 360.0;
  7035. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7036. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7037. }
  7038. return Arc2;
  7039. }());
  7040. BABYLON.Arc2 = Arc2;
  7041. var Path2 = /** @class */ (function () {
  7042. /**
  7043. * Creates a Path2 object from the starting 2D coordinates x and y.
  7044. */
  7045. function Path2(x, y) {
  7046. this._points = new Array();
  7047. this._length = 0.0;
  7048. this.closed = false;
  7049. this._points.push(new Vector2(x, y));
  7050. }
  7051. /**
  7052. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7053. * Returns the updated Path2.
  7054. */
  7055. Path2.prototype.addLineTo = function (x, y) {
  7056. if (this.closed) {
  7057. return this;
  7058. }
  7059. var newPoint = new Vector2(x, y);
  7060. var previousPoint = this._points[this._points.length - 1];
  7061. this._points.push(newPoint);
  7062. this._length += newPoint.subtract(previousPoint).length();
  7063. return this;
  7064. };
  7065. /**
  7066. * 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.
  7067. * Returns the updated Path2.
  7068. */
  7069. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7070. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7071. if (this.closed) {
  7072. return this;
  7073. }
  7074. var startPoint = this._points[this._points.length - 1];
  7075. var midPoint = new Vector2(midX, midY);
  7076. var endPoint = new Vector2(endX, endY);
  7077. var arc = new Arc2(startPoint, midPoint, endPoint);
  7078. var increment = arc.angle.radians() / numberOfSegments;
  7079. if (arc.orientation === Orientation.CW)
  7080. increment *= -1;
  7081. var currentAngle = arc.startAngle.radians() + increment;
  7082. for (var i = 0; i < numberOfSegments; i++) {
  7083. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7084. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7085. this.addLineTo(x, y);
  7086. currentAngle += increment;
  7087. }
  7088. return this;
  7089. };
  7090. /**
  7091. * Closes the Path2.
  7092. * Returns the Path2.
  7093. */
  7094. Path2.prototype.close = function () {
  7095. this.closed = true;
  7096. return this;
  7097. };
  7098. /**
  7099. * Returns the Path2 total length (float).
  7100. */
  7101. Path2.prototype.length = function () {
  7102. var result = this._length;
  7103. if (!this.closed) {
  7104. var lastPoint = this._points[this._points.length - 1];
  7105. var firstPoint = this._points[0];
  7106. result += (firstPoint.subtract(lastPoint).length());
  7107. }
  7108. return result;
  7109. };
  7110. /**
  7111. * Returns the Path2 internal array of points.
  7112. */
  7113. Path2.prototype.getPoints = function () {
  7114. return this._points;
  7115. };
  7116. /**
  7117. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7118. */
  7119. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7120. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7121. return Vector2.Zero();
  7122. }
  7123. var lengthPosition = normalizedLengthPosition * this.length();
  7124. var previousOffset = 0;
  7125. for (var i = 0; i < this._points.length; i++) {
  7126. var j = (i + 1) % this._points.length;
  7127. var a = this._points[i];
  7128. var b = this._points[j];
  7129. var bToA = b.subtract(a);
  7130. var nextOffset = (bToA.length() + previousOffset);
  7131. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7132. var dir = bToA.normalize();
  7133. var localOffset = lengthPosition - previousOffset;
  7134. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7135. }
  7136. previousOffset = nextOffset;
  7137. }
  7138. return Vector2.Zero();
  7139. };
  7140. /**
  7141. * Returns a new Path2 starting at the coordinates (x, y).
  7142. */
  7143. Path2.StartingAt = function (x, y) {
  7144. return new Path2(x, y);
  7145. };
  7146. return Path2;
  7147. }());
  7148. BABYLON.Path2 = Path2;
  7149. var Path3D = /** @class */ (function () {
  7150. /**
  7151. * new Path3D(path, normal, raw)
  7152. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7153. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7154. * path : an array of Vector3, the curve axis of the Path3D
  7155. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7156. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7157. */
  7158. function Path3D(path, firstNormal, raw) {
  7159. if (firstNormal === void 0) { firstNormal = null; }
  7160. this.path = path;
  7161. this._curve = new Array();
  7162. this._distances = new Array();
  7163. this._tangents = new Array();
  7164. this._normals = new Array();
  7165. this._binormals = new Array();
  7166. for (var p = 0; p < path.length; p++) {
  7167. this._curve[p] = path[p].clone(); // hard copy
  7168. }
  7169. this._raw = raw || false;
  7170. this._compute(firstNormal);
  7171. }
  7172. /**
  7173. * Returns the Path3D array of successive Vector3 designing its curve.
  7174. */
  7175. Path3D.prototype.getCurve = function () {
  7176. return this._curve;
  7177. };
  7178. /**
  7179. * Returns an array populated with tangent vectors on each Path3D curve point.
  7180. */
  7181. Path3D.prototype.getTangents = function () {
  7182. return this._tangents;
  7183. };
  7184. /**
  7185. * Returns an array populated with normal vectors on each Path3D curve point.
  7186. */
  7187. Path3D.prototype.getNormals = function () {
  7188. return this._normals;
  7189. };
  7190. /**
  7191. * Returns an array populated with binormal vectors on each Path3D curve point.
  7192. */
  7193. Path3D.prototype.getBinormals = function () {
  7194. return this._binormals;
  7195. };
  7196. /**
  7197. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7198. */
  7199. Path3D.prototype.getDistances = function () {
  7200. return this._distances;
  7201. };
  7202. /**
  7203. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7204. * Returns the same object updated.
  7205. */
  7206. Path3D.prototype.update = function (path, firstNormal) {
  7207. if (firstNormal === void 0) { firstNormal = null; }
  7208. for (var p = 0; p < path.length; p++) {
  7209. this._curve[p].x = path[p].x;
  7210. this._curve[p].y = path[p].y;
  7211. this._curve[p].z = path[p].z;
  7212. }
  7213. this._compute(firstNormal);
  7214. return this;
  7215. };
  7216. // private function compute() : computes tangents, normals and binormals
  7217. Path3D.prototype._compute = function (firstNormal) {
  7218. var l = this._curve.length;
  7219. // first and last tangents
  7220. this._tangents[0] = this._getFirstNonNullVector(0);
  7221. if (!this._raw) {
  7222. this._tangents[0].normalize();
  7223. }
  7224. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7225. if (!this._raw) {
  7226. this._tangents[l - 1].normalize();
  7227. }
  7228. // normals and binormals at first point : arbitrary vector with _normalVector()
  7229. var tg0 = this._tangents[0];
  7230. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7231. this._normals[0] = pp0;
  7232. if (!this._raw) {
  7233. this._normals[0].normalize();
  7234. }
  7235. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7236. if (!this._raw) {
  7237. this._binormals[0].normalize();
  7238. }
  7239. this._distances[0] = 0.0;
  7240. // normals and binormals : next points
  7241. var prev; // previous vector (segment)
  7242. var cur; // current vector (segment)
  7243. var curTang; // current tangent
  7244. // previous normal
  7245. var prevBinor; // previous binormal
  7246. for (var i = 1; i < l; i++) {
  7247. // tangents
  7248. prev = this._getLastNonNullVector(i);
  7249. if (i < l - 1) {
  7250. cur = this._getFirstNonNullVector(i);
  7251. this._tangents[i] = prev.add(cur);
  7252. this._tangents[i].normalize();
  7253. }
  7254. this._distances[i] = this._distances[i - 1] + prev.length();
  7255. // normals and binormals
  7256. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7257. curTang = this._tangents[i];
  7258. prevBinor = this._binormals[i - 1];
  7259. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7260. if (!this._raw) {
  7261. this._normals[i].normalize();
  7262. }
  7263. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7264. if (!this._raw) {
  7265. this._binormals[i].normalize();
  7266. }
  7267. }
  7268. };
  7269. // private function getFirstNonNullVector(index)
  7270. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7271. Path3D.prototype._getFirstNonNullVector = function (index) {
  7272. var i = 1;
  7273. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7274. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7275. i++;
  7276. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7277. }
  7278. return nNVector;
  7279. };
  7280. // private function getLastNonNullVector(index)
  7281. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7282. Path3D.prototype._getLastNonNullVector = function (index) {
  7283. var i = 1;
  7284. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7285. while (nLVector.length() === 0 && index > i + 1) {
  7286. i++;
  7287. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7288. }
  7289. return nLVector;
  7290. };
  7291. // private function normalVector(v0, vt, va) :
  7292. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7293. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7294. Path3D.prototype._normalVector = function (v0, vt, va) {
  7295. var normal0;
  7296. var tgl = vt.length();
  7297. if (tgl === 0.0) {
  7298. tgl = 1.0;
  7299. }
  7300. if (va === undefined || va === null) {
  7301. var point;
  7302. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7303. point = new Vector3(0.0, -1.0, 0.0);
  7304. }
  7305. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7306. point = new Vector3(1.0, 0.0, 0.0);
  7307. }
  7308. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7309. point = new Vector3(0.0, 0.0, 1.0);
  7310. }
  7311. else {
  7312. point = Vector3.Zero();
  7313. }
  7314. normal0 = Vector3.Cross(vt, point);
  7315. }
  7316. else {
  7317. normal0 = Vector3.Cross(vt, va);
  7318. Vector3.CrossToRef(normal0, vt, normal0);
  7319. }
  7320. normal0.normalize();
  7321. return normal0;
  7322. };
  7323. return Path3D;
  7324. }());
  7325. BABYLON.Path3D = Path3D;
  7326. var Curve3 = /** @class */ (function () {
  7327. /**
  7328. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7329. * A Curve3 is designed from a series of successive Vector3.
  7330. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7331. */
  7332. function Curve3(points) {
  7333. this._length = 0.0;
  7334. this._points = points;
  7335. this._length = this._computeLength(points);
  7336. }
  7337. /**
  7338. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7339. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7340. * @param v1 (Vector3) the control point
  7341. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7342. * @param nbPoints (integer) the wanted number of points in the curve
  7343. */
  7344. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7345. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7346. var bez = new Array();
  7347. var equation = function (t, val0, val1, val2) {
  7348. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7349. return res;
  7350. };
  7351. for (var i = 0; i <= nbPoints; i++) {
  7352. 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)));
  7353. }
  7354. return new Curve3(bez);
  7355. };
  7356. /**
  7357. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7358. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7359. * @param v1 (Vector3) the first control point
  7360. * @param v2 (Vector3) the second control point
  7361. * @param v3 (Vector3) the end point of the Cubic Bezier
  7362. * @param nbPoints (integer) the wanted number of points in the curve
  7363. */
  7364. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7365. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7366. var bez = new Array();
  7367. var equation = function (t, val0, val1, val2, val3) {
  7368. 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;
  7369. return res;
  7370. };
  7371. for (var i = 0; i <= nbPoints; i++) {
  7372. 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)));
  7373. }
  7374. return new Curve3(bez);
  7375. };
  7376. /**
  7377. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7378. * @param p1 (Vector3) the origin point of the Hermite Spline
  7379. * @param t1 (Vector3) the tangent vector at the origin point
  7380. * @param p2 (Vector3) the end point of the Hermite Spline
  7381. * @param t2 (Vector3) the tangent vector at the end point
  7382. * @param nbPoints (integer) the wanted number of points in the curve
  7383. */
  7384. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7385. var hermite = new Array();
  7386. var step = 1.0 / nbPoints;
  7387. for (var i = 0; i <= nbPoints; i++) {
  7388. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7389. }
  7390. return new Curve3(hermite);
  7391. };
  7392. /**
  7393. * Returns a Curve3 object along a CatmullRom Spline curve :
  7394. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7395. * @param nbPoints (integer) the wanted number of points between each curve control points
  7396. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7397. */
  7398. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7399. var catmullRom = new Array();
  7400. var step = 1.0 / nbPoints;
  7401. var amount = 0.0;
  7402. if (closed) {
  7403. var pointsCount = points.length;
  7404. for (var i = 0; i < pointsCount; i++) {
  7405. amount = 0;
  7406. for (var c = 0; c < nbPoints; c++) {
  7407. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7408. amount += step;
  7409. }
  7410. }
  7411. catmullRom.push(catmullRom[0]);
  7412. }
  7413. else {
  7414. var totalPoints = new Array();
  7415. totalPoints.push(points[0].clone());
  7416. Array.prototype.push.apply(totalPoints, points);
  7417. totalPoints.push(points[points.length - 1].clone());
  7418. for (var i = 0; i < totalPoints.length - 3; i++) {
  7419. amount = 0;
  7420. for (var c = 0; c < nbPoints; c++) {
  7421. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7422. amount += step;
  7423. }
  7424. }
  7425. i--;
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. }
  7428. return new Curve3(catmullRom);
  7429. };
  7430. /**
  7431. * Returns the Curve3 stored array of successive Vector3
  7432. */
  7433. Curve3.prototype.getPoints = function () {
  7434. return this._points;
  7435. };
  7436. /**
  7437. * Returns the computed length (float) of the curve.
  7438. */
  7439. Curve3.prototype.length = function () {
  7440. return this._length;
  7441. };
  7442. /**
  7443. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7444. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7445. * curveA and curveB keep unchanged.
  7446. */
  7447. Curve3.prototype.continue = function (curve) {
  7448. var lastPoint = this._points[this._points.length - 1];
  7449. var continuedPoints = this._points.slice();
  7450. var curvePoints = curve.getPoints();
  7451. for (var i = 1; i < curvePoints.length; i++) {
  7452. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7453. }
  7454. var continuedCurve = new Curve3(continuedPoints);
  7455. return continuedCurve;
  7456. };
  7457. Curve3.prototype._computeLength = function (path) {
  7458. var l = 0;
  7459. for (var i = 1; i < path.length; i++) {
  7460. l += (path[i].subtract(path[i - 1])).length();
  7461. }
  7462. return l;
  7463. };
  7464. return Curve3;
  7465. }());
  7466. BABYLON.Curve3 = Curve3;
  7467. // Vertex formats
  7468. var PositionNormalVertex = /** @class */ (function () {
  7469. function PositionNormalVertex(position, normal) {
  7470. if (position === void 0) { position = Vector3.Zero(); }
  7471. if (normal === void 0) { normal = Vector3.Up(); }
  7472. this.position = position;
  7473. this.normal = normal;
  7474. }
  7475. PositionNormalVertex.prototype.clone = function () {
  7476. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7477. };
  7478. return PositionNormalVertex;
  7479. }());
  7480. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7481. var PositionNormalTextureVertex = /** @class */ (function () {
  7482. function PositionNormalTextureVertex(position, normal, uv) {
  7483. if (position === void 0) { position = Vector3.Zero(); }
  7484. if (normal === void 0) { normal = Vector3.Up(); }
  7485. if (uv === void 0) { uv = Vector2.Zero(); }
  7486. this.position = position;
  7487. this.normal = normal;
  7488. this.uv = uv;
  7489. }
  7490. PositionNormalTextureVertex.prototype.clone = function () {
  7491. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7492. };
  7493. return PositionNormalTextureVertex;
  7494. }());
  7495. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7496. // Temporary pre-allocated objects for engine internal use
  7497. // usage in any internal function :
  7498. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7499. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7500. var Tmp = /** @class */ (function () {
  7501. function Tmp() {
  7502. }
  7503. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7504. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7505. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7506. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7507. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7508. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7509. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7510. Matrix.Zero(), Matrix.Zero(),
  7511. Matrix.Zero(), Matrix.Zero(),
  7512. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7513. return Tmp;
  7514. }());
  7515. BABYLON.Tmp = Tmp;
  7516. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7517. var MathTmp = /** @class */ (function () {
  7518. function MathTmp() {
  7519. }
  7520. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7521. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7522. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7523. return MathTmp;
  7524. }());
  7525. })(BABYLON || (BABYLON = {}));
  7526. //# sourceMappingURL=babylon.math.js.map
  7527. var BABYLON;
  7528. (function (BABYLON) {
  7529. var Scalar = /** @class */ (function () {
  7530. function Scalar() {
  7531. }
  7532. /**
  7533. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7534. */
  7535. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7536. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7537. var num = a - b;
  7538. return -epsilon <= num && num <= epsilon;
  7539. };
  7540. /**
  7541. * Returns a string : the upper case translation of the number i to hexadecimal.
  7542. */
  7543. Scalar.ToHex = function (i) {
  7544. var str = i.toString(16);
  7545. if (i <= 15) {
  7546. return ("0" + str).toUpperCase();
  7547. }
  7548. return str.toUpperCase();
  7549. };
  7550. /**
  7551. * Returns -1 if value is negative and +1 is value is positive.
  7552. * Returns the value itself if it's equal to zero.
  7553. */
  7554. Scalar.Sign = function (value) {
  7555. value = +value; // convert to a number
  7556. if (value === 0 || isNaN(value))
  7557. return value;
  7558. return value > 0 ? 1 : -1;
  7559. };
  7560. /**
  7561. * Returns the value itself if it's between min and max.
  7562. * Returns min if the value is lower than min.
  7563. * Returns max if the value is greater than max.
  7564. */
  7565. Scalar.Clamp = function (value, min, max) {
  7566. if (min === void 0) { min = 0; }
  7567. if (max === void 0) { max = 1; }
  7568. return Math.min(max, Math.max(min, value));
  7569. };
  7570. /**
  7571. * Returns the log2 of value.
  7572. */
  7573. Scalar.Log2 = function (value) {
  7574. return Math.log(value) * Math.LOG2E;
  7575. };
  7576. /**
  7577. * Loops the value, so that it is never larger than length and never smaller than 0.
  7578. *
  7579. * This is similar to the modulo operator but it works with floating point numbers.
  7580. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7581. * With t = 5 and length = 2.5, the result would be 0.0.
  7582. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7583. */
  7584. Scalar.Repeat = function (value, length) {
  7585. return value - Math.floor(value / length) * length;
  7586. };
  7587. /**
  7588. * Normalize the value between 0.0 and 1.0 using min and max values
  7589. */
  7590. Scalar.Normalize = function (value, min, max) {
  7591. return (value - min) / (max - min);
  7592. };
  7593. /**
  7594. * Denormalize the value from 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Denormalize = function (normalized, min, max) {
  7597. return (normalized * (max - min) + min);
  7598. };
  7599. /**
  7600. * Calculates the shortest difference between two given angles given in degrees.
  7601. */
  7602. Scalar.DeltaAngle = function (current, target) {
  7603. var num = Scalar.Repeat(target - current, 360.0);
  7604. if (num > 180.0) {
  7605. num -= 360.0;
  7606. }
  7607. return num;
  7608. };
  7609. /**
  7610. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7611. *
  7612. * The returned value will move back and forth between 0 and length
  7613. */
  7614. Scalar.PingPong = function (tx, length) {
  7615. var t = Scalar.Repeat(tx, length * 2.0);
  7616. return length - Math.abs(t - length);
  7617. };
  7618. /**
  7619. * Interpolates between min and max with smoothing at the limits.
  7620. *
  7621. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7622. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7623. */
  7624. Scalar.SmoothStep = function (from, to, tx) {
  7625. var t = Scalar.Clamp(tx);
  7626. t = -2.0 * t * t * t + 3.0 * t * t;
  7627. return to * t + from * (1.0 - t);
  7628. };
  7629. /**
  7630. * Moves a value current towards target.
  7631. *
  7632. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7633. * Negative values of maxDelta pushes the value away from target.
  7634. */
  7635. Scalar.MoveTowards = function (current, target, maxDelta) {
  7636. var result = 0;
  7637. if (Math.abs(target - current) <= maxDelta) {
  7638. result = target;
  7639. }
  7640. else {
  7641. result = current + Scalar.Sign(target - current) * maxDelta;
  7642. }
  7643. return result;
  7644. };
  7645. /**
  7646. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7647. *
  7648. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7649. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7650. */
  7651. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7652. var num = Scalar.DeltaAngle(current, target);
  7653. var result = 0;
  7654. if (-maxDelta < num && num < maxDelta) {
  7655. result = target;
  7656. }
  7657. else {
  7658. target = current + num;
  7659. result = Scalar.MoveTowards(current, target, maxDelta);
  7660. }
  7661. return result;
  7662. };
  7663. /**
  7664. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7665. */
  7666. Scalar.Lerp = function (start, end, amount) {
  7667. return start + ((end - start) * amount);
  7668. };
  7669. /**
  7670. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7671. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7672. */
  7673. Scalar.LerpAngle = function (start, end, amount) {
  7674. var num = Scalar.Repeat(end - start, 360.0);
  7675. if (num > 180.0) {
  7676. num -= 360.0;
  7677. }
  7678. return start + num * Scalar.Clamp(amount);
  7679. };
  7680. /**
  7681. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7682. */
  7683. Scalar.InverseLerp = function (a, b, value) {
  7684. var result = 0;
  7685. if (a != b) {
  7686. result = Scalar.Clamp((value - a) / (b - a));
  7687. }
  7688. else {
  7689. result = 0.0;
  7690. }
  7691. return result;
  7692. };
  7693. /**
  7694. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7695. */
  7696. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7697. var squared = amount * amount;
  7698. var cubed = amount * squared;
  7699. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7700. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7701. var part3 = (cubed - (2.0 * squared)) + amount;
  7702. var part4 = cubed - squared;
  7703. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7704. };
  7705. /**
  7706. * Returns a random float number between and min and max values
  7707. */
  7708. Scalar.RandomRange = function (min, max) {
  7709. if (min === max)
  7710. return min;
  7711. return ((Math.random() * (max - min)) + min);
  7712. };
  7713. /**
  7714. * This function returns percentage of a number in a given range.
  7715. *
  7716. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7717. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7718. */
  7719. Scalar.RangeToPercent = function (number, min, max) {
  7720. return ((number - min) / (max - min));
  7721. };
  7722. /**
  7723. * This function returns number that corresponds to the percentage in a given range.
  7724. *
  7725. * PercentToRange(0.34,0,100) will return 34.
  7726. */
  7727. Scalar.PercentToRange = function (percent, min, max) {
  7728. return ((max - min) * percent + min);
  7729. };
  7730. /**
  7731. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7732. * @param angle The angle to normalize in radian.
  7733. * @return The converted angle.
  7734. */
  7735. Scalar.NormalizeRadians = function (angle) {
  7736. // More precise but slower version kept for reference.
  7737. // angle = angle % Tools.TwoPi;
  7738. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7739. //if (angle > Math.PI) {
  7740. // angle -= Tools.TwoPi;
  7741. //}
  7742. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7743. return angle;
  7744. };
  7745. /**
  7746. * Two pi constants convenient for computation.
  7747. */
  7748. Scalar.TwoPi = Math.PI * 2;
  7749. return Scalar;
  7750. }());
  7751. BABYLON.Scalar = Scalar;
  7752. })(BABYLON || (BABYLON = {}));
  7753. //# sourceMappingURL=babylon.math.scalar.js.map
  7754. //# sourceMappingURL=babylon.mixins.js.map
  7755. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7756. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7757. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7758. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7759. //# sourceMappingURL=babylon.webgl2.js.map
  7760. var BABYLON;
  7761. (function (BABYLON) {
  7762. var __decoratorInitialStore = {};
  7763. var __mergedStore = {};
  7764. var _copySource = function (creationFunction, source, instanciate) {
  7765. var destination = creationFunction();
  7766. // Tags
  7767. if (BABYLON.Tags) {
  7768. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7769. }
  7770. var classStore = getMergedStore(destination);
  7771. // Properties
  7772. for (var property in classStore) {
  7773. var propertyDescriptor = classStore[property];
  7774. var sourceProperty = source[property];
  7775. var propertyType = propertyDescriptor.type;
  7776. if (sourceProperty !== undefined && sourceProperty !== null) {
  7777. switch (propertyType) {
  7778. case 0: // Value
  7779. case 6: // Mesh reference
  7780. case 11: // Camera reference
  7781. destination[property] = sourceProperty;
  7782. break;
  7783. case 1: // Texture
  7784. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. case 2: // Color3
  7787. case 3: // FresnelParameters
  7788. case 4: // Vector2
  7789. case 5: // Vector3
  7790. case 7: // Color Curves
  7791. case 10: // Quaternion
  7792. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7793. break;
  7794. }
  7795. }
  7796. }
  7797. return destination;
  7798. };
  7799. function getDirectStore(target) {
  7800. var classKey = target.getClassName();
  7801. if (!__decoratorInitialStore[classKey]) {
  7802. __decoratorInitialStore[classKey] = {};
  7803. }
  7804. return __decoratorInitialStore[classKey];
  7805. }
  7806. /**
  7807. * Return the list of properties flagged as serializable
  7808. * @param target: host object
  7809. */
  7810. function getMergedStore(target) {
  7811. var classKey = target.getClassName();
  7812. if (__mergedStore[classKey]) {
  7813. return __mergedStore[classKey];
  7814. }
  7815. __mergedStore[classKey] = {};
  7816. var store = __mergedStore[classKey];
  7817. var currentTarget = target;
  7818. var currentKey = classKey;
  7819. while (currentKey) {
  7820. var initialStore = __decoratorInitialStore[currentKey];
  7821. for (var property in initialStore) {
  7822. store[property] = initialStore[property];
  7823. }
  7824. var parent_1 = void 0;
  7825. var done = false;
  7826. do {
  7827. parent_1 = Object.getPrototypeOf(currentTarget);
  7828. if (!parent_1.getClassName) {
  7829. done = true;
  7830. break;
  7831. }
  7832. if (parent_1.getClassName() !== currentKey) {
  7833. break;
  7834. }
  7835. currentTarget = parent_1;
  7836. } while (parent_1);
  7837. if (done) {
  7838. break;
  7839. }
  7840. currentKey = parent_1.getClassName();
  7841. currentTarget = parent_1;
  7842. }
  7843. return store;
  7844. }
  7845. function generateSerializableMember(type, sourceName) {
  7846. return function (target, propertyKey) {
  7847. var classStore = getDirectStore(target);
  7848. if (!classStore[propertyKey]) {
  7849. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7850. }
  7851. };
  7852. }
  7853. function generateExpandMember(setCallback, targetKey) {
  7854. if (targetKey === void 0) { targetKey = null; }
  7855. return function (target, propertyKey) {
  7856. var key = targetKey || ("_" + propertyKey);
  7857. Object.defineProperty(target, propertyKey, {
  7858. get: function () {
  7859. return this[key];
  7860. },
  7861. set: function (value) {
  7862. if (this[key] === value) {
  7863. return;
  7864. }
  7865. this[key] = value;
  7866. target[setCallback].apply(this);
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. };
  7872. }
  7873. function expandToProperty(callback, targetKey) {
  7874. if (targetKey === void 0) { targetKey = null; }
  7875. return generateExpandMember(callback, targetKey);
  7876. }
  7877. BABYLON.expandToProperty = expandToProperty;
  7878. function serialize(sourceName) {
  7879. return generateSerializableMember(0, sourceName); // value member
  7880. }
  7881. BABYLON.serialize = serialize;
  7882. function serializeAsTexture(sourceName) {
  7883. return generateSerializableMember(1, sourceName); // texture member
  7884. }
  7885. BABYLON.serializeAsTexture = serializeAsTexture;
  7886. function serializeAsColor3(sourceName) {
  7887. return generateSerializableMember(2, sourceName); // color3 member
  7888. }
  7889. BABYLON.serializeAsColor3 = serializeAsColor3;
  7890. function serializeAsFresnelParameters(sourceName) {
  7891. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7892. }
  7893. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7894. function serializeAsVector2(sourceName) {
  7895. return generateSerializableMember(4, sourceName); // vector2 member
  7896. }
  7897. BABYLON.serializeAsVector2 = serializeAsVector2;
  7898. function serializeAsVector3(sourceName) {
  7899. return generateSerializableMember(5, sourceName); // vector3 member
  7900. }
  7901. BABYLON.serializeAsVector3 = serializeAsVector3;
  7902. function serializeAsMeshReference(sourceName) {
  7903. return generateSerializableMember(6, sourceName); // mesh reference member
  7904. }
  7905. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7906. function serializeAsColorCurves(sourceName) {
  7907. return generateSerializableMember(7, sourceName); // color curves
  7908. }
  7909. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7910. function serializeAsColor4(sourceName) {
  7911. return generateSerializableMember(8, sourceName); // color 4
  7912. }
  7913. BABYLON.serializeAsColor4 = serializeAsColor4;
  7914. function serializeAsImageProcessingConfiguration(sourceName) {
  7915. return generateSerializableMember(9, sourceName); // image processing
  7916. }
  7917. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7918. function serializeAsQuaternion(sourceName) {
  7919. return generateSerializableMember(10, sourceName); // quaternion member
  7920. }
  7921. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7922. /**
  7923. * Decorator used to define property that can be serialized as reference to a camera
  7924. * @param sourceName defines the name of the property to decorate
  7925. */
  7926. function serializeAsCameraReference(sourceName) {
  7927. return generateSerializableMember(11, sourceName); // camera reference member
  7928. }
  7929. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7930. var SerializationHelper = /** @class */ (function () {
  7931. function SerializationHelper() {
  7932. }
  7933. SerializationHelper.Serialize = function (entity, serializationObject) {
  7934. if (!serializationObject) {
  7935. serializationObject = {};
  7936. }
  7937. // Tags
  7938. if (BABYLON.Tags) {
  7939. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7940. }
  7941. var serializedProperties = getMergedStore(entity);
  7942. // Properties
  7943. for (var property in serializedProperties) {
  7944. var propertyDescriptor = serializedProperties[property];
  7945. var targetPropertyName = propertyDescriptor.sourceName || property;
  7946. var propertyType = propertyDescriptor.type;
  7947. var sourceProperty = entity[property];
  7948. if (sourceProperty !== undefined && sourceProperty !== null) {
  7949. switch (propertyType) {
  7950. case 0: // Value
  7951. serializationObject[targetPropertyName] = sourceProperty;
  7952. break;
  7953. case 1: // Texture
  7954. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7955. break;
  7956. case 2: // Color3
  7957. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7958. break;
  7959. case 3: // FresnelParameters
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 4: // Vector2
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 5: // Vector3
  7966. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7967. break;
  7968. case 6: // Mesh reference
  7969. serializationObject[targetPropertyName] = sourceProperty.id;
  7970. break;
  7971. case 7: // Color Curves
  7972. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7973. break;
  7974. case 8: // Color 4
  7975. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7976. break;
  7977. case 9: // Image Processing
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 10: // Quaternion
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 11: // Camera reference
  7984. serializationObject[targetPropertyName] = sourceProperty.id;
  7985. break;
  7986. }
  7987. }
  7988. }
  7989. return serializationObject;
  7990. };
  7991. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7992. if (rootUrl === void 0) { rootUrl = null; }
  7993. var destination = creationFunction();
  7994. if (!rootUrl) {
  7995. rootUrl = "";
  7996. }
  7997. // Tags
  7998. if (BABYLON.Tags) {
  7999. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8000. }
  8001. var classStore = getMergedStore(destination);
  8002. // Properties
  8003. for (var property in classStore) {
  8004. var propertyDescriptor = classStore[property];
  8005. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8006. var propertyType = propertyDescriptor.type;
  8007. if (sourceProperty !== undefined && sourceProperty !== null) {
  8008. var dest = destination;
  8009. switch (propertyType) {
  8010. case 0: // Value
  8011. dest[property] = sourceProperty;
  8012. break;
  8013. case 1: // Texture
  8014. if (scene) {
  8015. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8016. }
  8017. break;
  8018. case 2: // Color3
  8019. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8020. break;
  8021. case 3: // FresnelParameters
  8022. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8023. break;
  8024. case 4: // Vector2
  8025. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8026. break;
  8027. case 5: // Vector3
  8028. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8029. break;
  8030. case 6: // Mesh reference
  8031. if (scene) {
  8032. dest[property] = scene.getLastMeshByID(sourceProperty);
  8033. }
  8034. break;
  8035. case 7: // Color Curves
  8036. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8037. break;
  8038. case 8: // Color 4
  8039. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8040. break;
  8041. case 9: // Image Processing
  8042. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8043. break;
  8044. case 10: // Quaternion
  8045. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8046. break;
  8047. case 11: // Camera reference
  8048. if (scene) {
  8049. dest[property] = scene.getCameraByID(sourceProperty);
  8050. }
  8051. break;
  8052. }
  8053. }
  8054. }
  8055. return destination;
  8056. };
  8057. SerializationHelper.Clone = function (creationFunction, source) {
  8058. return _copySource(creationFunction, source, false);
  8059. };
  8060. SerializationHelper.Instanciate = function (creationFunction, source) {
  8061. return _copySource(creationFunction, source, true);
  8062. };
  8063. return SerializationHelper;
  8064. }());
  8065. BABYLON.SerializationHelper = SerializationHelper;
  8066. })(BABYLON || (BABYLON = {}));
  8067. //# sourceMappingURL=babylon.decorators.js.map
  8068. var BABYLON;
  8069. (function (BABYLON) {
  8070. /**
  8071. * Wrapper class for promise with external resolve and reject.
  8072. */
  8073. var Deferred = /** @class */ (function () {
  8074. /**
  8075. * Constructor for this deferred object.
  8076. */
  8077. function Deferred() {
  8078. var _this = this;
  8079. this.promise = new Promise(function (resolve, reject) {
  8080. _this._resolve = resolve;
  8081. _this._reject = reject;
  8082. });
  8083. }
  8084. Object.defineProperty(Deferred.prototype, "resolve", {
  8085. /**
  8086. * The resolve method of the promise associated with this deferred object.
  8087. */
  8088. get: function () {
  8089. return this._resolve;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Deferred.prototype, "reject", {
  8095. /**
  8096. * The reject method of the promise associated with this deferred object.
  8097. */
  8098. get: function () {
  8099. return this._reject;
  8100. },
  8101. enumerable: true,
  8102. configurable: true
  8103. });
  8104. return Deferred;
  8105. }());
  8106. BABYLON.Deferred = Deferred;
  8107. })(BABYLON || (BABYLON = {}));
  8108. //# sourceMappingURL=babylon.deferred.js.map
  8109. var BABYLON;
  8110. (function (BABYLON) {
  8111. /**
  8112. * A class serves as a medium between the observable and its observers
  8113. */
  8114. var EventState = /** @class */ (function () {
  8115. /**
  8116. * Create a new EventState
  8117. * @param mask defines the mask associated with this state
  8118. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8119. * @param target defines the original target of the state
  8120. * @param currentTarget defines the current target of the state
  8121. */
  8122. function EventState(mask, skipNextObservers, target, currentTarget) {
  8123. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8124. this.initalize(mask, skipNextObservers, target, currentTarget);
  8125. }
  8126. /**
  8127. * Initialize the current event state
  8128. * @param mask defines the mask associated with this state
  8129. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8130. * @param target defines the original target of the state
  8131. * @param currentTarget defines the current target of the state
  8132. * @returns the current event state
  8133. */
  8134. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8135. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8136. this.mask = mask;
  8137. this.skipNextObservers = skipNextObservers;
  8138. this.target = target;
  8139. this.currentTarget = currentTarget;
  8140. return this;
  8141. };
  8142. return EventState;
  8143. }());
  8144. BABYLON.EventState = EventState;
  8145. /**
  8146. * Represent an Observer registered to a given Observable object.
  8147. */
  8148. var Observer = /** @class */ (function () {
  8149. /**
  8150. * Creates a new observer
  8151. * @param callback defines the callback to call when the observer is notified
  8152. * @param mask defines the mask of the observer (used to filter notifications)
  8153. * @param scope defines the current scope used to restore the JS context
  8154. */
  8155. function Observer(
  8156. /**
  8157. * Defines the callback to call when the observer is notified
  8158. */
  8159. callback,
  8160. /**
  8161. * Defines the mask of the observer (used to filter notifications)
  8162. */
  8163. mask,
  8164. /**
  8165. * Defines the current scope used to restore the JS context
  8166. */
  8167. scope) {
  8168. if (scope === void 0) { scope = null; }
  8169. this.callback = callback;
  8170. this.mask = mask;
  8171. this.scope = scope;
  8172. /** @hidden */
  8173. this._willBeUnregistered = false;
  8174. /**
  8175. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8176. */
  8177. this.unregisterOnNextCall = false;
  8178. }
  8179. return Observer;
  8180. }());
  8181. BABYLON.Observer = Observer;
  8182. /**
  8183. * Represent a list of observers registered to multiple Observables object.
  8184. */
  8185. var MultiObserver = /** @class */ (function () {
  8186. function MultiObserver() {
  8187. }
  8188. /**
  8189. * Release associated resources
  8190. */
  8191. MultiObserver.prototype.dispose = function () {
  8192. if (this._observers && this._observables) {
  8193. for (var index = 0; index < this._observers.length; index++) {
  8194. this._observables[index].remove(this._observers[index]);
  8195. }
  8196. }
  8197. this._observers = null;
  8198. this._observables = null;
  8199. };
  8200. /**
  8201. * Raise a callback when one of the observable will notify
  8202. * @param observables defines a list of observables to watch
  8203. * @param callback defines the callback to call on notification
  8204. * @param mask defines the mask used to filter notifications
  8205. * @param scope defines the current scope used to restore the JS context
  8206. * @returns the new MultiObserver
  8207. */
  8208. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8209. if (mask === void 0) { mask = -1; }
  8210. if (scope === void 0) { scope = null; }
  8211. var result = new MultiObserver();
  8212. result._observers = new Array();
  8213. result._observables = observables;
  8214. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8215. var observable = observables_1[_i];
  8216. var observer = observable.add(callback, mask, false, scope);
  8217. if (observer) {
  8218. result._observers.push(observer);
  8219. }
  8220. }
  8221. return result;
  8222. };
  8223. return MultiObserver;
  8224. }());
  8225. BABYLON.MultiObserver = MultiObserver;
  8226. /**
  8227. * The Observable class is a simple implementation of the Observable pattern.
  8228. *
  8229. * 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.
  8230. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8231. * 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).
  8232. * 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.
  8233. */
  8234. var Observable = /** @class */ (function () {
  8235. /**
  8236. * Creates a new observable
  8237. * @param onObserverAdded defines a callback to call when a new observer is added
  8238. */
  8239. function Observable(onObserverAdded) {
  8240. this._observers = new Array();
  8241. this._eventState = new EventState(0);
  8242. if (onObserverAdded) {
  8243. this._onObserverAdded = onObserverAdded;
  8244. }
  8245. }
  8246. /**
  8247. * Create a new Observer with the specified callback
  8248. * @param callback the callback that will be executed for that Observer
  8249. * @param mask the mask used to filter observers
  8250. * @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.
  8251. * @param scope optional scope for the callback to be called from
  8252. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8253. * @returns the new observer created for the callback
  8254. */
  8255. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8256. if (mask === void 0) { mask = -1; }
  8257. if (insertFirst === void 0) { insertFirst = false; }
  8258. if (scope === void 0) { scope = null; }
  8259. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8260. if (!callback) {
  8261. return null;
  8262. }
  8263. var observer = new Observer(callback, mask, scope);
  8264. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8265. if (insertFirst) {
  8266. this._observers.unshift(observer);
  8267. }
  8268. else {
  8269. this._observers.push(observer);
  8270. }
  8271. if (this._onObserverAdded) {
  8272. this._onObserverAdded(observer);
  8273. }
  8274. return observer;
  8275. };
  8276. /**
  8277. * Create a new Observer with the specified callback and unregisters after the next notification
  8278. * @param callback the callback that will be executed for that Observer
  8279. * @returns the new observer created for the callback
  8280. */
  8281. Observable.prototype.addOnce = function (callback) {
  8282. return this.add(callback, undefined, undefined, undefined, true);
  8283. };
  8284. /**
  8285. * Remove an Observer from the Observable object
  8286. * @param observer the instance of the Observer to remove
  8287. * @returns false if it doesn't belong to this Observable
  8288. */
  8289. Observable.prototype.remove = function (observer) {
  8290. if (!observer) {
  8291. return false;
  8292. }
  8293. var index = this._observers.indexOf(observer);
  8294. if (index !== -1) {
  8295. this._observers.splice(index, 1);
  8296. return true;
  8297. }
  8298. return false;
  8299. };
  8300. /**
  8301. * Remove a callback from the Observable object
  8302. * @param callback the callback to remove
  8303. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8304. * @returns false if it doesn't belong to this Observable
  8305. */
  8306. Observable.prototype.removeCallback = function (callback, scope) {
  8307. for (var index = 0; index < this._observers.length; index++) {
  8308. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8309. this._observers.splice(index, 1);
  8310. return true;
  8311. }
  8312. }
  8313. return false;
  8314. };
  8315. Observable.prototype._deferUnregister = function (observer) {
  8316. var _this = this;
  8317. observer.unregisterOnNextCall = false;
  8318. observer._willBeUnregistered = true;
  8319. BABYLON.Tools.SetImmediate(function () {
  8320. _this.remove(observer);
  8321. });
  8322. };
  8323. /**
  8324. * Notify all Observers by calling their respective callback with the given data
  8325. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8326. * @param eventData defines the data to send to all observers
  8327. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8328. * @param target defines the original target of the state
  8329. * @param currentTarget defines the current target of the state
  8330. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8331. */
  8332. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8333. if (mask === void 0) { mask = -1; }
  8334. if (!this._observers.length) {
  8335. return true;
  8336. }
  8337. var state = this._eventState;
  8338. state.mask = mask;
  8339. state.target = target;
  8340. state.currentTarget = currentTarget;
  8341. state.skipNextObservers = false;
  8342. state.lastReturnValue = eventData;
  8343. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8344. var obs = _a[_i];
  8345. if (obs._willBeUnregistered) {
  8346. continue;
  8347. }
  8348. if (obs.mask & mask) {
  8349. if (obs.scope) {
  8350. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8351. }
  8352. else {
  8353. state.lastReturnValue = obs.callback(eventData, state);
  8354. }
  8355. if (obs.unregisterOnNextCall) {
  8356. this._deferUnregister(obs);
  8357. }
  8358. }
  8359. if (state.skipNextObservers) {
  8360. return false;
  8361. }
  8362. }
  8363. return true;
  8364. };
  8365. /**
  8366. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8367. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8368. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8369. * and it is crucial that all callbacks will be executed.
  8370. * The order of the callbacks is kept, callbacks are not executed parallel.
  8371. *
  8372. * @param eventData The data to be sent to each callback
  8373. * @param mask is used to filter observers defaults to -1
  8374. * @param target defines the callback target (see EventState)
  8375. * @param currentTarget defines he current object in the bubbling phase
  8376. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8377. */
  8378. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8379. var _this = this;
  8380. if (mask === void 0) { mask = -1; }
  8381. // create an empty promise
  8382. var p = Promise.resolve(eventData);
  8383. // no observers? return this promise.
  8384. if (!this._observers.length) {
  8385. return p;
  8386. }
  8387. var state = this._eventState;
  8388. state.mask = mask;
  8389. state.target = target;
  8390. state.currentTarget = currentTarget;
  8391. state.skipNextObservers = false;
  8392. // execute one callback after another (not using Promise.all, the order is important)
  8393. this._observers.forEach(function (obs) {
  8394. if (state.skipNextObservers) {
  8395. return;
  8396. }
  8397. if (obs._willBeUnregistered) {
  8398. return;
  8399. }
  8400. if (obs.mask & mask) {
  8401. if (obs.scope) {
  8402. p = p.then(function (lastReturnedValue) {
  8403. state.lastReturnValue = lastReturnedValue;
  8404. return obs.callback.apply(obs.scope, [eventData, state]);
  8405. });
  8406. }
  8407. else {
  8408. p = p.then(function (lastReturnedValue) {
  8409. state.lastReturnValue = lastReturnedValue;
  8410. return obs.callback(eventData, state);
  8411. });
  8412. }
  8413. if (obs.unregisterOnNextCall) {
  8414. _this._deferUnregister(obs);
  8415. }
  8416. }
  8417. });
  8418. // return the eventData
  8419. return p.then(function () { return eventData; });
  8420. };
  8421. /**
  8422. * Notify a specific observer
  8423. * @param observer defines the observer to notify
  8424. * @param eventData defines the data to be sent to each callback
  8425. * @param mask is used to filter observers defaults to -1
  8426. */
  8427. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8428. if (mask === void 0) { mask = -1; }
  8429. var state = this._eventState;
  8430. state.mask = mask;
  8431. state.skipNextObservers = false;
  8432. observer.callback(eventData, state);
  8433. };
  8434. /**
  8435. * Gets a boolean indicating if the observable has at least one observer
  8436. * @returns true is the Observable has at least one Observer registered
  8437. */
  8438. Observable.prototype.hasObservers = function () {
  8439. return this._observers.length > 0;
  8440. };
  8441. /**
  8442. * Clear the list of observers
  8443. */
  8444. Observable.prototype.clear = function () {
  8445. this._observers = new Array();
  8446. this._onObserverAdded = null;
  8447. };
  8448. /**
  8449. * Clone the current observable
  8450. * @returns a new observable
  8451. */
  8452. Observable.prototype.clone = function () {
  8453. var result = new Observable();
  8454. result._observers = this._observers.slice(0);
  8455. return result;
  8456. };
  8457. /**
  8458. * Does this observable handles observer registered with a given mask
  8459. * @param mask defines the mask to be tested
  8460. * @return whether or not one observer registered with the given mask is handeled
  8461. **/
  8462. Observable.prototype.hasSpecificMask = function (mask) {
  8463. if (mask === void 0) { mask = -1; }
  8464. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8465. var obs = _a[_i];
  8466. if (obs.mask & mask || obs.mask === mask) {
  8467. return true;
  8468. }
  8469. }
  8470. return false;
  8471. };
  8472. return Observable;
  8473. }());
  8474. BABYLON.Observable = Observable;
  8475. })(BABYLON || (BABYLON = {}));
  8476. //# sourceMappingURL=babylon.observable.js.map
  8477. var BABYLON;
  8478. (function (BABYLON) {
  8479. var SmartArray = /** @class */ (function () {
  8480. function SmartArray(capacity) {
  8481. this.length = 0;
  8482. this.data = new Array(capacity);
  8483. this._id = SmartArray._GlobalId++;
  8484. }
  8485. SmartArray.prototype.push = function (value) {
  8486. this.data[this.length++] = value;
  8487. if (this.length > this.data.length) {
  8488. this.data.length *= 2;
  8489. }
  8490. };
  8491. SmartArray.prototype.forEach = function (func) {
  8492. for (var index = 0; index < this.length; index++) {
  8493. func(this.data[index]);
  8494. }
  8495. };
  8496. SmartArray.prototype.sort = function (compareFn) {
  8497. this.data.sort(compareFn);
  8498. };
  8499. SmartArray.prototype.reset = function () {
  8500. this.length = 0;
  8501. };
  8502. SmartArray.prototype.dispose = function () {
  8503. this.reset();
  8504. if (this.data) {
  8505. this.data.length = 0;
  8506. this.data = [];
  8507. }
  8508. };
  8509. SmartArray.prototype.concat = function (array) {
  8510. if (array.length === 0) {
  8511. return;
  8512. }
  8513. if (this.length + array.length > this.data.length) {
  8514. this.data.length = (this.length + array.length) * 2;
  8515. }
  8516. for (var index = 0; index < array.length; index++) {
  8517. this.data[this.length++] = (array.data || array)[index];
  8518. }
  8519. };
  8520. SmartArray.prototype.indexOf = function (value) {
  8521. var position = this.data.indexOf(value);
  8522. if (position >= this.length) {
  8523. return -1;
  8524. }
  8525. return position;
  8526. };
  8527. SmartArray.prototype.contains = function (value) {
  8528. return this.data.indexOf(value) !== -1;
  8529. };
  8530. // Statics
  8531. SmartArray._GlobalId = 0;
  8532. return SmartArray;
  8533. }());
  8534. BABYLON.SmartArray = SmartArray;
  8535. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8536. __extends(SmartArrayNoDuplicate, _super);
  8537. function SmartArrayNoDuplicate() {
  8538. var _this = _super !== null && _super.apply(this, arguments) || this;
  8539. _this._duplicateId = 0;
  8540. return _this;
  8541. }
  8542. SmartArrayNoDuplicate.prototype.push = function (value) {
  8543. _super.prototype.push.call(this, value);
  8544. if (!value.__smartArrayFlags) {
  8545. value.__smartArrayFlags = {};
  8546. }
  8547. value.__smartArrayFlags[this._id] = this._duplicateId;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8550. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8551. return false;
  8552. }
  8553. this.push(value);
  8554. return true;
  8555. };
  8556. SmartArrayNoDuplicate.prototype.reset = function () {
  8557. _super.prototype.reset.call(this);
  8558. this._duplicateId++;
  8559. };
  8560. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8561. if (array.length === 0) {
  8562. return;
  8563. }
  8564. if (this.length + array.length > this.data.length) {
  8565. this.data.length = (this.length + array.length) * 2;
  8566. }
  8567. for (var index = 0; index < array.length; index++) {
  8568. var item = (array.data || array)[index];
  8569. this.pushNoDuplicate(item);
  8570. }
  8571. };
  8572. return SmartArrayNoDuplicate;
  8573. }(SmartArray));
  8574. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8575. })(BABYLON || (BABYLON = {}));
  8576. //# sourceMappingURL=babylon.smartArray.js.map
  8577. var BABYLON;
  8578. (function (BABYLON) {
  8579. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8580. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8581. var LoadFileError = /** @class */ (function (_super) {
  8582. __extends(LoadFileError, _super);
  8583. function LoadFileError(message, request) {
  8584. var _this = _super.call(this, message) || this;
  8585. _this.request = request;
  8586. _this.name = "LoadFileError";
  8587. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8588. return _this;
  8589. }
  8590. // Polyfill for Object.setPrototypeOf if necessary.
  8591. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8592. return LoadFileError;
  8593. }(Error));
  8594. BABYLON.LoadFileError = LoadFileError;
  8595. var RetryStrategy = /** @class */ (function () {
  8596. function RetryStrategy() {
  8597. }
  8598. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8599. if (maxRetries === void 0) { maxRetries = 3; }
  8600. if (baseInterval === void 0) { baseInterval = 500; }
  8601. return function (url, request, retryIndex) {
  8602. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8603. return -1;
  8604. }
  8605. return Math.pow(2, retryIndex) * baseInterval;
  8606. };
  8607. };
  8608. return RetryStrategy;
  8609. }());
  8610. BABYLON.RetryStrategy = RetryStrategy;
  8611. // Screenshots
  8612. var screenshotCanvas;
  8613. var cloneValue = function (source, destinationObject) {
  8614. if (!source)
  8615. return null;
  8616. if (source instanceof BABYLON.Mesh) {
  8617. return null;
  8618. }
  8619. if (source instanceof BABYLON.SubMesh) {
  8620. return source.clone(destinationObject);
  8621. }
  8622. else if (source.clone) {
  8623. return source.clone();
  8624. }
  8625. return null;
  8626. };
  8627. var Tools = /** @class */ (function () {
  8628. function Tools() {
  8629. }
  8630. /**
  8631. * Interpolates between a and b via alpha
  8632. * @param a The lower value (returned when alpha = 0)
  8633. * @param b The upper value (returned when alpha = 1)
  8634. * @param alpha The interpolation-factor
  8635. * @return The mixed value
  8636. */
  8637. Tools.Mix = function (a, b, alpha) {
  8638. return a * (1 - alpha) + b * alpha;
  8639. };
  8640. Tools.Instantiate = function (className) {
  8641. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8642. return Tools.RegisteredExternalClasses[className];
  8643. }
  8644. var arr = className.split(".");
  8645. var fn = (window || this);
  8646. for (var i = 0, len = arr.length; i < len; i++) {
  8647. fn = fn[arr[i]];
  8648. }
  8649. if (typeof fn !== "function") {
  8650. return null;
  8651. }
  8652. return fn;
  8653. };
  8654. /**
  8655. * Provides a slice function that will work even on IE
  8656. * @param data defines the array to slice
  8657. * @param start defines the start of the data (optional)
  8658. * @param end defines the end of the data (optional)
  8659. * @returns the new sliced array
  8660. */
  8661. Tools.Slice = function (data, start, end) {
  8662. if (data.slice) {
  8663. return data.slice(start, end);
  8664. }
  8665. return Array.prototype.slice.call(data, start, end);
  8666. };
  8667. Tools.SetImmediate = function (action) {
  8668. if (window.setImmediate) {
  8669. window.setImmediate(action);
  8670. }
  8671. else {
  8672. setTimeout(action, 1);
  8673. }
  8674. };
  8675. Tools.IsExponentOfTwo = function (value) {
  8676. var count = 1;
  8677. do {
  8678. count *= 2;
  8679. } while (count < value);
  8680. return count === value;
  8681. };
  8682. /**
  8683. * Returns the nearest 32-bit single precision float representation of a Number
  8684. * @param value A Number. If the parameter is of a different type, it will get converted
  8685. * to a number or to NaN if it cannot be converted
  8686. * @returns number
  8687. */
  8688. Tools.FloatRound = function (value) {
  8689. if (Math.fround) {
  8690. return Math.fround(value);
  8691. }
  8692. return (Tools._tmpFloatArray[0] = value);
  8693. };
  8694. /**
  8695. * Find the next highest power of two.
  8696. * @param x Number to start search from.
  8697. * @return Next highest power of two.
  8698. */
  8699. Tools.CeilingPOT = function (x) {
  8700. x--;
  8701. x |= x >> 1;
  8702. x |= x >> 2;
  8703. x |= x >> 4;
  8704. x |= x >> 8;
  8705. x |= x >> 16;
  8706. x++;
  8707. return x;
  8708. };
  8709. /**
  8710. * Find the next lowest power of two.
  8711. * @param x Number to start search from.
  8712. * @return Next lowest power of two.
  8713. */
  8714. Tools.FloorPOT = function (x) {
  8715. x = x | (x >> 1);
  8716. x = x | (x >> 2);
  8717. x = x | (x >> 4);
  8718. x = x | (x >> 8);
  8719. x = x | (x >> 16);
  8720. return x - (x >> 1);
  8721. };
  8722. /**
  8723. * Find the nearest power of two.
  8724. * @param x Number to start search from.
  8725. * @return Next nearest power of two.
  8726. */
  8727. Tools.NearestPOT = function (x) {
  8728. var c = Tools.CeilingPOT(x);
  8729. var f = Tools.FloorPOT(x);
  8730. return (c - x) > (x - f) ? f : c;
  8731. };
  8732. Tools.GetExponentOfTwo = function (value, max, mode) {
  8733. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8734. var pot;
  8735. switch (mode) {
  8736. case BABYLON.Engine.SCALEMODE_FLOOR:
  8737. pot = Tools.FloorPOT(value);
  8738. break;
  8739. case BABYLON.Engine.SCALEMODE_NEAREST:
  8740. pot = Tools.NearestPOT(value);
  8741. break;
  8742. case BABYLON.Engine.SCALEMODE_CEILING:
  8743. default:
  8744. pot = Tools.CeilingPOT(value);
  8745. break;
  8746. }
  8747. return Math.min(pot, max);
  8748. };
  8749. Tools.GetFilename = function (path) {
  8750. var index = path.lastIndexOf("/");
  8751. if (index < 0)
  8752. return path;
  8753. return path.substring(index + 1);
  8754. };
  8755. /**
  8756. * Extracts the "folder" part of a path (everything before the filename).
  8757. * @param uri The URI to extract the info from
  8758. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8759. * @returns The "folder" part of the path
  8760. */
  8761. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8762. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8763. var index = uri.lastIndexOf("/");
  8764. if (index < 0) {
  8765. if (returnUnchangedIfNoSlash) {
  8766. return uri;
  8767. }
  8768. return "";
  8769. }
  8770. return uri.substring(0, index + 1);
  8771. };
  8772. Tools.GetDOMTextContent = function (element) {
  8773. var result = "";
  8774. var child = element.firstChild;
  8775. while (child) {
  8776. if (child.nodeType === 3) {
  8777. result += child.textContent;
  8778. }
  8779. child = child.nextSibling;
  8780. }
  8781. return result;
  8782. };
  8783. Tools.ToDegrees = function (angle) {
  8784. return angle * 180 / Math.PI;
  8785. };
  8786. Tools.ToRadians = function (angle) {
  8787. return angle * Math.PI / 180;
  8788. };
  8789. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8790. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8791. var output = "";
  8792. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8793. var i = 0;
  8794. var bytes = new Uint8Array(buffer);
  8795. while (i < bytes.length) {
  8796. chr1 = bytes[i++];
  8797. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8798. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8799. enc1 = chr1 >> 2;
  8800. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8801. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8802. enc4 = chr3 & 63;
  8803. if (isNaN(chr2)) {
  8804. enc3 = enc4 = 64;
  8805. }
  8806. else if (isNaN(chr3)) {
  8807. enc4 = 64;
  8808. }
  8809. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8810. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8811. }
  8812. return "data:image/png;base64," + output;
  8813. };
  8814. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8815. if (bias === void 0) { bias = null; }
  8816. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8817. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8818. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8819. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8820. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8821. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8822. }
  8823. if (bias) {
  8824. minimum.x -= minimum.x * bias.x + bias.y;
  8825. minimum.y -= minimum.y * bias.x + bias.y;
  8826. minimum.z -= minimum.z * bias.x + bias.y;
  8827. maximum.x += maximum.x * bias.x + bias.y;
  8828. maximum.y += maximum.y * bias.x + bias.y;
  8829. maximum.z += maximum.z * bias.x + bias.y;
  8830. }
  8831. return {
  8832. minimum: minimum,
  8833. maximum: maximum
  8834. };
  8835. };
  8836. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8837. if (bias === void 0) { bias = null; }
  8838. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8839. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8840. if (!stride) {
  8841. stride = 3;
  8842. }
  8843. for (var index = start; index < start + count; index++) {
  8844. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8847. }
  8848. if (bias) {
  8849. minimum.x -= minimum.x * bias.x + bias.y;
  8850. minimum.y -= minimum.y * bias.x + bias.y;
  8851. minimum.z -= minimum.z * bias.x + bias.y;
  8852. maximum.x += maximum.x * bias.x + bias.y;
  8853. maximum.y += maximum.y * bias.x + bias.y;
  8854. maximum.z += maximum.z * bias.x + bias.y;
  8855. }
  8856. return {
  8857. minimum: minimum,
  8858. maximum: maximum
  8859. };
  8860. };
  8861. Tools.Vector2ArrayFeeder = function (array) {
  8862. return function (index) {
  8863. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8864. var length = isFloatArray ? array.length / 2 : array.length;
  8865. if (index >= length) {
  8866. return null;
  8867. }
  8868. if (isFloatArray) {
  8869. var fa = array;
  8870. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8871. }
  8872. var a = array;
  8873. return a[index];
  8874. };
  8875. };
  8876. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8877. if (bias === void 0) { bias = null; }
  8878. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8879. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8880. var i = 0;
  8881. var cur = feeder(i++);
  8882. while (cur) {
  8883. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8884. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8885. cur = feeder(i++);
  8886. }
  8887. if (bias) {
  8888. minimum.x -= minimum.x * bias.x + bias.y;
  8889. minimum.y -= minimum.y * bias.x + bias.y;
  8890. maximum.x += maximum.x * bias.x + bias.y;
  8891. maximum.y += maximum.y * bias.x + bias.y;
  8892. }
  8893. return {
  8894. minimum: minimum,
  8895. maximum: maximum
  8896. };
  8897. };
  8898. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8899. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8900. return null;
  8901. return Array.isArray(obj) ? obj : [obj];
  8902. };
  8903. // Misc.
  8904. Tools.GetPointerPrefix = function () {
  8905. var eventPrefix = "pointer";
  8906. // Check if pointer events are supported
  8907. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8908. eventPrefix = "mouse";
  8909. }
  8910. return eventPrefix;
  8911. };
  8912. /**
  8913. * @param func - the function to be called
  8914. * @param requester - the object that will request the next frame. Falls back to window.
  8915. */
  8916. Tools.QueueNewFrame = function (func, requester) {
  8917. if (!Tools.IsWindowObjectExist()) {
  8918. return setTimeout(func, 16);
  8919. }
  8920. if (!requester) {
  8921. requester = window;
  8922. }
  8923. if (requester.requestAnimationFrame) {
  8924. return requester.requestAnimationFrame(func);
  8925. }
  8926. else if (requester.msRequestAnimationFrame) {
  8927. return requester.msRequestAnimationFrame(func);
  8928. }
  8929. else if (requester.webkitRequestAnimationFrame) {
  8930. return requester.webkitRequestAnimationFrame(func);
  8931. }
  8932. else if (requester.mozRequestAnimationFrame) {
  8933. return requester.mozRequestAnimationFrame(func);
  8934. }
  8935. else if (requester.oRequestAnimationFrame) {
  8936. return requester.oRequestAnimationFrame(func);
  8937. }
  8938. else {
  8939. return window.setTimeout(func, 16);
  8940. }
  8941. };
  8942. Tools.RequestFullscreen = function (element) {
  8943. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8944. if (!requestFunction)
  8945. return;
  8946. requestFunction.call(element);
  8947. };
  8948. Tools.ExitFullscreen = function () {
  8949. if (document.exitFullscreen) {
  8950. document.exitFullscreen();
  8951. }
  8952. else if (document.mozCancelFullScreen) {
  8953. document.mozCancelFullScreen();
  8954. }
  8955. else if (document.webkitCancelFullScreen) {
  8956. document.webkitCancelFullScreen();
  8957. }
  8958. else if (document.msCancelFullScreen) {
  8959. document.msCancelFullScreen();
  8960. }
  8961. };
  8962. Tools.SetCorsBehavior = function (url, element) {
  8963. if (url && url.indexOf("data:") === 0) {
  8964. return;
  8965. }
  8966. if (Tools.CorsBehavior) {
  8967. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8968. element.crossOrigin = Tools.CorsBehavior;
  8969. }
  8970. else {
  8971. var result = Tools.CorsBehavior(url);
  8972. if (result) {
  8973. element.crossOrigin = result;
  8974. }
  8975. }
  8976. }
  8977. };
  8978. // External files
  8979. Tools.CleanUrl = function (url) {
  8980. url = url.replace(/#/mg, "%23");
  8981. return url;
  8982. };
  8983. /**
  8984. * Loads an image as an HTMLImageElement.
  8985. * @param input url string, ArrayBuffer, or Blob to load
  8986. * @param onLoad callback called when the image successfully loads
  8987. * @param onError callback called when the image fails to load
  8988. * @param database database for caching
  8989. * @returns the HTMLImageElement of the loaded image
  8990. */
  8991. Tools.LoadImage = function (input, onLoad, onError, database) {
  8992. var url;
  8993. var usingObjectURL = false;
  8994. if (input instanceof ArrayBuffer) {
  8995. url = URL.createObjectURL(new Blob([input]));
  8996. usingObjectURL = true;
  8997. }
  8998. else if (input instanceof Blob) {
  8999. url = URL.createObjectURL(input);
  9000. usingObjectURL = true;
  9001. }
  9002. else {
  9003. url = Tools.CleanUrl(input);
  9004. url = Tools.PreprocessUrl(input);
  9005. }
  9006. var img = new Image();
  9007. Tools.SetCorsBehavior(url, img);
  9008. var loadHandler = function () {
  9009. if (usingObjectURL && img.src) {
  9010. URL.revokeObjectURL(img.src);
  9011. }
  9012. img.removeEventListener("load", loadHandler);
  9013. img.removeEventListener("error", errorHandler);
  9014. onLoad(img);
  9015. };
  9016. var errorHandler = function (err) {
  9017. if (usingObjectURL && img.src) {
  9018. URL.revokeObjectURL(img.src);
  9019. }
  9020. img.removeEventListener("load", loadHandler);
  9021. img.removeEventListener("error", errorHandler);
  9022. Tools.Error("Error while trying to load image: " + input);
  9023. if (onError) {
  9024. onError("Error while trying to load image: " + input, err);
  9025. }
  9026. };
  9027. img.addEventListener("load", loadHandler);
  9028. img.addEventListener("error", errorHandler);
  9029. var noIndexedDB = function () {
  9030. img.src = url;
  9031. };
  9032. var loadFromIndexedDB = function () {
  9033. if (database) {
  9034. database.loadImageFromDB(url, img);
  9035. }
  9036. };
  9037. //ANY database to do!
  9038. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9039. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9040. }
  9041. else {
  9042. if (url.indexOf("file:") !== -1) {
  9043. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9044. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9045. try {
  9046. var blobURL;
  9047. try {
  9048. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9049. }
  9050. catch (ex) {
  9051. // Chrome doesn't support oneTimeOnly parameter
  9052. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9053. }
  9054. img.src = blobURL;
  9055. usingObjectURL = true;
  9056. }
  9057. catch (e) {
  9058. img.src = "";
  9059. }
  9060. return img;
  9061. }
  9062. }
  9063. noIndexedDB();
  9064. }
  9065. return img;
  9066. };
  9067. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9068. url = Tools.CleanUrl(url);
  9069. url = Tools.PreprocessUrl(url);
  9070. // If file and file input are set
  9071. if (url.indexOf("file:") !== -1) {
  9072. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9073. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9074. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9075. }
  9076. }
  9077. var loadUrl = Tools.BaseUrl + url;
  9078. var aborted = false;
  9079. var fileRequest = {
  9080. onCompleteObservable: new BABYLON.Observable(),
  9081. abort: function () { return aborted = true; },
  9082. };
  9083. var requestFile = function () {
  9084. var request = new XMLHttpRequest();
  9085. var retryHandle = null;
  9086. fileRequest.abort = function () {
  9087. aborted = true;
  9088. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9089. request.abort();
  9090. }
  9091. if (retryHandle !== null) {
  9092. clearTimeout(retryHandle);
  9093. retryHandle = null;
  9094. }
  9095. };
  9096. var retryLoop = function (retryIndex) {
  9097. request.open('GET', loadUrl, true);
  9098. if (useArrayBuffer) {
  9099. request.responseType = "arraybuffer";
  9100. }
  9101. if (onProgress) {
  9102. request.addEventListener("progress", onProgress);
  9103. }
  9104. var onLoadEnd = function () {
  9105. request.removeEventListener("loadend", onLoadEnd);
  9106. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9107. fileRequest.onCompleteObservable.clear();
  9108. };
  9109. request.addEventListener("loadend", onLoadEnd);
  9110. var onReadyStateChange = function () {
  9111. if (aborted) {
  9112. return;
  9113. }
  9114. // In case of undefined state in some browsers.
  9115. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9116. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9117. request.removeEventListener("readystatechange", onReadyStateChange);
  9118. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9119. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9120. return;
  9121. }
  9122. var retryStrategy = Tools.DefaultRetryStrategy;
  9123. if (retryStrategy) {
  9124. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9125. if (waitTime !== -1) {
  9126. // Prevent the request from completing for retry.
  9127. request.removeEventListener("loadend", onLoadEnd);
  9128. request = new XMLHttpRequest();
  9129. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9130. return;
  9131. }
  9132. }
  9133. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9134. if (onError) {
  9135. onError(request, e);
  9136. }
  9137. else {
  9138. throw e;
  9139. }
  9140. }
  9141. };
  9142. request.addEventListener("readystatechange", onReadyStateChange);
  9143. request.send();
  9144. };
  9145. retryLoop(0);
  9146. };
  9147. // Caching all files
  9148. if (database && database.enableSceneOffline) {
  9149. var noIndexedDB_1 = function () {
  9150. if (!aborted) {
  9151. requestFile();
  9152. }
  9153. };
  9154. var loadFromIndexedDB = function () {
  9155. // TODO: database needs to support aborting and should return a IFileRequest
  9156. if (aborted) {
  9157. return;
  9158. }
  9159. if (database) {
  9160. database.loadFileFromDB(url, function (data) {
  9161. if (!aborted) {
  9162. onSuccess(data);
  9163. }
  9164. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9165. }, onProgress ? function (event) {
  9166. if (!aborted) {
  9167. onProgress(event);
  9168. }
  9169. } : undefined, noIndexedDB_1, useArrayBuffer);
  9170. }
  9171. };
  9172. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9173. }
  9174. else {
  9175. requestFile();
  9176. }
  9177. return fileRequest;
  9178. };
  9179. /**
  9180. * Load a script (identified by an url). When the url returns, the
  9181. * content of this file is added into a new script element, attached to the DOM (body element)
  9182. */
  9183. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9184. var head = document.getElementsByTagName('head')[0];
  9185. var script = document.createElement('script');
  9186. script.type = 'text/javascript';
  9187. script.src = scriptUrl;
  9188. script.onload = function () {
  9189. if (onSuccess) {
  9190. onSuccess();
  9191. }
  9192. };
  9193. script.onerror = function (e) {
  9194. if (onError) {
  9195. onError("Unable to load script '" + scriptUrl + "'", e);
  9196. }
  9197. };
  9198. head.appendChild(script);
  9199. };
  9200. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9201. var reader = new FileReader();
  9202. var request = {
  9203. onCompleteObservable: new BABYLON.Observable(),
  9204. abort: function () { return reader.abort(); },
  9205. };
  9206. reader.onloadend = function (e) {
  9207. request.onCompleteObservable.notifyObservers(request);
  9208. };
  9209. reader.onload = function (e) {
  9210. //target doesn't have result from ts 1.3
  9211. callback(e.target['result']);
  9212. };
  9213. reader.onprogress = progressCallback;
  9214. reader.readAsDataURL(fileToLoad);
  9215. return request;
  9216. };
  9217. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9218. var reader = new FileReader();
  9219. var request = {
  9220. onCompleteObservable: new BABYLON.Observable(),
  9221. abort: function () { return reader.abort(); },
  9222. };
  9223. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9224. reader.onerror = function (e) {
  9225. Tools.Log("Error while reading file: " + fileToLoad.name);
  9226. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9227. };
  9228. reader.onload = function (e) {
  9229. //target doesn't have result from ts 1.3
  9230. callback(e.target['result']);
  9231. };
  9232. if (progressCallBack) {
  9233. reader.onprogress = progressCallBack;
  9234. }
  9235. if (!useArrayBuffer) {
  9236. // Asynchronous read
  9237. reader.readAsText(fileToLoad);
  9238. }
  9239. else {
  9240. reader.readAsArrayBuffer(fileToLoad);
  9241. }
  9242. return request;
  9243. };
  9244. //returns a downloadable url to a file content.
  9245. Tools.FileAsURL = function (content) {
  9246. var fileBlob = new Blob([content]);
  9247. var url = window.URL || window.webkitURL;
  9248. var link = url.createObjectURL(fileBlob);
  9249. return link;
  9250. };
  9251. // Misc.
  9252. Tools.Format = function (value, decimals) {
  9253. if (decimals === void 0) { decimals = 2; }
  9254. return value.toFixed(decimals);
  9255. };
  9256. Tools.CheckExtends = function (v, min, max) {
  9257. if (v.x < min.x)
  9258. min.x = v.x;
  9259. if (v.y < min.y)
  9260. min.y = v.y;
  9261. if (v.z < min.z)
  9262. min.z = v.z;
  9263. if (v.x > max.x)
  9264. max.x = v.x;
  9265. if (v.y > max.y)
  9266. max.y = v.y;
  9267. if (v.z > max.z)
  9268. max.z = v.z;
  9269. };
  9270. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9271. for (var prop in source) {
  9272. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9273. continue;
  9274. }
  9275. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9276. continue;
  9277. }
  9278. var sourceValue = source[prop];
  9279. var typeOfSourceValue = typeof sourceValue;
  9280. if (typeOfSourceValue === "function") {
  9281. continue;
  9282. }
  9283. try {
  9284. if (typeOfSourceValue === "object") {
  9285. if (sourceValue instanceof Array) {
  9286. destination[prop] = [];
  9287. if (sourceValue.length > 0) {
  9288. if (typeof sourceValue[0] == "object") {
  9289. for (var index = 0; index < sourceValue.length; index++) {
  9290. var clonedValue = cloneValue(sourceValue[index], destination);
  9291. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9292. destination[prop].push(clonedValue);
  9293. }
  9294. }
  9295. }
  9296. else {
  9297. destination[prop] = sourceValue.slice(0);
  9298. }
  9299. }
  9300. }
  9301. else {
  9302. destination[prop] = cloneValue(sourceValue, destination);
  9303. }
  9304. }
  9305. else {
  9306. destination[prop] = sourceValue;
  9307. }
  9308. }
  9309. catch (e) {
  9310. // Just ignore error (it could be because of a read-only property)
  9311. }
  9312. }
  9313. };
  9314. Tools.IsEmpty = function (obj) {
  9315. for (var i in obj) {
  9316. if (obj.hasOwnProperty(i)) {
  9317. return false;
  9318. }
  9319. }
  9320. return true;
  9321. };
  9322. Tools.RegisterTopRootEvents = function (events) {
  9323. for (var index = 0; index < events.length; index++) {
  9324. var event = events[index];
  9325. window.addEventListener(event.name, event.handler, false);
  9326. try {
  9327. if (window.parent) {
  9328. window.parent.addEventListener(event.name, event.handler, false);
  9329. }
  9330. }
  9331. catch (e) {
  9332. // Silently fails...
  9333. }
  9334. }
  9335. };
  9336. Tools.UnregisterTopRootEvents = function (events) {
  9337. for (var index = 0; index < events.length; index++) {
  9338. var event = events[index];
  9339. window.removeEventListener(event.name, event.handler);
  9340. try {
  9341. if (window.parent) {
  9342. window.parent.removeEventListener(event.name, event.handler);
  9343. }
  9344. }
  9345. catch (e) {
  9346. // Silently fails...
  9347. }
  9348. }
  9349. };
  9350. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9351. if (mimeType === void 0) { mimeType = "image/png"; }
  9352. // Read the contents of the framebuffer
  9353. var numberOfChannelsByLine = width * 4;
  9354. var halfHeight = height / 2;
  9355. //Reading datas from WebGL
  9356. var data = engine.readPixels(0, 0, width, height);
  9357. //To flip image on Y axis.
  9358. for (var i = 0; i < halfHeight; i++) {
  9359. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9360. var currentCell = j + i * numberOfChannelsByLine;
  9361. var targetLine = height - i - 1;
  9362. var targetCell = j + targetLine * numberOfChannelsByLine;
  9363. var temp = data[currentCell];
  9364. data[currentCell] = data[targetCell];
  9365. data[targetCell] = temp;
  9366. }
  9367. }
  9368. // Create a 2D canvas to store the result
  9369. if (!screenshotCanvas) {
  9370. screenshotCanvas = document.createElement('canvas');
  9371. }
  9372. screenshotCanvas.width = width;
  9373. screenshotCanvas.height = height;
  9374. var context = screenshotCanvas.getContext('2d');
  9375. if (context) {
  9376. // Copy the pixels to a 2D canvas
  9377. var imageData = context.createImageData(width, height);
  9378. var castData = (imageData.data);
  9379. castData.set(data);
  9380. context.putImageData(imageData, 0, 0);
  9381. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9382. }
  9383. };
  9384. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9385. if (mimeType === void 0) { mimeType = "image/png"; }
  9386. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9387. if (successCallback) {
  9388. successCallback(base64Image);
  9389. }
  9390. else {
  9391. // We need HTMLCanvasElement.toBlob for HD screenshots
  9392. if (!screenshotCanvas.toBlob) {
  9393. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9394. screenshotCanvas.toBlob = function (callback, type, quality) {
  9395. var _this = this;
  9396. setTimeout(function () {
  9397. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9398. for (var i = 0; i < len; i++) {
  9399. arr[i] = binStr.charCodeAt(i);
  9400. }
  9401. callback(new Blob([arr], { type: type || 'image/png' }));
  9402. });
  9403. };
  9404. }
  9405. screenshotCanvas.toBlob(function (blob) {
  9406. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9407. if (("download" in document.createElement("a"))) {
  9408. if (!fileName) {
  9409. var date = new Date();
  9410. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9411. fileName = "screenshot_" + stringDate + ".png";
  9412. }
  9413. Tools.Download(blob, fileName);
  9414. }
  9415. else {
  9416. var url = URL.createObjectURL(blob);
  9417. var newWindow = window.open("");
  9418. if (!newWindow)
  9419. return;
  9420. var img = newWindow.document.createElement("img");
  9421. img.onload = function () {
  9422. // no longer need to read the blob so it's revoked
  9423. URL.revokeObjectURL(url);
  9424. };
  9425. img.src = url;
  9426. newWindow.document.body.appendChild(img);
  9427. }
  9428. });
  9429. }
  9430. };
  9431. /**
  9432. * Downloads a blob in the browser
  9433. * @param blob defines the blob to download
  9434. * @param fileName defines the name of the downloaded file
  9435. */
  9436. Tools.Download = function (blob, fileName) {
  9437. var url = window.URL.createObjectURL(blob);
  9438. var a = document.createElement("a");
  9439. document.body.appendChild(a);
  9440. a.style.display = "none";
  9441. a.href = url;
  9442. a.download = fileName;
  9443. a.addEventListener("click", function () {
  9444. if (a.parentElement) {
  9445. a.parentElement.removeChild(a);
  9446. }
  9447. });
  9448. a.click();
  9449. window.URL.revokeObjectURL(url);
  9450. };
  9451. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9452. if (mimeType === void 0) { mimeType = "image/png"; }
  9453. var width;
  9454. var height;
  9455. // If a precision value is specified
  9456. if (size.precision) {
  9457. width = Math.round(engine.getRenderWidth() * size.precision);
  9458. height = Math.round(width / engine.getAspectRatio(camera));
  9459. }
  9460. else if (size.width && size.height) {
  9461. width = size.width;
  9462. height = size.height;
  9463. }
  9464. //If passing only width, computing height to keep display canvas ratio.
  9465. else if (size.width && !size.height) {
  9466. width = size.width;
  9467. height = Math.round(width / engine.getAspectRatio(camera));
  9468. }
  9469. //If passing only height, computing width to keep display canvas ratio.
  9470. else if (size.height && !size.width) {
  9471. height = size.height;
  9472. width = Math.round(height * engine.getAspectRatio(camera));
  9473. }
  9474. //Assuming here that "size" parameter is a number
  9475. else if (!isNaN(size)) {
  9476. height = size;
  9477. width = size;
  9478. }
  9479. else {
  9480. Tools.Error("Invalid 'size' parameter !");
  9481. return;
  9482. }
  9483. if (!screenshotCanvas) {
  9484. screenshotCanvas = document.createElement('canvas');
  9485. }
  9486. screenshotCanvas.width = width;
  9487. screenshotCanvas.height = height;
  9488. var renderContext = screenshotCanvas.getContext("2d");
  9489. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9490. var newWidth = width;
  9491. var newHeight = newWidth / ratio;
  9492. if (newHeight > height) {
  9493. newHeight = height;
  9494. newWidth = newHeight * ratio;
  9495. }
  9496. var offsetX = Math.max(0, width - newWidth) / 2;
  9497. var offsetY = Math.max(0, height - newHeight) / 2;
  9498. var renderingCanvas = engine.getRenderingCanvas();
  9499. if (renderContext && renderingCanvas) {
  9500. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9501. }
  9502. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9503. };
  9504. /**
  9505. * Generates an image screenshot from the specified camera.
  9506. *
  9507. * @param engine The engine to use for rendering
  9508. * @param camera The camera to use for rendering
  9509. * @param size This parameter can be set to a single number or to an object with the
  9510. * following (optional) properties: precision, width, height. If a single number is passed,
  9511. * it will be used for both width and height. If an object is passed, the screenshot size
  9512. * will be derived from the parameters. The precision property is a multiplier allowing
  9513. * rendering at a higher or lower resolution.
  9514. * @param successCallback The callback receives a single parameter which contains the
  9515. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9516. * src parameter of an <img> to display it.
  9517. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9518. * Check your browser for supported MIME types.
  9519. * @param samples Texture samples (default: 1)
  9520. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9521. * @param fileName A name for for the downloaded file.
  9522. * @constructor
  9523. */
  9524. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9525. if (mimeType === void 0) { mimeType = "image/png"; }
  9526. if (samples === void 0) { samples = 1; }
  9527. if (antialiasing === void 0) { antialiasing = false; }
  9528. var width;
  9529. var height;
  9530. //If a precision value is specified
  9531. if (size.precision) {
  9532. width = Math.round(engine.getRenderWidth() * size.precision);
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. size = { width: width, height: height };
  9535. }
  9536. else if (size.width && size.height) {
  9537. width = size.width;
  9538. height = size.height;
  9539. }
  9540. //If passing only width, computing height to keep display canvas ratio.
  9541. else if (size.width && !size.height) {
  9542. width = size.width;
  9543. height = Math.round(width / engine.getAspectRatio(camera));
  9544. size = { width: width, height: height };
  9545. }
  9546. //If passing only height, computing width to keep display canvas ratio.
  9547. else if (size.height && !size.width) {
  9548. height = size.height;
  9549. width = Math.round(height * engine.getAspectRatio(camera));
  9550. size = { width: width, height: height };
  9551. }
  9552. //Assuming here that "size" parameter is a number
  9553. else if (!isNaN(size)) {
  9554. height = size;
  9555. width = size;
  9556. }
  9557. else {
  9558. Tools.Error("Invalid 'size' parameter !");
  9559. return;
  9560. }
  9561. var scene = camera.getScene();
  9562. var previousCamera = null;
  9563. if (scene.activeCamera !== camera) {
  9564. previousCamera = scene.activeCamera;
  9565. scene.activeCamera = camera;
  9566. }
  9567. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9568. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9569. texture.renderList = null;
  9570. texture.samples = samples;
  9571. if (antialiasing) {
  9572. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9573. }
  9574. texture.onAfterRenderObservable.add(function () {
  9575. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9576. });
  9577. scene.incrementRenderId();
  9578. scene.resetCachedMaterial();
  9579. texture.render(true);
  9580. texture.dispose();
  9581. if (previousCamera) {
  9582. scene.activeCamera = previousCamera;
  9583. }
  9584. camera.getProjectionMatrix(true); // Force cache refresh;
  9585. };
  9586. // XHR response validator for local file scenario
  9587. Tools.ValidateXHRData = function (xhr, dataType) {
  9588. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9589. if (dataType === void 0) { dataType = 7; }
  9590. try {
  9591. if (dataType & 1) {
  9592. if (xhr.responseText && xhr.responseText.length > 0) {
  9593. return true;
  9594. }
  9595. else if (dataType === 1) {
  9596. return false;
  9597. }
  9598. }
  9599. if (dataType & 2) {
  9600. // Check header width and height since there is no "TGA" magic number
  9601. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9602. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9603. return true;
  9604. }
  9605. else if (dataType === 2) {
  9606. return false;
  9607. }
  9608. }
  9609. if (dataType & 4) {
  9610. // Check for the "DDS" magic number
  9611. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9612. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9613. return true;
  9614. }
  9615. else {
  9616. return false;
  9617. }
  9618. }
  9619. }
  9620. catch (e) {
  9621. // Global protection
  9622. }
  9623. return false;
  9624. };
  9625. /**
  9626. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9627. * Be aware Math.random() could cause collisions, but:
  9628. * "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"
  9629. */
  9630. Tools.RandomId = function () {
  9631. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9632. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9633. return v.toString(16);
  9634. });
  9635. };
  9636. /**
  9637. * Test if the given uri is a base64 string.
  9638. * @param uri The uri to test
  9639. * @return True if the uri is a base64 string or false otherwise.
  9640. */
  9641. Tools.IsBase64 = function (uri) {
  9642. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9643. };
  9644. /**
  9645. * Decode the given base64 uri.
  9646. * @param uri The uri to decode
  9647. * @return The decoded base64 data.
  9648. */
  9649. Tools.DecodeBase64 = function (uri) {
  9650. var decodedString = atob(uri.split(",")[1]);
  9651. var bufferLength = decodedString.length;
  9652. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9653. for (var i = 0; i < bufferLength; i++) {
  9654. bufferView[i] = decodedString.charCodeAt(i);
  9655. }
  9656. return bufferView.buffer;
  9657. };
  9658. Object.defineProperty(Tools, "NoneLogLevel", {
  9659. get: function () {
  9660. return Tools._NoneLogLevel;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Tools, "MessageLogLevel", {
  9666. get: function () {
  9667. return Tools._MessageLogLevel;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Tools, "WarningLogLevel", {
  9673. get: function () {
  9674. return Tools._WarningLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "ErrorLogLevel", {
  9680. get: function () {
  9681. return Tools._ErrorLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Object.defineProperty(Tools, "AllLogLevel", {
  9687. get: function () {
  9688. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Tools._AddLogEntry = function (entry) {
  9694. Tools._LogCache = entry + Tools._LogCache;
  9695. if (Tools.OnNewCacheEntry) {
  9696. Tools.OnNewCacheEntry(entry);
  9697. }
  9698. };
  9699. Tools._FormatMessage = function (message) {
  9700. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9701. var date = new Date();
  9702. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9703. };
  9704. Tools._LogDisabled = function (message) {
  9705. // nothing to do
  9706. };
  9707. Tools._LogEnabled = function (message) {
  9708. var formattedMessage = Tools._FormatMessage(message);
  9709. console.log("BJS - " + formattedMessage);
  9710. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9711. Tools._AddLogEntry(entry);
  9712. };
  9713. Tools._WarnDisabled = function (message) {
  9714. // nothing to do
  9715. };
  9716. Tools._WarnEnabled = function (message) {
  9717. var formattedMessage = Tools._FormatMessage(message);
  9718. console.warn("BJS - " + formattedMessage);
  9719. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9720. Tools._AddLogEntry(entry);
  9721. };
  9722. Tools._ErrorDisabled = function (message) {
  9723. // nothing to do
  9724. };
  9725. Tools._ErrorEnabled = function (message) {
  9726. Tools.errorsCount++;
  9727. var formattedMessage = Tools._FormatMessage(message);
  9728. console.error("BJS - " + formattedMessage);
  9729. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9730. Tools._AddLogEntry(entry);
  9731. };
  9732. Object.defineProperty(Tools, "LogCache", {
  9733. get: function () {
  9734. return Tools._LogCache;
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. Tools.ClearLogCache = function () {
  9740. Tools._LogCache = "";
  9741. Tools.errorsCount = 0;
  9742. };
  9743. Object.defineProperty(Tools, "LogLevels", {
  9744. set: function (level) {
  9745. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9746. Tools.Log = Tools._LogEnabled;
  9747. }
  9748. else {
  9749. Tools.Log = Tools._LogDisabled;
  9750. }
  9751. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9752. Tools.Warn = Tools._WarnEnabled;
  9753. }
  9754. else {
  9755. Tools.Warn = Tools._WarnDisabled;
  9756. }
  9757. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9758. Tools.Error = Tools._ErrorEnabled;
  9759. }
  9760. else {
  9761. Tools.Error = Tools._ErrorDisabled;
  9762. }
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Tools.IsWindowObjectExist = function () {
  9768. return (typeof window) !== "undefined";
  9769. };
  9770. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9771. get: function () {
  9772. return Tools._PerformanceNoneLogLevel;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9778. get: function () {
  9779. return Tools._PerformanceUserMarkLogLevel;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9785. get: function () {
  9786. return Tools._PerformanceConsoleLogLevel;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9792. set: function (level) {
  9793. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9794. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9795. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9796. return;
  9797. }
  9798. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9799. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9800. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9801. return;
  9802. }
  9803. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9804. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9810. };
  9811. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9812. };
  9813. Tools._StartUserMark = function (counterName, condition) {
  9814. if (condition === void 0) { condition = true; }
  9815. if (!Tools._performance) {
  9816. if (!Tools.IsWindowObjectExist()) {
  9817. return;
  9818. }
  9819. Tools._performance = window.performance;
  9820. }
  9821. if (!condition || !Tools._performance.mark) {
  9822. return;
  9823. }
  9824. Tools._performance.mark(counterName + "-Begin");
  9825. };
  9826. Tools._EndUserMark = function (counterName, condition) {
  9827. if (condition === void 0) { condition = true; }
  9828. if (!condition || !Tools._performance.mark) {
  9829. return;
  9830. }
  9831. Tools._performance.mark(counterName + "-End");
  9832. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9833. };
  9834. Tools._StartPerformanceConsole = function (counterName, condition) {
  9835. if (condition === void 0) { condition = true; }
  9836. if (!condition) {
  9837. return;
  9838. }
  9839. Tools._StartUserMark(counterName, condition);
  9840. if (console.time) {
  9841. console.time(counterName);
  9842. }
  9843. };
  9844. Tools._EndPerformanceConsole = function (counterName, condition) {
  9845. if (condition === void 0) { condition = true; }
  9846. if (!condition) {
  9847. return;
  9848. }
  9849. Tools._EndUserMark(counterName, condition);
  9850. if (console.time) {
  9851. console.timeEnd(counterName);
  9852. }
  9853. };
  9854. Object.defineProperty(Tools, "Now", {
  9855. get: function () {
  9856. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9857. return window.performance.now();
  9858. }
  9859. return Date.now();
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. /**
  9865. * This method will return the name of the class used to create the instance of the given object.
  9866. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9867. * @param object the object to get the class name from
  9868. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9869. */
  9870. Tools.GetClassName = function (object, isType) {
  9871. if (isType === void 0) { isType = false; }
  9872. var name = null;
  9873. if (!isType && object.getClassName) {
  9874. name = object.getClassName();
  9875. }
  9876. else {
  9877. if (object instanceof Object) {
  9878. var classObj = isType ? object : Object.getPrototypeOf(object);
  9879. name = classObj.constructor["__bjsclassName__"];
  9880. }
  9881. if (!name) {
  9882. name = typeof object;
  9883. }
  9884. }
  9885. return name;
  9886. };
  9887. Tools.First = function (array, predicate) {
  9888. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9889. var el = array_1[_i];
  9890. if (predicate(el)) {
  9891. return el;
  9892. }
  9893. }
  9894. return null;
  9895. };
  9896. /**
  9897. * This method will return the name of the full name of the class, including its owning module (if any).
  9898. * 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).
  9899. * @param object the object to get the class name from
  9900. * @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.
  9901. */
  9902. Tools.getFullClassName = function (object, isType) {
  9903. if (isType === void 0) { isType = false; }
  9904. var className = null;
  9905. var moduleName = null;
  9906. if (!isType && object.getClassName) {
  9907. className = object.getClassName();
  9908. }
  9909. else {
  9910. if (object instanceof Object) {
  9911. var classObj = isType ? object : Object.getPrototypeOf(object);
  9912. className = classObj.constructor["__bjsclassName__"];
  9913. moduleName = classObj.constructor["__bjsmoduleName__"];
  9914. }
  9915. if (!className) {
  9916. className = typeof object;
  9917. }
  9918. }
  9919. if (!className) {
  9920. return null;
  9921. }
  9922. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9923. };
  9924. /**
  9925. * 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.
  9926. * @param array
  9927. */
  9928. Tools.arrayOrStringFeeder = function (array) {
  9929. return function (index) {
  9930. if (index >= array.length) {
  9931. return null;
  9932. }
  9933. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9934. if (val && val.getHashCode) {
  9935. val = val.getHashCode();
  9936. }
  9937. if (typeof val === "string") {
  9938. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9939. }
  9940. return val;
  9941. };
  9942. };
  9943. /**
  9944. * Compute the hashCode of a stream of number
  9945. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9946. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9947. * @return the hash code computed
  9948. */
  9949. Tools.hashCodeFromStream = function (feeder) {
  9950. // Based from here: http://stackoverflow.com/a/7616484/802124
  9951. var hash = 0;
  9952. var index = 0;
  9953. var chr = feeder(index++);
  9954. while (chr != null) {
  9955. hash = ((hash << 5) - hash) + chr;
  9956. hash |= 0; // Convert to 32bit integer
  9957. chr = feeder(index++);
  9958. }
  9959. return hash;
  9960. };
  9961. /**
  9962. * Returns a promise that resolves after the given amount of time.
  9963. * @param delay Number of milliseconds to delay
  9964. * @returns Promise that resolves after the given amount of time
  9965. */
  9966. Tools.DelayAsync = function (delay) {
  9967. return new Promise(function (resolve) {
  9968. setTimeout(function () {
  9969. resolve();
  9970. }, delay);
  9971. });
  9972. };
  9973. Tools.BaseUrl = "";
  9974. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9975. /**
  9976. * Default behaviour for cors in the application.
  9977. * It can be a string if the expected behavior is identical in the entire app.
  9978. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9979. */
  9980. Tools.CorsBehavior = "anonymous";
  9981. Tools.UseFallbackTexture = true;
  9982. /**
  9983. * Use this object to register external classes like custom textures or material
  9984. * to allow the laoders to instantiate them
  9985. */
  9986. Tools.RegisteredExternalClasses = {};
  9987. // Used in case of a texture loading problem
  9988. 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";
  9989. Tools._tmpFloatArray = new Float32Array(1);
  9990. Tools.PreprocessUrl = function (url) {
  9991. return url;
  9992. };
  9993. // Logs
  9994. Tools._NoneLogLevel = 0;
  9995. Tools._MessageLogLevel = 1;
  9996. Tools._WarningLogLevel = 2;
  9997. Tools._ErrorLogLevel = 4;
  9998. Tools._LogCache = "";
  9999. Tools.errorsCount = 0;
  10000. Tools.Log = Tools._LogEnabled;
  10001. Tools.Warn = Tools._WarnEnabled;
  10002. Tools.Error = Tools._ErrorEnabled;
  10003. // Performances
  10004. Tools._PerformanceNoneLogLevel = 0;
  10005. Tools._PerformanceUserMarkLogLevel = 1;
  10006. Tools._PerformanceConsoleLogLevel = 2;
  10007. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10008. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10009. return Tools;
  10010. }());
  10011. BABYLON.Tools = Tools;
  10012. /**
  10013. * This class is used to track a performance counter which is number based.
  10014. * The user has access to many properties which give statistics of different nature
  10015. *
  10016. * The implementer can track two kinds of Performance Counter: time and count
  10017. * 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.
  10018. * 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.
  10019. */
  10020. var PerfCounter = /** @class */ (function () {
  10021. function PerfCounter() {
  10022. this._startMonitoringTime = 0;
  10023. this._min = 0;
  10024. this._max = 0;
  10025. this._average = 0;
  10026. this._lastSecAverage = 0;
  10027. this._current = 0;
  10028. this._totalValueCount = 0;
  10029. this._totalAccumulated = 0;
  10030. this._lastSecAccumulated = 0;
  10031. this._lastSecTime = 0;
  10032. this._lastSecValueCount = 0;
  10033. }
  10034. Object.defineProperty(PerfCounter.prototype, "min", {
  10035. /**
  10036. * Returns the smallest value ever
  10037. */
  10038. get: function () {
  10039. return this._min;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(PerfCounter.prototype, "max", {
  10045. /**
  10046. * Returns the biggest value ever
  10047. */
  10048. get: function () {
  10049. return this._max;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(PerfCounter.prototype, "average", {
  10055. /**
  10056. * Returns the average value since the performance counter is running
  10057. */
  10058. get: function () {
  10059. return this._average;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10065. /**
  10066. * Returns the average value of the last second the counter was monitored
  10067. */
  10068. get: function () {
  10069. return this._lastSecAverage;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(PerfCounter.prototype, "current", {
  10075. /**
  10076. * Returns the current value
  10077. */
  10078. get: function () {
  10079. return this._current;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "total", {
  10085. get: function () {
  10086. return this._totalAccumulated;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(PerfCounter.prototype, "count", {
  10092. get: function () {
  10093. return this._totalValueCount;
  10094. },
  10095. enumerable: true,
  10096. configurable: true
  10097. });
  10098. /**
  10099. * Call this method to start monitoring a new frame.
  10100. * 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.
  10101. */
  10102. PerfCounter.prototype.fetchNewFrame = function () {
  10103. this._totalValueCount++;
  10104. this._current = 0;
  10105. this._lastSecValueCount++;
  10106. };
  10107. /**
  10108. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10109. * @param newCount the count value to add to the monitored count
  10110. * @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.
  10111. */
  10112. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10113. if (!PerfCounter.Enabled) {
  10114. return;
  10115. }
  10116. this._current += newCount;
  10117. if (fetchResult) {
  10118. this._fetchResult();
  10119. }
  10120. };
  10121. /**
  10122. * Start monitoring this performance counter
  10123. */
  10124. PerfCounter.prototype.beginMonitoring = function () {
  10125. if (!PerfCounter.Enabled) {
  10126. return;
  10127. }
  10128. this._startMonitoringTime = Tools.Now;
  10129. };
  10130. /**
  10131. * Compute the time lapsed since the previous beginMonitoring() call.
  10132. * @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
  10133. */
  10134. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10135. if (newFrame === void 0) { newFrame = true; }
  10136. if (!PerfCounter.Enabled) {
  10137. return;
  10138. }
  10139. if (newFrame) {
  10140. this.fetchNewFrame();
  10141. }
  10142. var currentTime = Tools.Now;
  10143. this._current = currentTime - this._startMonitoringTime;
  10144. if (newFrame) {
  10145. this._fetchResult();
  10146. }
  10147. };
  10148. PerfCounter.prototype._fetchResult = function () {
  10149. this._totalAccumulated += this._current;
  10150. this._lastSecAccumulated += this._current;
  10151. // Min/Max update
  10152. this._min = Math.min(this._min, this._current);
  10153. this._max = Math.max(this._max, this._current);
  10154. this._average = this._totalAccumulated / this._totalValueCount;
  10155. // Reset last sec?
  10156. var now = Tools.Now;
  10157. if ((now - this._lastSecTime) > 1000) {
  10158. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10159. this._lastSecTime = now;
  10160. this._lastSecAccumulated = 0;
  10161. this._lastSecValueCount = 0;
  10162. }
  10163. };
  10164. PerfCounter.Enabled = true;
  10165. return PerfCounter;
  10166. }());
  10167. BABYLON.PerfCounter = PerfCounter;
  10168. /**
  10169. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10170. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10171. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10172. * @param name The name of the class, case should be preserved
  10173. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10174. */
  10175. function className(name, module) {
  10176. return function (target) {
  10177. target["__bjsclassName__"] = name;
  10178. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10179. };
  10180. }
  10181. BABYLON.className = className;
  10182. /**
  10183. * An implementation of a loop for asynchronous functions.
  10184. */
  10185. var AsyncLoop = /** @class */ (function () {
  10186. /**
  10187. * Constroctor.
  10188. * @param iterations the number of iterations.
  10189. * @param _fn the function to run each iteration
  10190. * @param _successCallback the callback that will be called upon succesful execution
  10191. * @param offset starting offset.
  10192. */
  10193. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10194. if (offset === void 0) { offset = 0; }
  10195. this.iterations = iterations;
  10196. this._fn = _fn;
  10197. this._successCallback = _successCallback;
  10198. this.index = offset - 1;
  10199. this._done = false;
  10200. }
  10201. /**
  10202. * Execute the next iteration. Must be called after the last iteration was finished.
  10203. */
  10204. AsyncLoop.prototype.executeNext = function () {
  10205. if (!this._done) {
  10206. if (this.index + 1 < this.iterations) {
  10207. ++this.index;
  10208. this._fn(this);
  10209. }
  10210. else {
  10211. this.breakLoop();
  10212. }
  10213. }
  10214. };
  10215. /**
  10216. * Break the loop and run the success callback.
  10217. */
  10218. AsyncLoop.prototype.breakLoop = function () {
  10219. this._done = true;
  10220. this._successCallback();
  10221. };
  10222. /**
  10223. * Helper function
  10224. */
  10225. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10226. if (offset === void 0) { offset = 0; }
  10227. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10228. loop.executeNext();
  10229. return loop;
  10230. };
  10231. /**
  10232. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10233. * @param iterations total number of iterations
  10234. * @param syncedIterations number of synchronous iterations in each async iteration.
  10235. * @param fn the function to call each iteration.
  10236. * @param callback a success call back that will be called when iterating stops.
  10237. * @param breakFunction a break condition (optional)
  10238. * @param timeout timeout settings for the setTimeout function. default - 0.
  10239. * @constructor
  10240. */
  10241. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10242. if (timeout === void 0) { timeout = 0; }
  10243. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10244. if (breakFunction && breakFunction())
  10245. loop.breakLoop();
  10246. else {
  10247. setTimeout(function () {
  10248. for (var i = 0; i < syncedIterations; ++i) {
  10249. var iteration = (loop.index * syncedIterations) + i;
  10250. if (iteration >= iterations)
  10251. break;
  10252. fn(iteration);
  10253. if (breakFunction && breakFunction()) {
  10254. loop.breakLoop();
  10255. break;
  10256. }
  10257. }
  10258. loop.executeNext();
  10259. }, timeout);
  10260. }
  10261. }, callback);
  10262. };
  10263. return AsyncLoop;
  10264. }());
  10265. BABYLON.AsyncLoop = AsyncLoop;
  10266. })(BABYLON || (BABYLON = {}));
  10267. //# sourceMappingURL=babylon.tools.js.map
  10268. var BABYLON;
  10269. (function (BABYLON) {
  10270. var PromiseStates;
  10271. (function (PromiseStates) {
  10272. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10273. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10274. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10275. })(PromiseStates || (PromiseStates = {}));
  10276. var FulFillmentAgregator = /** @class */ (function () {
  10277. function FulFillmentAgregator() {
  10278. this.count = 0;
  10279. this.target = 0;
  10280. this.results = [];
  10281. }
  10282. return FulFillmentAgregator;
  10283. }());
  10284. var InternalPromise = /** @class */ (function () {
  10285. function InternalPromise(resolver) {
  10286. var _this = this;
  10287. this._state = PromiseStates.Pending;
  10288. this._children = new Array();
  10289. this._rejectWasConsumed = false;
  10290. if (!resolver) {
  10291. return;
  10292. }
  10293. try {
  10294. resolver(function (value) {
  10295. _this._resolve(value);
  10296. }, function (reason) {
  10297. _this._reject(reason);
  10298. });
  10299. }
  10300. catch (e) {
  10301. this._reject(e);
  10302. }
  10303. }
  10304. Object.defineProperty(InternalPromise.prototype, "_result", {
  10305. get: function () {
  10306. return this._resultValue;
  10307. },
  10308. set: function (value) {
  10309. this._resultValue = value;
  10310. if (this._parent && this._parent._result === undefined) {
  10311. this._parent._result = value;
  10312. }
  10313. },
  10314. enumerable: true,
  10315. configurable: true
  10316. });
  10317. InternalPromise.prototype.catch = function (onRejected) {
  10318. return this.then(undefined, onRejected);
  10319. };
  10320. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10321. var _this = this;
  10322. var newPromise = new InternalPromise();
  10323. newPromise._onFulfilled = onFulfilled;
  10324. newPromise._onRejected = onRejected;
  10325. // Composition
  10326. this._children.push(newPromise);
  10327. newPromise._parent = this;
  10328. if (this._state !== PromiseStates.Pending) {
  10329. BABYLON.Tools.SetImmediate(function () {
  10330. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10331. var returnedValue = newPromise._resolve(_this._result);
  10332. if (returnedValue !== undefined && returnedValue !== null) {
  10333. if (returnedValue._state !== undefined) {
  10334. var returnedPromise = returnedValue;
  10335. newPromise._children.push(returnedPromise);
  10336. returnedPromise._parent = newPromise;
  10337. newPromise = returnedPromise;
  10338. }
  10339. else {
  10340. newPromise._result = returnedValue;
  10341. }
  10342. }
  10343. }
  10344. else {
  10345. newPromise._reject(_this._reason);
  10346. }
  10347. });
  10348. }
  10349. return newPromise;
  10350. };
  10351. InternalPromise.prototype._moveChildren = function (children) {
  10352. var _this = this;
  10353. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10354. this._children.forEach(function (child) {
  10355. child._parent = _this;
  10356. });
  10357. if (this._state === PromiseStates.Fulfilled) {
  10358. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10359. var child = _b[_i];
  10360. child._resolve(this._result);
  10361. }
  10362. }
  10363. else if (this._state === PromiseStates.Rejected) {
  10364. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10365. var child = _d[_c];
  10366. child._reject(this._reason);
  10367. }
  10368. }
  10369. var _a;
  10370. };
  10371. InternalPromise.prototype._resolve = function (value) {
  10372. try {
  10373. this._state = PromiseStates.Fulfilled;
  10374. var returnedValue = null;
  10375. if (this._onFulfilled) {
  10376. returnedValue = this._onFulfilled(value);
  10377. }
  10378. if (returnedValue !== undefined && returnedValue !== null) {
  10379. if (returnedValue._state !== undefined) {
  10380. // Transmit children
  10381. var returnedPromise = returnedValue;
  10382. returnedPromise._parent = this;
  10383. returnedPromise._moveChildren(this._children);
  10384. value = returnedPromise._result;
  10385. }
  10386. else {
  10387. value = returnedValue;
  10388. }
  10389. }
  10390. this._result = value;
  10391. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10392. var child = _a[_i];
  10393. child._resolve(value);
  10394. }
  10395. this._children.length = 0;
  10396. delete this._onFulfilled;
  10397. delete this._onRejected;
  10398. }
  10399. catch (e) {
  10400. this._reject(e, true);
  10401. }
  10402. };
  10403. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10404. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10405. this._state = PromiseStates.Rejected;
  10406. this._reason = reason;
  10407. if (this._onRejected && !onLocalThrow) {
  10408. try {
  10409. this._onRejected(reason);
  10410. this._rejectWasConsumed = true;
  10411. }
  10412. catch (e) {
  10413. reason = e;
  10414. }
  10415. }
  10416. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10417. var child = _a[_i];
  10418. if (this._rejectWasConsumed) {
  10419. child._resolve(null);
  10420. }
  10421. else {
  10422. child._reject(reason);
  10423. }
  10424. }
  10425. this._children.length = 0;
  10426. delete this._onFulfilled;
  10427. delete this._onRejected;
  10428. };
  10429. InternalPromise.resolve = function (value) {
  10430. var newPromise = new InternalPromise();
  10431. newPromise._resolve(value);
  10432. return newPromise;
  10433. };
  10434. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10435. promise.then(function (value) {
  10436. agregator.results[index] = value;
  10437. agregator.count++;
  10438. if (agregator.count === agregator.target) {
  10439. agregator.rootPromise._resolve(agregator.results);
  10440. }
  10441. return null;
  10442. }, function (reason) {
  10443. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10444. agregator.rootPromise._reject(reason);
  10445. }
  10446. });
  10447. };
  10448. InternalPromise.all = function (promises) {
  10449. var newPromise = new InternalPromise();
  10450. var agregator = new FulFillmentAgregator();
  10451. agregator.target = promises.length;
  10452. agregator.rootPromise = newPromise;
  10453. if (promises.length) {
  10454. for (var index = 0; index < promises.length; index++) {
  10455. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10456. }
  10457. }
  10458. else {
  10459. newPromise._resolve([]);
  10460. }
  10461. return newPromise;
  10462. };
  10463. InternalPromise.race = function (promises) {
  10464. var newPromise = new InternalPromise();
  10465. if (promises.length) {
  10466. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10467. var promise = promises_1[_i];
  10468. promise.then(function (value) {
  10469. if (newPromise) {
  10470. newPromise._resolve(value);
  10471. newPromise = null;
  10472. }
  10473. return null;
  10474. }, function (reason) {
  10475. if (newPromise) {
  10476. newPromise._reject(reason);
  10477. newPromise = null;
  10478. }
  10479. });
  10480. }
  10481. }
  10482. return newPromise;
  10483. };
  10484. return InternalPromise;
  10485. }());
  10486. /**
  10487. * Helper class that provides a small promise polyfill
  10488. */
  10489. var PromisePolyfill = /** @class */ (function () {
  10490. function PromisePolyfill() {
  10491. }
  10492. /**
  10493. * Static function used to check if the polyfill is required
  10494. * If this is the case then the function will inject the polyfill to window.Promise
  10495. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10496. */
  10497. PromisePolyfill.Apply = function (force) {
  10498. if (force === void 0) { force = false; }
  10499. if (force || typeof Promise === 'undefined') {
  10500. var root = window;
  10501. root.Promise = InternalPromise;
  10502. }
  10503. };
  10504. return PromisePolyfill;
  10505. }());
  10506. BABYLON.PromisePolyfill = PromisePolyfill;
  10507. })(BABYLON || (BABYLON = {}));
  10508. //# sourceMappingURL=babylon.promise.js.map
  10509. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10510. var BABYLON;
  10511. (function (BABYLON) {
  10512. /**
  10513. * Helper class to push actions to a pool of workers.
  10514. */
  10515. var WorkerPool = /** @class */ (function () {
  10516. /**
  10517. * Constructor
  10518. * @param workers Array of workers to use for actions
  10519. */
  10520. function WorkerPool(workers) {
  10521. this._pendingActions = new Array();
  10522. this._workerInfos = workers.map(function (worker) { return ({
  10523. worker: worker,
  10524. active: false
  10525. }); });
  10526. }
  10527. /**
  10528. * Terminates all workers and clears any pending actions.
  10529. */
  10530. WorkerPool.prototype.dispose = function () {
  10531. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10532. var workerInfo = _a[_i];
  10533. workerInfo.worker.terminate();
  10534. }
  10535. delete this._workerInfos;
  10536. delete this._pendingActions;
  10537. };
  10538. /**
  10539. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10540. * pended until a worker has completed its action.
  10541. * @param action The action to perform. Call onComplete when the action is complete.
  10542. */
  10543. WorkerPool.prototype.push = function (action) {
  10544. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10545. var workerInfo = _a[_i];
  10546. if (!workerInfo.active) {
  10547. this._execute(workerInfo, action);
  10548. return;
  10549. }
  10550. }
  10551. this._pendingActions.push(action);
  10552. };
  10553. WorkerPool.prototype._execute = function (workerInfo, action) {
  10554. var _this = this;
  10555. workerInfo.active = true;
  10556. action(workerInfo.worker, function () {
  10557. workerInfo.active = false;
  10558. var nextAction = _this._pendingActions.shift();
  10559. if (nextAction) {
  10560. _this._execute(workerInfo, nextAction);
  10561. }
  10562. });
  10563. };
  10564. return WorkerPool;
  10565. }());
  10566. BABYLON.WorkerPool = WorkerPool;
  10567. })(BABYLON || (BABYLON = {}));
  10568. //# sourceMappingURL=babylon.workerPool.js.map
  10569. var BABYLON;
  10570. (function (BABYLON) {
  10571. /**
  10572. * @hidden
  10573. **/
  10574. var _AlphaState = /** @class */ (function () {
  10575. /**
  10576. * Initializes the state.
  10577. */
  10578. function _AlphaState() {
  10579. this._isAlphaBlendDirty = false;
  10580. this._isBlendFunctionParametersDirty = false;
  10581. this._isBlendEquationParametersDirty = false;
  10582. this._isBlendConstantsDirty = false;
  10583. this._alphaBlend = false;
  10584. this._blendFunctionParameters = new Array(4);
  10585. this._blendEquationParameters = new Array(2);
  10586. this._blendConstants = new Array(4);
  10587. this.reset();
  10588. }
  10589. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10590. get: function () {
  10591. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10597. get: function () {
  10598. return this._alphaBlend;
  10599. },
  10600. set: function (value) {
  10601. if (this._alphaBlend === value) {
  10602. return;
  10603. }
  10604. this._alphaBlend = value;
  10605. this._isAlphaBlendDirty = true;
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10611. if (this._blendConstants[0] === r &&
  10612. this._blendConstants[1] === g &&
  10613. this._blendConstants[2] === b &&
  10614. this._blendConstants[3] === a) {
  10615. return;
  10616. }
  10617. this._blendConstants[0] = r;
  10618. this._blendConstants[1] = g;
  10619. this._blendConstants[2] = b;
  10620. this._blendConstants[3] = a;
  10621. this._isBlendConstantsDirty = true;
  10622. };
  10623. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10624. if (this._blendFunctionParameters[0] === value0 &&
  10625. this._blendFunctionParameters[1] === value1 &&
  10626. this._blendFunctionParameters[2] === value2 &&
  10627. this._blendFunctionParameters[3] === value3) {
  10628. return;
  10629. }
  10630. this._blendFunctionParameters[0] = value0;
  10631. this._blendFunctionParameters[1] = value1;
  10632. this._blendFunctionParameters[2] = value2;
  10633. this._blendFunctionParameters[3] = value3;
  10634. this._isBlendFunctionParametersDirty = true;
  10635. };
  10636. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10637. if (this._blendEquationParameters[0] === rgb &&
  10638. this._blendEquationParameters[1] === alpha) {
  10639. return;
  10640. }
  10641. this._blendEquationParameters[0] = rgb;
  10642. this._blendEquationParameters[1] = alpha;
  10643. this._isBlendEquationParametersDirty = true;
  10644. };
  10645. _AlphaState.prototype.reset = function () {
  10646. this._alphaBlend = false;
  10647. this._blendFunctionParameters[0] = null;
  10648. this._blendFunctionParameters[1] = null;
  10649. this._blendFunctionParameters[2] = null;
  10650. this._blendFunctionParameters[3] = null;
  10651. this._blendEquationParameters[0] = null;
  10652. this._blendEquationParameters[1] = null;
  10653. this._blendConstants[0] = null;
  10654. this._blendConstants[1] = null;
  10655. this._blendConstants[2] = null;
  10656. this._blendConstants[3] = null;
  10657. this._isAlphaBlendDirty = true;
  10658. this._isBlendFunctionParametersDirty = false;
  10659. this._isBlendEquationParametersDirty = false;
  10660. this._isBlendConstantsDirty = false;
  10661. };
  10662. _AlphaState.prototype.apply = function (gl) {
  10663. if (!this.isDirty) {
  10664. return;
  10665. }
  10666. // Alpha blend
  10667. if (this._isAlphaBlendDirty) {
  10668. if (this._alphaBlend) {
  10669. gl.enable(gl.BLEND);
  10670. }
  10671. else {
  10672. gl.disable(gl.BLEND);
  10673. }
  10674. this._isAlphaBlendDirty = false;
  10675. }
  10676. // Alpha function
  10677. if (this._isBlendFunctionParametersDirty) {
  10678. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10679. this._isBlendFunctionParametersDirty = false;
  10680. }
  10681. // Alpha equation
  10682. if (this._isBlendEquationParametersDirty) {
  10683. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10684. this._isBlendEquationParametersDirty = false;
  10685. }
  10686. // Constants
  10687. if (this._isBlendConstantsDirty) {
  10688. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10689. this._isBlendConstantsDirty = false;
  10690. }
  10691. };
  10692. return _AlphaState;
  10693. }());
  10694. BABYLON._AlphaState = _AlphaState;
  10695. })(BABYLON || (BABYLON = {}));
  10696. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10697. var BABYLON;
  10698. (function (BABYLON) {
  10699. /**
  10700. * @hidden
  10701. **/
  10702. var _DepthCullingState = /** @class */ (function () {
  10703. /**
  10704. * Initializes the state.
  10705. */
  10706. function _DepthCullingState() {
  10707. this._isDepthTestDirty = false;
  10708. this._isDepthMaskDirty = false;
  10709. this._isDepthFuncDirty = false;
  10710. this._isCullFaceDirty = false;
  10711. this._isCullDirty = false;
  10712. this._isZOffsetDirty = false;
  10713. this._isFrontFaceDirty = false;
  10714. this.reset();
  10715. }
  10716. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10717. get: function () {
  10718. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10724. get: function () {
  10725. return this._zOffset;
  10726. },
  10727. set: function (value) {
  10728. if (this._zOffset === value) {
  10729. return;
  10730. }
  10731. this._zOffset = value;
  10732. this._isZOffsetDirty = true;
  10733. },
  10734. enumerable: true,
  10735. configurable: true
  10736. });
  10737. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10738. get: function () {
  10739. return this._cullFace;
  10740. },
  10741. set: function (value) {
  10742. if (this._cullFace === value) {
  10743. return;
  10744. }
  10745. this._cullFace = value;
  10746. this._isCullFaceDirty = true;
  10747. },
  10748. enumerable: true,
  10749. configurable: true
  10750. });
  10751. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10752. get: function () {
  10753. return this._cull;
  10754. },
  10755. set: function (value) {
  10756. if (this._cull === value) {
  10757. return;
  10758. }
  10759. this._cull = value;
  10760. this._isCullDirty = true;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10766. get: function () {
  10767. return this._depthFunc;
  10768. },
  10769. set: function (value) {
  10770. if (this._depthFunc === value) {
  10771. return;
  10772. }
  10773. this._depthFunc = value;
  10774. this._isDepthFuncDirty = true;
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10780. get: function () {
  10781. return this._depthMask;
  10782. },
  10783. set: function (value) {
  10784. if (this._depthMask === value) {
  10785. return;
  10786. }
  10787. this._depthMask = value;
  10788. this._isDepthMaskDirty = true;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10794. get: function () {
  10795. return this._depthTest;
  10796. },
  10797. set: function (value) {
  10798. if (this._depthTest === value) {
  10799. return;
  10800. }
  10801. this._depthTest = value;
  10802. this._isDepthTestDirty = true;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10808. get: function () {
  10809. return this._frontFace;
  10810. },
  10811. set: function (value) {
  10812. if (this._frontFace === value) {
  10813. return;
  10814. }
  10815. this._frontFace = value;
  10816. this._isFrontFaceDirty = true;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. _DepthCullingState.prototype.reset = function () {
  10822. this._depthMask = true;
  10823. this._depthTest = true;
  10824. this._depthFunc = null;
  10825. this._cullFace = null;
  10826. this._cull = null;
  10827. this._zOffset = 0;
  10828. this._frontFace = null;
  10829. this._isDepthTestDirty = true;
  10830. this._isDepthMaskDirty = true;
  10831. this._isDepthFuncDirty = false;
  10832. this._isCullFaceDirty = false;
  10833. this._isCullDirty = false;
  10834. this._isZOffsetDirty = false;
  10835. this._isFrontFaceDirty = false;
  10836. };
  10837. _DepthCullingState.prototype.apply = function (gl) {
  10838. if (!this.isDirty) {
  10839. return;
  10840. }
  10841. // Cull
  10842. if (this._isCullDirty) {
  10843. if (this.cull) {
  10844. gl.enable(gl.CULL_FACE);
  10845. }
  10846. else {
  10847. gl.disable(gl.CULL_FACE);
  10848. }
  10849. this._isCullDirty = false;
  10850. }
  10851. // Cull face
  10852. if (this._isCullFaceDirty) {
  10853. gl.cullFace(this.cullFace);
  10854. this._isCullFaceDirty = false;
  10855. }
  10856. // Depth mask
  10857. if (this._isDepthMaskDirty) {
  10858. gl.depthMask(this.depthMask);
  10859. this._isDepthMaskDirty = false;
  10860. }
  10861. // Depth test
  10862. if (this._isDepthTestDirty) {
  10863. if (this.depthTest) {
  10864. gl.enable(gl.DEPTH_TEST);
  10865. }
  10866. else {
  10867. gl.disable(gl.DEPTH_TEST);
  10868. }
  10869. this._isDepthTestDirty = false;
  10870. }
  10871. // Depth func
  10872. if (this._isDepthFuncDirty) {
  10873. gl.depthFunc(this.depthFunc);
  10874. this._isDepthFuncDirty = false;
  10875. }
  10876. // zOffset
  10877. if (this._isZOffsetDirty) {
  10878. if (this.zOffset) {
  10879. gl.enable(gl.POLYGON_OFFSET_FILL);
  10880. gl.polygonOffset(this.zOffset, 0);
  10881. }
  10882. else {
  10883. gl.disable(gl.POLYGON_OFFSET_FILL);
  10884. }
  10885. this._isZOffsetDirty = false;
  10886. }
  10887. // Front face
  10888. if (this._isFrontFaceDirty) {
  10889. gl.frontFace(this.frontFace);
  10890. this._isFrontFaceDirty = false;
  10891. }
  10892. };
  10893. return _DepthCullingState;
  10894. }());
  10895. BABYLON._DepthCullingState = _DepthCullingState;
  10896. })(BABYLON || (BABYLON = {}));
  10897. //# sourceMappingURL=babylon.depthCullingState.js.map
  10898. var BABYLON;
  10899. (function (BABYLON) {
  10900. /**
  10901. * @hidden
  10902. **/
  10903. var _StencilState = /** @class */ (function () {
  10904. function _StencilState() {
  10905. this._isStencilTestDirty = false;
  10906. this._isStencilMaskDirty = false;
  10907. this._isStencilFuncDirty = false;
  10908. this._isStencilOpDirty = false;
  10909. this.reset();
  10910. }
  10911. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10912. get: function () {
  10913. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10919. get: function () {
  10920. return this._stencilFunc;
  10921. },
  10922. set: function (value) {
  10923. if (this._stencilFunc === value) {
  10924. return;
  10925. }
  10926. this._stencilFunc = value;
  10927. this._isStencilFuncDirty = true;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10933. get: function () {
  10934. return this._stencilFuncRef;
  10935. },
  10936. set: function (value) {
  10937. if (this._stencilFuncRef === value) {
  10938. return;
  10939. }
  10940. this._stencilFuncRef = value;
  10941. this._isStencilFuncDirty = true;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10947. get: function () {
  10948. return this._stencilFuncMask;
  10949. },
  10950. set: function (value) {
  10951. if (this._stencilFuncMask === value) {
  10952. return;
  10953. }
  10954. this._stencilFuncMask = value;
  10955. this._isStencilFuncDirty = true;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10961. get: function () {
  10962. return this._stencilOpStencilFail;
  10963. },
  10964. set: function (value) {
  10965. if (this._stencilOpStencilFail === value) {
  10966. return;
  10967. }
  10968. this._stencilOpStencilFail = value;
  10969. this._isStencilOpDirty = true;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10975. get: function () {
  10976. return this._stencilOpDepthFail;
  10977. },
  10978. set: function (value) {
  10979. if (this._stencilOpDepthFail === value) {
  10980. return;
  10981. }
  10982. this._stencilOpDepthFail = value;
  10983. this._isStencilOpDirty = true;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10989. get: function () {
  10990. return this._stencilOpStencilDepthPass;
  10991. },
  10992. set: function (value) {
  10993. if (this._stencilOpStencilDepthPass === value) {
  10994. return;
  10995. }
  10996. this._stencilOpStencilDepthPass = value;
  10997. this._isStencilOpDirty = true;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11003. get: function () {
  11004. return this._stencilMask;
  11005. },
  11006. set: function (value) {
  11007. if (this._stencilMask === value) {
  11008. return;
  11009. }
  11010. this._stencilMask = value;
  11011. this._isStencilMaskDirty = true;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11017. get: function () {
  11018. return this._stencilTest;
  11019. },
  11020. set: function (value) {
  11021. if (this._stencilTest === value) {
  11022. return;
  11023. }
  11024. this._stencilTest = value;
  11025. this._isStencilTestDirty = true;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. _StencilState.prototype.reset = function () {
  11031. this._stencilTest = false;
  11032. this._stencilMask = 0xFF;
  11033. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11034. this._stencilFuncRef = 1;
  11035. this._stencilFuncMask = 0xFF;
  11036. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11037. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11038. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11039. this._isStencilTestDirty = true;
  11040. this._isStencilMaskDirty = true;
  11041. this._isStencilFuncDirty = true;
  11042. this._isStencilOpDirty = true;
  11043. };
  11044. _StencilState.prototype.apply = function (gl) {
  11045. if (!this.isDirty) {
  11046. return;
  11047. }
  11048. // Stencil test
  11049. if (this._isStencilTestDirty) {
  11050. if (this.stencilTest) {
  11051. gl.enable(gl.STENCIL_TEST);
  11052. }
  11053. else {
  11054. gl.disable(gl.STENCIL_TEST);
  11055. }
  11056. this._isStencilTestDirty = false;
  11057. }
  11058. // Stencil mask
  11059. if (this._isStencilMaskDirty) {
  11060. gl.stencilMask(this.stencilMask);
  11061. this._isStencilMaskDirty = false;
  11062. }
  11063. // Stencil func
  11064. if (this._isStencilFuncDirty) {
  11065. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11066. this._isStencilFuncDirty = false;
  11067. }
  11068. // Stencil op
  11069. if (this._isStencilOpDirty) {
  11070. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11071. this._isStencilOpDirty = false;
  11072. }
  11073. };
  11074. return _StencilState;
  11075. }());
  11076. BABYLON._StencilState = _StencilState;
  11077. })(BABYLON || (BABYLON = {}));
  11078. //# sourceMappingURL=babylon.stencilState.js.map
  11079. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11080. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11081. s = arguments[i];
  11082. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11083. t[p] = s[p];
  11084. }
  11085. return t;
  11086. };
  11087. var BABYLON;
  11088. (function (BABYLON) {
  11089. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11090. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11091. };
  11092. var compileRawShader = function (gl, source, type) {
  11093. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11094. gl.shaderSource(shader, source);
  11095. gl.compileShader(shader);
  11096. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11097. var log = gl.getShaderInfoLog(shader);
  11098. if (log) {
  11099. throw new Error(log);
  11100. }
  11101. }
  11102. if (!shader) {
  11103. throw new Error("Something went wrong while compile the shader.");
  11104. }
  11105. return shader;
  11106. };
  11107. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11108. var magFilter = gl.NEAREST;
  11109. var minFilter = gl.NEAREST;
  11110. switch (samplingMode) {
  11111. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11112. magFilter = gl.LINEAR;
  11113. if (generateMipMaps) {
  11114. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11115. }
  11116. else {
  11117. minFilter = gl.LINEAR;
  11118. }
  11119. break;
  11120. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11121. magFilter = gl.LINEAR;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11124. }
  11125. else {
  11126. minFilter = gl.LINEAR;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11130. magFilter = gl.NEAREST;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11133. }
  11134. else {
  11135. minFilter = gl.NEAREST;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11142. }
  11143. else {
  11144. minFilter = gl.NEAREST;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11148. magFilter = gl.NEAREST;
  11149. if (generateMipMaps) {
  11150. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11151. }
  11152. else {
  11153. minFilter = gl.LINEAR;
  11154. }
  11155. break;
  11156. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11157. magFilter = gl.NEAREST;
  11158. if (generateMipMaps) {
  11159. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11160. }
  11161. else {
  11162. minFilter = gl.LINEAR;
  11163. }
  11164. break;
  11165. case BABYLON.Texture.NEAREST_LINEAR:
  11166. magFilter = gl.NEAREST;
  11167. minFilter = gl.LINEAR;
  11168. break;
  11169. case BABYLON.Texture.NEAREST_NEAREST:
  11170. magFilter = gl.NEAREST;
  11171. minFilter = gl.NEAREST;
  11172. break;
  11173. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11174. magFilter = gl.LINEAR;
  11175. if (generateMipMaps) {
  11176. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11177. }
  11178. else {
  11179. minFilter = gl.NEAREST;
  11180. }
  11181. break;
  11182. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11183. magFilter = gl.LINEAR;
  11184. if (generateMipMaps) {
  11185. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11186. }
  11187. else {
  11188. minFilter = gl.NEAREST;
  11189. }
  11190. break;
  11191. case BABYLON.Texture.LINEAR_LINEAR:
  11192. magFilter = gl.LINEAR;
  11193. minFilter = gl.LINEAR;
  11194. break;
  11195. case BABYLON.Texture.LINEAR_NEAREST:
  11196. magFilter = gl.LINEAR;
  11197. minFilter = gl.NEAREST;
  11198. break;
  11199. }
  11200. return {
  11201. min: minFilter,
  11202. mag: magFilter
  11203. };
  11204. };
  11205. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11206. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11207. var img;
  11208. var onload = function () {
  11209. loadedImages[index] = img;
  11210. loadedImages._internalCount++;
  11211. if (scene) {
  11212. scene._removePendingData(img);
  11213. }
  11214. if (loadedImages._internalCount === 6) {
  11215. onfinish(loadedImages);
  11216. }
  11217. };
  11218. var onerror = function (message, exception) {
  11219. if (scene) {
  11220. scene._removePendingData(img);
  11221. }
  11222. if (onErrorCallBack) {
  11223. onErrorCallBack(message, exception);
  11224. }
  11225. };
  11226. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11227. if (scene) {
  11228. scene._addPendingData(img);
  11229. }
  11230. };
  11231. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11232. if (onError === void 0) { onError = null; }
  11233. var loadedImages = [];
  11234. loadedImages._internalCount = 0;
  11235. for (var index = 0; index < 6; index++) {
  11236. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11237. }
  11238. };
  11239. var BufferPointer = /** @class */ (function () {
  11240. function BufferPointer() {
  11241. }
  11242. return BufferPointer;
  11243. }());
  11244. /**
  11245. * Interface for attribute information associated with buffer instanciation
  11246. */
  11247. var InstancingAttributeInfo = /** @class */ (function () {
  11248. function InstancingAttributeInfo() {
  11249. }
  11250. return InstancingAttributeInfo;
  11251. }());
  11252. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11253. /**
  11254. * Define options used to create a render target texture
  11255. */
  11256. var RenderTargetCreationOptions = /** @class */ (function () {
  11257. function RenderTargetCreationOptions() {
  11258. }
  11259. return RenderTargetCreationOptions;
  11260. }());
  11261. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11262. /**
  11263. * Define options used to create a depth texture
  11264. */
  11265. var DepthTextureCreationOptions = /** @class */ (function () {
  11266. function DepthTextureCreationOptions() {
  11267. }
  11268. return DepthTextureCreationOptions;
  11269. }());
  11270. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11271. /**
  11272. * Class used to describe the capabilities of the engine relatively to the current browser
  11273. */
  11274. var EngineCapabilities = /** @class */ (function () {
  11275. function EngineCapabilities() {
  11276. }
  11277. return EngineCapabilities;
  11278. }());
  11279. BABYLON.EngineCapabilities = EngineCapabilities;
  11280. /**
  11281. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11282. */
  11283. var Engine = /** @class */ (function () {
  11284. /**
  11285. * Creates a new engine
  11286. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11287. * @param antialias defines enable antialiasing (default: false)
  11288. * @param options defines further options to be sent to the getContext() function
  11289. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11290. */
  11291. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11292. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11293. var _this = this;
  11294. // Public members
  11295. /**
  11296. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11297. */
  11298. this.forcePOTTextures = false;
  11299. /**
  11300. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11301. */
  11302. this.isFullscreen = false;
  11303. /**
  11304. * Gets a boolean indicating if the pointer is currently locked
  11305. */
  11306. this.isPointerLock = false;
  11307. /**
  11308. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11309. */
  11310. this.cullBackFaces = true;
  11311. /**
  11312. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11313. */
  11314. this.renderEvenInBackground = true;
  11315. /**
  11316. * Gets or sets a boolean indicating that cache can be kept between frames
  11317. */
  11318. this.preventCacheWipeBetweenFrames = false;
  11319. /**
  11320. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11321. **/
  11322. this.enableOfflineSupport = false;
  11323. /**
  11324. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11325. **/
  11326. this.disableManifestCheck = false;
  11327. /**
  11328. * Gets the list of created scenes
  11329. */
  11330. this.scenes = new Array();
  11331. /**
  11332. * Gets the list of created postprocesses
  11333. */
  11334. this.postProcesses = new Array();
  11335. // Observables
  11336. /**
  11337. * Observable event triggered each time the rendering canvas is resized
  11338. */
  11339. this.onResizeObservable = new BABYLON.Observable();
  11340. /**
  11341. * Observable event triggered each time the canvas loses focus
  11342. */
  11343. this.onCanvasBlurObservable = new BABYLON.Observable();
  11344. /**
  11345. * Observable event triggered each time the canvas gains focus
  11346. */
  11347. this.onCanvasFocusObservable = new BABYLON.Observable();
  11348. /**
  11349. * Observable event triggered each time the canvas receives pointerout event
  11350. */
  11351. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11352. /**
  11353. * Observable event triggered before each texture is initialized
  11354. */
  11355. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11356. //WebVR
  11357. this._vrDisplay = undefined;
  11358. this._vrSupported = false;
  11359. this._vrExclusivePointerMode = false;
  11360. // Uniform buffers list
  11361. /**
  11362. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11363. */
  11364. this.disableUniformBuffers = false;
  11365. /** @hidden */
  11366. this._uniformBuffers = new Array();
  11367. // Observables
  11368. /**
  11369. * Observable raised when the engine begins a new frame
  11370. */
  11371. this.onBeginFrameObservable = new BABYLON.Observable();
  11372. /**
  11373. * Observable raised when the engine ends the current frame
  11374. */
  11375. this.onEndFrameObservable = new BABYLON.Observable();
  11376. /**
  11377. * Observable raised when the engine is about to compile a shader
  11378. */
  11379. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11380. /**
  11381. * Observable raised when the engine has jsut compiled a shader
  11382. */
  11383. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11384. this._windowIsBackground = false;
  11385. this._webGLVersion = 1.0;
  11386. /** @hidden */
  11387. this._badOS = false;
  11388. /** @hidden */
  11389. this._badDesktopOS = false;
  11390. /**
  11391. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11392. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11393. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11394. */
  11395. this.disableTextureBindingOptimization = false;
  11396. /**
  11397. * Observable signaled when VR display mode changes
  11398. */
  11399. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11400. /**
  11401. * Observable signaled when VR request present is complete
  11402. */
  11403. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11404. /**
  11405. * Observable signaled when VR request present starts
  11406. */
  11407. this.onVRRequestPresentStart = new BABYLON.Observable();
  11408. this._colorWrite = true;
  11409. /** @hidden */
  11410. this._drawCalls = new BABYLON.PerfCounter();
  11411. /** @hidden */
  11412. this._textureCollisions = new BABYLON.PerfCounter();
  11413. this._renderingQueueLaunched = false;
  11414. this._activeRenderLoops = new Array();
  11415. // Deterministic lockstepMaxSteps
  11416. this._deterministicLockstep = false;
  11417. this._lockstepMaxSteps = 4;
  11418. // Lost context
  11419. /**
  11420. * Observable signaled when a context lost event is raised
  11421. */
  11422. this.onContextLostObservable = new BABYLON.Observable();
  11423. /**
  11424. * Observable signaled when a context restored event is raised
  11425. */
  11426. this.onContextRestoredObservable = new BABYLON.Observable();
  11427. this._contextWasLost = false;
  11428. this._doNotHandleContextLost = false;
  11429. // FPS
  11430. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11431. this._fps = 60;
  11432. this._deltaTime = 0;
  11433. /**
  11434. * Turn this value on if you want to pause FPS computation when in background
  11435. */
  11436. this.disablePerformanceMonitorInBackground = false;
  11437. // States
  11438. /** @hidden */
  11439. this._depthCullingState = new BABYLON._DepthCullingState();
  11440. /** @hidden */
  11441. this._stencilState = new BABYLON._StencilState();
  11442. /** @hidden */
  11443. this._alphaState = new BABYLON._AlphaState();
  11444. /** @hidden */
  11445. this._alphaMode = Engine.ALPHA_DISABLE;
  11446. // Cache
  11447. this._internalTexturesCache = new Array();
  11448. /** @hidden */
  11449. this._activeChannel = 0;
  11450. this._currentTextureChannel = -1;
  11451. /** @hidden */
  11452. this._boundTexturesCache = {};
  11453. this._compiledEffects = {};
  11454. this._vertexAttribArraysEnabled = [];
  11455. this._uintIndicesCurrentlySet = false;
  11456. this._currentBoundBuffer = new Array();
  11457. this._currentBufferPointers = new Array();
  11458. this._currentInstanceLocations = new Array();
  11459. this._currentInstanceBuffers = new Array();
  11460. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11461. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11462. this._vaoRecordInProgress = false;
  11463. this._mustWipeVertexAttributes = false;
  11464. this._nextFreeTextureSlots = new Array();
  11465. this._maxSimultaneousTextures = 0;
  11466. this._activeRequests = new Array();
  11467. // Hardware supported Compressed Textures
  11468. this._texturesSupported = new Array();
  11469. /**
  11470. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11471. */
  11472. this.premultipliedAlpha = true;
  11473. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11474. this._onVRFullScreenTriggered = function () {
  11475. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11476. //get the old size before we change
  11477. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11478. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11479. //get the width and height, change the render size
  11480. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11481. _this.setHardwareScalingLevel(1);
  11482. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11483. }
  11484. else {
  11485. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11486. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11487. }
  11488. };
  11489. this._unpackFlipYCached = null;
  11490. this._boundUniforms = {};
  11491. // Register promises
  11492. BABYLON.PromisePolyfill.Apply();
  11493. var canvas = null;
  11494. Engine.Instances.push(this);
  11495. if (!canvasOrContext) {
  11496. return;
  11497. }
  11498. options = options || {};
  11499. if (canvasOrContext.getContext) {
  11500. canvas = canvasOrContext;
  11501. this._renderingCanvas = canvas;
  11502. if (antialias != null) {
  11503. options.antialias = antialias;
  11504. }
  11505. if (options.deterministicLockstep === undefined) {
  11506. options.deterministicLockstep = false;
  11507. }
  11508. if (options.lockstepMaxSteps === undefined) {
  11509. options.lockstepMaxSteps = 4;
  11510. }
  11511. if (options.preserveDrawingBuffer === undefined) {
  11512. options.preserveDrawingBuffer = false;
  11513. }
  11514. if (options.audioEngine === undefined) {
  11515. options.audioEngine = true;
  11516. }
  11517. if (options.stencil === undefined) {
  11518. options.stencil = true;
  11519. }
  11520. if (options.premultipliedAlpha === false) {
  11521. this.premultipliedAlpha = false;
  11522. }
  11523. this._deterministicLockstep = options.deterministicLockstep;
  11524. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11525. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11526. // Exceptions
  11527. if (navigator && navigator.userAgent) {
  11528. var ua = navigator.userAgent;
  11529. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11530. var exception = _a[_i];
  11531. var key = exception.key;
  11532. var targets = exception.targets;
  11533. if (ua.indexOf(key) > -1) {
  11534. if (exception.capture && exception.captureConstraint) {
  11535. var capture = exception.capture;
  11536. var constraint = exception.captureConstraint;
  11537. var regex = new RegExp(capture);
  11538. var matches = regex.exec(ua);
  11539. if (matches && matches.length > 0) {
  11540. var capturedValue = parseInt(matches[matches.length - 1]);
  11541. if (capturedValue >= constraint) {
  11542. continue;
  11543. }
  11544. }
  11545. }
  11546. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11547. var target = targets_1[_b];
  11548. switch (target) {
  11549. case "uniformBuffer":
  11550. this.disableUniformBuffers = true;
  11551. break;
  11552. case "textureBindingOptimization":
  11553. this.disableTextureBindingOptimization = true;
  11554. break;
  11555. }
  11556. }
  11557. }
  11558. }
  11559. }
  11560. // GL
  11561. if (!options.disableWebGL2Support) {
  11562. try {
  11563. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11564. if (this._gl) {
  11565. this._webGLVersion = 2.0;
  11566. }
  11567. }
  11568. catch (e) {
  11569. // Do nothing
  11570. }
  11571. }
  11572. if (!this._gl) {
  11573. if (!canvas) {
  11574. throw new Error("The provided canvas is null or undefined.");
  11575. }
  11576. try {
  11577. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11578. }
  11579. catch (e) {
  11580. throw new Error("WebGL not supported");
  11581. }
  11582. }
  11583. if (!this._gl) {
  11584. throw new Error("WebGL not supported");
  11585. }
  11586. this._onCanvasFocus = function () {
  11587. _this.onCanvasFocusObservable.notifyObservers(_this);
  11588. };
  11589. this._onCanvasBlur = function () {
  11590. _this.onCanvasBlurObservable.notifyObservers(_this);
  11591. };
  11592. canvas.addEventListener("focus", this._onCanvasFocus);
  11593. canvas.addEventListener("blur", this._onCanvasBlur);
  11594. this._onBlur = function () {
  11595. if (_this.disablePerformanceMonitorInBackground) {
  11596. _this._performanceMonitor.disable();
  11597. }
  11598. _this._windowIsBackground = true;
  11599. };
  11600. this._onFocus = function () {
  11601. if (_this.disablePerformanceMonitorInBackground) {
  11602. _this._performanceMonitor.enable();
  11603. }
  11604. _this._windowIsBackground = false;
  11605. };
  11606. this._onCanvasPointerOut = function (ev) {
  11607. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11608. };
  11609. window.addEventListener("blur", this._onBlur);
  11610. window.addEventListener("focus", this._onFocus);
  11611. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11612. // Context lost
  11613. if (!this._doNotHandleContextLost) {
  11614. this._onContextLost = function (evt) {
  11615. evt.preventDefault();
  11616. _this._contextWasLost = true;
  11617. BABYLON.Tools.Warn("WebGL context lost.");
  11618. _this.onContextLostObservable.notifyObservers(_this);
  11619. };
  11620. this._onContextRestored = function (evt) {
  11621. // Adding a timeout to avoid race condition at browser level
  11622. setTimeout(function () {
  11623. // Rebuild gl context
  11624. _this._initGLContext();
  11625. // Rebuild effects
  11626. _this._rebuildEffects();
  11627. // Rebuild textures
  11628. _this._rebuildInternalTextures();
  11629. // Rebuild buffers
  11630. _this._rebuildBuffers();
  11631. // Cache
  11632. _this.wipeCaches(true);
  11633. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11634. _this.onContextRestoredObservable.notifyObservers(_this);
  11635. _this._contextWasLost = false;
  11636. }, 0);
  11637. };
  11638. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11639. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11640. }
  11641. }
  11642. else {
  11643. this._gl = canvasOrContext;
  11644. this._renderingCanvas = this._gl.canvas;
  11645. if (this._gl.renderbufferStorageMultisample) {
  11646. this._webGLVersion = 2.0;
  11647. }
  11648. options.stencil = this._gl.getContextAttributes().stencil;
  11649. }
  11650. // Viewport
  11651. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11652. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11653. this.resize();
  11654. this._isStencilEnable = options.stencil ? true : false;
  11655. this._initGLContext();
  11656. if (canvas) {
  11657. // Fullscreen
  11658. this._onFullscreenChange = function () {
  11659. if (document.fullscreen !== undefined) {
  11660. _this.isFullscreen = document.fullscreen;
  11661. }
  11662. else if (document.mozFullScreen !== undefined) {
  11663. _this.isFullscreen = document.mozFullScreen;
  11664. }
  11665. else if (document.webkitIsFullScreen !== undefined) {
  11666. _this.isFullscreen = document.webkitIsFullScreen;
  11667. }
  11668. else if (document.msIsFullScreen !== undefined) {
  11669. _this.isFullscreen = document.msIsFullScreen;
  11670. }
  11671. // Pointer lock
  11672. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11673. canvas.requestPointerLock = canvas.requestPointerLock ||
  11674. canvas.msRequestPointerLock ||
  11675. canvas.mozRequestPointerLock ||
  11676. canvas.webkitRequestPointerLock;
  11677. if (canvas.requestPointerLock) {
  11678. canvas.requestPointerLock();
  11679. }
  11680. }
  11681. };
  11682. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11683. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11684. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11685. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11686. // Pointer lock
  11687. this._onPointerLockChange = function () {
  11688. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11689. document.webkitPointerLockElement === canvas ||
  11690. document.msPointerLockElement === canvas ||
  11691. document.pointerLockElement === canvas);
  11692. };
  11693. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11694. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11695. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11696. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11697. this._onVRDisplayPointerRestricted = function () {
  11698. if (canvas) {
  11699. canvas.requestPointerLock();
  11700. }
  11701. };
  11702. this._onVRDisplayPointerUnrestricted = function () {
  11703. document.exitPointerLock();
  11704. };
  11705. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11706. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11707. }
  11708. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11709. Engine.audioEngine = new BABYLON.AudioEngine();
  11710. }
  11711. // Prepare buffer pointers
  11712. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11713. this._currentBufferPointers[i] = new BufferPointer();
  11714. }
  11715. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11716. // Load WebVR Devices
  11717. if (options.autoEnableWebVR) {
  11718. this.initWebVR();
  11719. }
  11720. // Detect if we are running on a faulty buggy OS.
  11721. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11722. // Detect if we are running on a faulty buggy desktop OS.
  11723. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11724. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11725. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11726. }
  11727. Object.defineProperty(Engine, "LastCreatedEngine", {
  11728. /**
  11729. * Gets the latest created engine
  11730. */
  11731. get: function () {
  11732. if (Engine.Instances.length === 0) {
  11733. return null;
  11734. }
  11735. return Engine.Instances[Engine.Instances.length - 1];
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "LastCreatedScene", {
  11741. /**
  11742. * Gets the latest created scene
  11743. */
  11744. get: function () {
  11745. var lastCreatedEngine = Engine.LastCreatedEngine;
  11746. if (!lastCreatedEngine) {
  11747. return null;
  11748. }
  11749. if (lastCreatedEngine.scenes.length === 0) {
  11750. return null;
  11751. }
  11752. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. /**
  11758. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11759. * @param flag defines which part of the materials must be marked as dirty
  11760. * @param predicate defines a predicate used to filter which materials should be affected
  11761. */
  11762. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11763. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11764. var engine = Engine.Instances[engineIndex];
  11765. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11766. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11767. }
  11768. }
  11769. };
  11770. Object.defineProperty(Engine, "NEVER", {
  11771. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11772. get: function () {
  11773. return Engine._NEVER;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Engine, "ALWAYS", {
  11779. /** 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 */
  11780. get: function () {
  11781. return Engine._ALWAYS;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine, "LESS", {
  11787. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11788. get: function () {
  11789. return Engine._LESS;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine, "EQUAL", {
  11795. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11796. get: function () {
  11797. return Engine._EQUAL;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine, "LEQUAL", {
  11803. /** 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 */
  11804. get: function () {
  11805. return Engine._LEQUAL;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "GREATER", {
  11811. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11812. get: function () {
  11813. return Engine._GREATER;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "GEQUAL", {
  11819. /** 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 */
  11820. get: function () {
  11821. return Engine._GEQUAL;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "NOTEQUAL", {
  11827. /** 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 */
  11828. get: function () {
  11829. return Engine._NOTEQUAL;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "KEEP", {
  11835. /** Passed to stencilOperation to specify that stencil value must be kept */
  11836. get: function () {
  11837. return Engine._KEEP;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "REPLACE", {
  11843. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11844. get: function () {
  11845. return Engine._REPLACE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "INCR", {
  11851. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11852. get: function () {
  11853. return Engine._INCR;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "DECR", {
  11859. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11860. get: function () {
  11861. return Engine._DECR;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "INVERT", {
  11867. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11868. get: function () {
  11869. return Engine._INVERT;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "INCR_WRAP", {
  11875. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11876. get: function () {
  11877. return Engine._INCR_WRAP;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "DECR_WRAP", {
  11883. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11884. get: function () {
  11885. return Engine._DECR_WRAP;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11891. // Alpha
  11892. /** Defines that alpha blending is disabled */
  11893. get: function () {
  11894. return Engine._ALPHA_DISABLE;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11900. /** Defines that alpha blending to SRC + DEST */
  11901. get: function () {
  11902. return Engine._ALPHA_ONEONE;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "ALPHA_ADD", {
  11908. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11909. get: function () {
  11910. return Engine._ALPHA_ADD;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11916. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11917. get: function () {
  11918. return Engine._ALPHA_COMBINE;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11924. /** Defines that alpha blending to DEST - SRC * DEST */
  11925. get: function () {
  11926. return Engine._ALPHA_SUBTRACT;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11932. /** Defines that alpha blending to SRC * DEST */
  11933. get: function () {
  11934. return Engine._ALPHA_MULTIPLY;
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11940. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11941. get: function () {
  11942. return Engine._ALPHA_MAXIMIZED;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11948. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11949. get: function () {
  11950. return Engine._ALPHA_PREMULTIPLIED;
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11956. /**
  11957. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11958. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11959. */
  11960. get: function () {
  11961. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11962. },
  11963. enumerable: true,
  11964. configurable: true
  11965. });
  11966. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11967. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11968. get: function () {
  11969. return Engine._ALPHA_INTERPOLATE;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11975. /**
  11976. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11977. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11978. */
  11979. get: function () {
  11980. return Engine._ALPHA_SCREENMODE;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11986. // Delays
  11987. /** Defines that the ressource is not delayed*/
  11988. get: function () {
  11989. return Engine._DELAYLOADSTATE_NONE;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11995. /** Defines that the ressource was successfully delay loaded */
  11996. get: function () {
  11997. return Engine._DELAYLOADSTATE_LOADED;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12003. /** Defines that the ressource is currently delay loading */
  12004. get: function () {
  12005. return Engine._DELAYLOADSTATE_LOADING;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12011. /** Defines that the ressource is delayed and has not started loading */
  12012. get: function () {
  12013. return Engine._DELAYLOADSTATE_NOTLOADED;
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12019. /** ALPHA */
  12020. get: function () {
  12021. return Engine._TEXTUREFORMAT_ALPHA;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12027. /** LUMINANCE */
  12028. get: function () {
  12029. return Engine._TEXTUREFORMAT_LUMINANCE;
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12035. /**
  12036. * R
  12037. */
  12038. get: function () {
  12039. return Engine._TEXTUREFORMAT_R;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12045. /**
  12046. * RG
  12047. */
  12048. get: function () {
  12049. return Engine._TEXTUREFORMAT_RG;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12055. /** LUMINANCE_ALPHA */
  12056. get: function () {
  12057. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12063. /** RGB */
  12064. get: function () {
  12065. return Engine._TEXTUREFORMAT_RGB;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12071. /** RGBA */
  12072. get: function () {
  12073. return Engine._TEXTUREFORMAT_RGBA;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12079. /** UNSIGNED_INT */
  12080. get: function () {
  12081. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12087. /** FLOAT */
  12088. get: function () {
  12089. return Engine._TEXTURETYPE_FLOAT;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12095. /** HALF_FLOAT */
  12096. get: function () {
  12097. return Engine._TEXTURETYPE_HALF_FLOAT;
  12098. },
  12099. enumerable: true,
  12100. configurable: true
  12101. });
  12102. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12103. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12104. get: function () {
  12105. return Engine._SCALEMODE_FLOOR;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12111. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12112. get: function () {
  12113. return Engine._SCALEMODE_NEAREST;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12119. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12120. get: function () {
  12121. return Engine._SCALEMODE_CEILING;
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Engine, "Version", {
  12127. /**
  12128. * Returns the current version of the framework
  12129. */
  12130. get: function () {
  12131. return "3.3.0-alpha.8";
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12137. /**
  12138. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12139. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12140. */
  12141. get: function () {
  12142. return this._vrExclusivePointerMode;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12148. /**
  12149. * Gets a boolean indicating that the engine supports uniform buffers
  12150. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12151. */
  12152. get: function () {
  12153. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12159. /**
  12160. * Gets a boolean indicating that only power of 2 textures are supported
  12161. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12162. */
  12163. get: function () {
  12164. return this._webGLVersion < 2 || this.forcePOTTextures;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12170. /**
  12171. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12172. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12173. */
  12174. get: function () {
  12175. return this._doNotHandleContextLost;
  12176. },
  12177. set: function (value) {
  12178. this._doNotHandleContextLost = value;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12184. /**
  12185. * Gets the performance monitor attached to this engine
  12186. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12187. */
  12188. get: function () {
  12189. return this._performanceMonitor;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12195. /**
  12196. * Gets the list of texture formats supported
  12197. */
  12198. get: function () {
  12199. return this._texturesSupported;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12205. /**
  12206. * Gets the list of texture formats in use
  12207. */
  12208. get: function () {
  12209. return this._textureFormatInUse;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Engine.prototype, "currentViewport", {
  12215. /**
  12216. * Gets the current viewport
  12217. */
  12218. get: function () {
  12219. return this._cachedViewport;
  12220. },
  12221. enumerable: true,
  12222. configurable: true
  12223. });
  12224. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12225. /**
  12226. * Gets the default empty texture
  12227. */
  12228. get: function () {
  12229. if (!this._emptyTexture) {
  12230. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12231. }
  12232. return this._emptyTexture;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12238. /**
  12239. * Gets the default empty 3D texture
  12240. */
  12241. get: function () {
  12242. if (!this._emptyTexture3D) {
  12243. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12244. }
  12245. return this._emptyTexture3D;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12251. /**
  12252. * Gets the default empty cube texture
  12253. */
  12254. get: function () {
  12255. if (!this._emptyCubeTexture) {
  12256. var faceData = new Uint8Array(4);
  12257. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12258. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12259. }
  12260. return this._emptyCubeTexture;
  12261. },
  12262. enumerable: true,
  12263. configurable: true
  12264. });
  12265. Engine.prototype._rebuildInternalTextures = function () {
  12266. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12267. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12268. var internalTexture = currentState_1[_i];
  12269. internalTexture._rebuild();
  12270. }
  12271. };
  12272. Engine.prototype._rebuildEffects = function () {
  12273. for (var key in this._compiledEffects) {
  12274. var effect = this._compiledEffects[key];
  12275. effect._prepareEffect();
  12276. }
  12277. BABYLON.Effect.ResetCache();
  12278. };
  12279. Engine.prototype._rebuildBuffers = function () {
  12280. // Index / Vertex
  12281. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12282. var scene = _a[_i];
  12283. scene.resetCachedMaterial();
  12284. scene._rebuildGeometries();
  12285. scene._rebuildTextures();
  12286. }
  12287. // Uniforms
  12288. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12289. var uniformBuffer = _c[_b];
  12290. uniformBuffer._rebuild();
  12291. }
  12292. };
  12293. Engine.prototype._initGLContext = function () {
  12294. // Caps
  12295. this._caps = new EngineCapabilities();
  12296. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12297. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12298. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12299. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12300. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12301. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12302. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12303. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12304. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12305. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12306. // Infos
  12307. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12308. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12309. if (rendererInfo != null) {
  12310. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12311. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12312. }
  12313. if (!this._glVendor) {
  12314. this._glVendor = "Unknown vendor";
  12315. }
  12316. if (!this._glRenderer) {
  12317. this._glRenderer = "Unknown renderer";
  12318. }
  12319. // Constants
  12320. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12321. if (this._gl.RGBA16F !== 0x881A) {
  12322. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12323. }
  12324. if (this._gl.RGBA32F !== 0x8814) {
  12325. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12326. }
  12327. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12328. this._gl.DEPTH24_STENCIL8 = 35056;
  12329. }
  12330. // Extensions
  12331. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12332. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12333. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12334. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12335. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12336. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12337. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12338. 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');
  12339. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12340. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12341. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12342. this._caps.highPrecisionShaderSupported = true;
  12343. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12344. if (this._caps.timerQuery) {
  12345. if (this._webGLVersion === 1) {
  12346. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12347. }
  12348. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12349. }
  12350. // Checks if some of the format renders first to allow the use of webgl inspector.
  12351. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12352. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12353. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12354. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12355. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12356. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12357. if (this._webGLVersion > 1) {
  12358. this._gl.HALF_FLOAT_OES = 0x140B;
  12359. }
  12360. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12361. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12362. // Draw buffers
  12363. if (this._webGLVersion > 1) {
  12364. this._caps.drawBuffersExtension = true;
  12365. }
  12366. else {
  12367. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12368. if (drawBuffersExtension !== null) {
  12369. this._caps.drawBuffersExtension = true;
  12370. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12371. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12372. for (var i = 0; i < 16; i++) {
  12373. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12374. }
  12375. }
  12376. else {
  12377. this._caps.drawBuffersExtension = false;
  12378. }
  12379. }
  12380. // Depth Texture
  12381. if (this._webGLVersion > 1) {
  12382. this._caps.depthTextureExtension = true;
  12383. }
  12384. else {
  12385. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12386. if (depthTextureExtension != null) {
  12387. this._caps.depthTextureExtension = true;
  12388. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12389. }
  12390. }
  12391. // Vertex array object
  12392. if (this._webGLVersion > 1) {
  12393. this._caps.vertexArrayObject = true;
  12394. }
  12395. else {
  12396. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12397. if (vertexArrayObjectExtension != null) {
  12398. this._caps.vertexArrayObject = true;
  12399. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12400. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12401. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12402. }
  12403. else {
  12404. this._caps.vertexArrayObject = false;
  12405. }
  12406. }
  12407. // Instances count
  12408. if (this._webGLVersion > 1) {
  12409. this._caps.instancedArrays = true;
  12410. }
  12411. else {
  12412. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12413. if (instanceExtension != null) {
  12414. this._caps.instancedArrays = true;
  12415. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12416. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12417. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12418. }
  12419. else {
  12420. this._caps.instancedArrays = false;
  12421. }
  12422. }
  12423. // Intelligently add supported compressed formats in order to check for.
  12424. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12425. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12426. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12427. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12428. if (this._caps.astc)
  12429. this.texturesSupported.push('-astc.ktx');
  12430. if (this._caps.s3tc)
  12431. this.texturesSupported.push('-dxt.ktx');
  12432. if (this._caps.pvrtc)
  12433. this.texturesSupported.push('-pvrtc.ktx');
  12434. if (this._caps.etc2)
  12435. this.texturesSupported.push('-etc2.ktx');
  12436. if (this._caps.etc1)
  12437. this.texturesSupported.push('-etc1.ktx');
  12438. if (this._gl.getShaderPrecisionFormat) {
  12439. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12440. if (highp) {
  12441. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12442. }
  12443. }
  12444. // Depth buffer
  12445. this.setDepthBuffer(true);
  12446. this.setDepthFunctionToLessOrEqual();
  12447. this.setDepthWrite(true);
  12448. // Texture maps
  12449. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12450. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12451. this._nextFreeTextureSlots.push(slot);
  12452. }
  12453. };
  12454. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12455. /**
  12456. * Gets version of the current webGL context
  12457. */
  12458. get: function () {
  12459. return this._webGLVersion;
  12460. },
  12461. enumerable: true,
  12462. configurable: true
  12463. });
  12464. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12465. /**
  12466. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12467. */
  12468. get: function () {
  12469. return this._isStencilEnable;
  12470. },
  12471. enumerable: true,
  12472. configurable: true
  12473. });
  12474. Engine.prototype._prepareWorkingCanvas = function () {
  12475. if (this._workingCanvas) {
  12476. return;
  12477. }
  12478. this._workingCanvas = document.createElement("canvas");
  12479. var context = this._workingCanvas.getContext("2d");
  12480. if (context) {
  12481. this._workingContext = context;
  12482. }
  12483. };
  12484. /**
  12485. * Reset the texture cache to empty state
  12486. */
  12487. Engine.prototype.resetTextureCache = function () {
  12488. for (var key in this._boundTexturesCache) {
  12489. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12490. continue;
  12491. }
  12492. var boundTexture = this._boundTexturesCache[key];
  12493. if (boundTexture) {
  12494. this._removeDesignatedSlot(boundTexture);
  12495. }
  12496. this._boundTexturesCache[key] = null;
  12497. }
  12498. if (!this.disableTextureBindingOptimization) {
  12499. this._nextFreeTextureSlots = [];
  12500. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12501. this._nextFreeTextureSlots.push(slot);
  12502. }
  12503. }
  12504. this._currentTextureChannel = -1;
  12505. };
  12506. /**
  12507. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12508. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12509. * @returns true if engine is in deterministic lock step mode
  12510. */
  12511. Engine.prototype.isDeterministicLockStep = function () {
  12512. return this._deterministicLockstep;
  12513. };
  12514. /**
  12515. * Gets the max steps when engine is running in deterministic lock step
  12516. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12517. * @returns the max steps
  12518. */
  12519. Engine.prototype.getLockstepMaxSteps = function () {
  12520. return this._lockstepMaxSteps;
  12521. };
  12522. /**
  12523. * Gets an object containing information about the current webGL context
  12524. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12525. */
  12526. Engine.prototype.getGlInfo = function () {
  12527. return {
  12528. vendor: this._glVendor,
  12529. renderer: this._glRenderer,
  12530. version: this._glVersion
  12531. };
  12532. };
  12533. /**
  12534. * Gets current aspect ratio
  12535. * @param camera defines the camera to use to get the aspect ratio
  12536. * @param useScreen defines if screen size must be used (or the current render target if any)
  12537. * @returns a number defining the aspect ratio
  12538. */
  12539. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12540. if (useScreen === void 0) { useScreen = false; }
  12541. var viewport = camera.viewport;
  12542. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12543. };
  12544. /**
  12545. * Gets current screen aspect ratio
  12546. * @returns a number defining the aspect ratio
  12547. */
  12548. Engine.prototype.getScreenAspectRatio = function () {
  12549. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12550. };
  12551. /**
  12552. * Gets the current render width
  12553. * @param useScreen defines if screen size must be used (or the current render target if any)
  12554. * @returns a number defining the current render width
  12555. */
  12556. Engine.prototype.getRenderWidth = function (useScreen) {
  12557. if (useScreen === void 0) { useScreen = false; }
  12558. if (!useScreen && this._currentRenderTarget) {
  12559. return this._currentRenderTarget.width;
  12560. }
  12561. return this._gl.drawingBufferWidth;
  12562. };
  12563. /**
  12564. * Gets the current render height
  12565. * @param useScreen defines if screen size must be used (or the current render target if any)
  12566. * @returns a number defining the current render height
  12567. */
  12568. Engine.prototype.getRenderHeight = function (useScreen) {
  12569. if (useScreen === void 0) { useScreen = false; }
  12570. if (!useScreen && this._currentRenderTarget) {
  12571. return this._currentRenderTarget.height;
  12572. }
  12573. return this._gl.drawingBufferHeight;
  12574. };
  12575. /**
  12576. * Gets the HTML canvas attached with the current webGL context
  12577. * @returns a HTML canvas
  12578. */
  12579. Engine.prototype.getRenderingCanvas = function () {
  12580. return this._renderingCanvas;
  12581. };
  12582. /**
  12583. * Gets the client rect of the HTML canvas attached with the current webGL context
  12584. * @returns a client rectanglee
  12585. */
  12586. Engine.prototype.getRenderingCanvasClientRect = function () {
  12587. if (!this._renderingCanvas) {
  12588. return null;
  12589. }
  12590. return this._renderingCanvas.getBoundingClientRect();
  12591. };
  12592. /**
  12593. * Defines the hardware scaling level.
  12594. * By default the hardware scaling level is computed from the window device ratio.
  12595. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12596. * @param level defines the level to use
  12597. */
  12598. Engine.prototype.setHardwareScalingLevel = function (level) {
  12599. this._hardwareScalingLevel = level;
  12600. this.resize();
  12601. };
  12602. /**
  12603. * Gets the current hardware scaling level.
  12604. * By default the hardware scaling level is computed from the window device ratio.
  12605. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12606. * @returns a number indicating the current hardware scaling level
  12607. */
  12608. Engine.prototype.getHardwareScalingLevel = function () {
  12609. return this._hardwareScalingLevel;
  12610. };
  12611. /**
  12612. * Gets the list of loaded textures
  12613. * @returns an array containing all loaded textures
  12614. */
  12615. Engine.prototype.getLoadedTexturesCache = function () {
  12616. return this._internalTexturesCache;
  12617. };
  12618. /**
  12619. * Gets the object containing all engine capabilities
  12620. * @returns the EngineCapabilities object
  12621. */
  12622. Engine.prototype.getCaps = function () {
  12623. return this._caps;
  12624. };
  12625. Object.defineProperty(Engine.prototype, "drawCalls", {
  12626. /** @hidden */
  12627. get: function () {
  12628. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12629. return 0;
  12630. },
  12631. enumerable: true,
  12632. configurable: true
  12633. });
  12634. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12635. /** @hidden */
  12636. get: function () {
  12637. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12638. return null;
  12639. },
  12640. enumerable: true,
  12641. configurable: true
  12642. });
  12643. /**
  12644. * Gets the current depth function
  12645. * @returns a number defining the depth function
  12646. */
  12647. Engine.prototype.getDepthFunction = function () {
  12648. return this._depthCullingState.depthFunc;
  12649. };
  12650. /**
  12651. * Sets the current depth function
  12652. * @param depthFunc defines the function to use
  12653. */
  12654. Engine.prototype.setDepthFunction = function (depthFunc) {
  12655. this._depthCullingState.depthFunc = depthFunc;
  12656. };
  12657. /**
  12658. * Sets the current depth function to GREATER
  12659. */
  12660. Engine.prototype.setDepthFunctionToGreater = function () {
  12661. this._depthCullingState.depthFunc = this._gl.GREATER;
  12662. };
  12663. /**
  12664. * Sets the current depth function to GEQUAL
  12665. */
  12666. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12667. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12668. };
  12669. /**
  12670. * Sets the current depth function to LESS
  12671. */
  12672. Engine.prototype.setDepthFunctionToLess = function () {
  12673. this._depthCullingState.depthFunc = this._gl.LESS;
  12674. };
  12675. /**
  12676. * Sets the current depth function to LEQUAL
  12677. */
  12678. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12679. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12680. };
  12681. /**
  12682. * Gets a boolean indicating if stencil buffer is enabled
  12683. * @returns the current stencil buffer state
  12684. */
  12685. Engine.prototype.getStencilBuffer = function () {
  12686. return this._stencilState.stencilTest;
  12687. };
  12688. /**
  12689. * Enable or disable the stencil buffer
  12690. * @param enable defines if the stencil buffer must be enabled or disabled
  12691. */
  12692. Engine.prototype.setStencilBuffer = function (enable) {
  12693. this._stencilState.stencilTest = enable;
  12694. };
  12695. /**
  12696. * Gets the current stencil mask
  12697. * @returns a number defining the new stencil mask to use
  12698. */
  12699. Engine.prototype.getStencilMask = function () {
  12700. return this._stencilState.stencilMask;
  12701. };
  12702. /**
  12703. * Sets the current stencil mask
  12704. * @param mask defines the new stencil mask to use
  12705. */
  12706. Engine.prototype.setStencilMask = function (mask) {
  12707. this._stencilState.stencilMask = mask;
  12708. };
  12709. /**
  12710. * Gets the current stencil function
  12711. * @returns a number defining the stencil function to use
  12712. */
  12713. Engine.prototype.getStencilFunction = function () {
  12714. return this._stencilState.stencilFunc;
  12715. };
  12716. /**
  12717. * Gets the current stencil reference value
  12718. * @returns a number defining the stencil reference value to use
  12719. */
  12720. Engine.prototype.getStencilFunctionReference = function () {
  12721. return this._stencilState.stencilFuncRef;
  12722. };
  12723. /**
  12724. * Gets the current stencil mask
  12725. * @returns a number defining the stencil mask to use
  12726. */
  12727. Engine.prototype.getStencilFunctionMask = function () {
  12728. return this._stencilState.stencilFuncMask;
  12729. };
  12730. /**
  12731. * Sets the current stencil function
  12732. * @param stencilFunc defines the new stencil function to use
  12733. */
  12734. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12735. this._stencilState.stencilFunc = stencilFunc;
  12736. };
  12737. /**
  12738. * Sets the current stencil reference
  12739. * @param reference defines the new stencil reference to use
  12740. */
  12741. Engine.prototype.setStencilFunctionReference = function (reference) {
  12742. this._stencilState.stencilFuncRef = reference;
  12743. };
  12744. /**
  12745. * Sets the current stencil mask
  12746. * @param mask defines the new stencil mask to use
  12747. */
  12748. Engine.prototype.setStencilFunctionMask = function (mask) {
  12749. this._stencilState.stencilFuncMask = mask;
  12750. };
  12751. /**
  12752. * Gets the current stencil operation when stencil fails
  12753. * @returns a number defining stencil operation to use when stencil fails
  12754. */
  12755. Engine.prototype.getStencilOperationFail = function () {
  12756. return this._stencilState.stencilOpStencilFail;
  12757. };
  12758. /**
  12759. * Gets the current stencil operation when depth fails
  12760. * @returns a number defining stencil operation to use when depth fails
  12761. */
  12762. Engine.prototype.getStencilOperationDepthFail = function () {
  12763. return this._stencilState.stencilOpDepthFail;
  12764. };
  12765. /**
  12766. * Gets the current stencil operation when stencil passes
  12767. * @returns a number defining stencil operation to use when stencil passes
  12768. */
  12769. Engine.prototype.getStencilOperationPass = function () {
  12770. return this._stencilState.stencilOpStencilDepthPass;
  12771. };
  12772. /**
  12773. * Sets the stencil operation to use when stencil fails
  12774. * @param operation defines the stencil operation to use when stencil fails
  12775. */
  12776. Engine.prototype.setStencilOperationFail = function (operation) {
  12777. this._stencilState.stencilOpStencilFail = operation;
  12778. };
  12779. /**
  12780. * Sets the stencil operation to use when depth fails
  12781. * @param operation defines the stencil operation to use when depth fails
  12782. */
  12783. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12784. this._stencilState.stencilOpDepthFail = operation;
  12785. };
  12786. /**
  12787. * Sets the stencil operation to use when stencil passes
  12788. * @param operation defines the stencil operation to use when stencil passes
  12789. */
  12790. Engine.prototype.setStencilOperationPass = function (operation) {
  12791. this._stencilState.stencilOpStencilDepthPass = operation;
  12792. };
  12793. /**
  12794. * Sets a boolean indicating if the dithering state is enabled or disabled
  12795. * @param value defines the dithering state
  12796. */
  12797. Engine.prototype.setDitheringState = function (value) {
  12798. if (value) {
  12799. this._gl.enable(this._gl.DITHER);
  12800. }
  12801. else {
  12802. this._gl.disable(this._gl.DITHER);
  12803. }
  12804. };
  12805. /**
  12806. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12807. * @param value defines the rasterizer state
  12808. */
  12809. Engine.prototype.setRasterizerState = function (value) {
  12810. if (value) {
  12811. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12812. }
  12813. else {
  12814. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12815. }
  12816. };
  12817. /**
  12818. * stop executing a render loop function and remove it from the execution array
  12819. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12820. */
  12821. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12822. if (!renderFunction) {
  12823. this._activeRenderLoops = [];
  12824. return;
  12825. }
  12826. var index = this._activeRenderLoops.indexOf(renderFunction);
  12827. if (index >= 0) {
  12828. this._activeRenderLoops.splice(index, 1);
  12829. }
  12830. };
  12831. /** @hidden */
  12832. Engine.prototype._renderLoop = function () {
  12833. if (!this._contextWasLost) {
  12834. var shouldRender = true;
  12835. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12836. shouldRender = false;
  12837. }
  12838. if (shouldRender) {
  12839. // Start new frame
  12840. this.beginFrame();
  12841. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12842. var renderFunction = this._activeRenderLoops[index];
  12843. renderFunction();
  12844. }
  12845. // Present
  12846. this.endFrame();
  12847. }
  12848. }
  12849. if (this._activeRenderLoops.length > 0) {
  12850. // Register new frame
  12851. var requester = null;
  12852. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12853. requester = this._vrDisplay;
  12854. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12855. }
  12856. else {
  12857. this._renderingQueueLaunched = false;
  12858. }
  12859. };
  12860. /**
  12861. * Register and execute a render loop. The engine can have more than one render function
  12862. * @param renderFunction defines the function to continuously execute
  12863. */
  12864. Engine.prototype.runRenderLoop = function (renderFunction) {
  12865. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12866. return;
  12867. }
  12868. this._activeRenderLoops.push(renderFunction);
  12869. if (!this._renderingQueueLaunched) {
  12870. this._renderingQueueLaunched = true;
  12871. this._bindedRenderFunction = this._renderLoop.bind(this);
  12872. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12873. }
  12874. };
  12875. /**
  12876. * Toggle full screen mode
  12877. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12878. * @param options defines an option object to be sent to the requestFullscreen function
  12879. */
  12880. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12881. if (this.isFullscreen) {
  12882. BABYLON.Tools.ExitFullscreen();
  12883. }
  12884. else {
  12885. this._pointerLockRequested = requestPointerLock;
  12886. if (this._renderingCanvas) {
  12887. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12888. }
  12889. }
  12890. };
  12891. /**
  12892. * Clear the current render buffer or the current render target (if any is set up)
  12893. * @param color defines the color to use
  12894. * @param backBuffer defines if the back buffer must be cleared
  12895. * @param depth defines if the depth buffer must be cleared
  12896. * @param stencil defines if the stencil buffer must be cleared
  12897. */
  12898. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12899. if (stencil === void 0) { stencil = false; }
  12900. this.applyStates();
  12901. var mode = 0;
  12902. if (backBuffer && color) {
  12903. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12904. mode |= this._gl.COLOR_BUFFER_BIT;
  12905. }
  12906. if (depth) {
  12907. this._gl.clearDepth(1.0);
  12908. mode |= this._gl.DEPTH_BUFFER_BIT;
  12909. }
  12910. if (stencil) {
  12911. this._gl.clearStencil(0);
  12912. mode |= this._gl.STENCIL_BUFFER_BIT;
  12913. }
  12914. this._gl.clear(mode);
  12915. };
  12916. /**
  12917. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12918. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12919. * @param y defines the y-coordinate of the corner of the clear rectangle
  12920. * @param width defines the width of the clear rectangle
  12921. * @param height defines the height of the clear rectangle
  12922. * @param clearColor defines the clear color
  12923. */
  12924. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12925. var gl = this._gl;
  12926. // Save state
  12927. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12928. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12929. // Change state
  12930. gl.enable(gl.SCISSOR_TEST);
  12931. gl.scissor(x, y, width, height);
  12932. // Clear
  12933. this.clear(clearColor, true, true, true);
  12934. // Restore state
  12935. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12936. if (curScissor === true) {
  12937. gl.enable(gl.SCISSOR_TEST);
  12938. }
  12939. else {
  12940. gl.disable(gl.SCISSOR_TEST);
  12941. }
  12942. };
  12943. /** @hidden */
  12944. Engine.prototype._viewport = function (x, y, width, height) {
  12945. if (x !== this._viewportCached.x ||
  12946. y !== this._viewportCached.y ||
  12947. width !== this._viewportCached.z ||
  12948. height !== this._viewportCached.w) {
  12949. this._viewportCached.x = x;
  12950. this._viewportCached.y = y;
  12951. this._viewportCached.z = width;
  12952. this._viewportCached.w = height;
  12953. this._gl.viewport(x, y, width, height);
  12954. }
  12955. };
  12956. /**
  12957. * Set the WebGL's viewport
  12958. * @param viewport defines the viewport element to be used
  12959. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12960. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12961. */
  12962. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12963. var width = requiredWidth || this.getRenderWidth();
  12964. var height = requiredHeight || this.getRenderHeight();
  12965. var x = viewport.x || 0;
  12966. var y = viewport.y || 0;
  12967. this._cachedViewport = viewport;
  12968. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12969. };
  12970. /**
  12971. * Directly set the WebGL Viewport
  12972. * @param x defines the x coordinate of the viewport (in screen space)
  12973. * @param y defines the y coordinate of the viewport (in screen space)
  12974. * @param width defines the width of the viewport (in screen space)
  12975. * @param height defines the height of the viewport (in screen space)
  12976. * @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
  12977. */
  12978. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12979. var currentViewport = this._cachedViewport;
  12980. this._cachedViewport = null;
  12981. this._viewport(x, y, width, height);
  12982. return currentViewport;
  12983. };
  12984. /**
  12985. * Begin a new frame
  12986. */
  12987. Engine.prototype.beginFrame = function () {
  12988. this.onBeginFrameObservable.notifyObservers(this);
  12989. this._measureFps();
  12990. };
  12991. /**
  12992. * Enf the current frame
  12993. */
  12994. Engine.prototype.endFrame = function () {
  12995. // Force a flush in case we are using a bad OS.
  12996. if (this._badOS) {
  12997. this.flushFramebuffer();
  12998. }
  12999. // Submit frame to the vr device, if enabled
  13000. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13001. // TODO: We should only submit the frame if we read frameData successfully.
  13002. this._vrDisplay.submitFrame();
  13003. }
  13004. this.onEndFrameObservable.notifyObservers(this);
  13005. };
  13006. /**
  13007. * Resize the view according to the canvas' size
  13008. */
  13009. Engine.prototype.resize = function () {
  13010. // We're not resizing the size of the canvas while in VR mode & presenting
  13011. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13012. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13013. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13014. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13015. }
  13016. };
  13017. /**
  13018. * Force a specific size of the canvas
  13019. * @param width defines the new canvas' width
  13020. * @param height defines the new canvas' height
  13021. */
  13022. Engine.prototype.setSize = function (width, height) {
  13023. if (!this._renderingCanvas) {
  13024. return;
  13025. }
  13026. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13027. return;
  13028. }
  13029. this._renderingCanvas.width = width;
  13030. this._renderingCanvas.height = height;
  13031. for (var index = 0; index < this.scenes.length; index++) {
  13032. var scene = this.scenes[index];
  13033. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13034. var cam = scene.cameras[camIndex];
  13035. cam._currentRenderId = 0;
  13036. }
  13037. }
  13038. if (this.onResizeObservable.hasObservers) {
  13039. this.onResizeObservable.notifyObservers(this);
  13040. }
  13041. };
  13042. // WebVR functions
  13043. /**
  13044. * Gets a boolean indicating if a webVR device was detected
  13045. * @returns true if a webVR device was detected
  13046. */
  13047. Engine.prototype.isVRDevicePresent = function () {
  13048. return !!this._vrDisplay;
  13049. };
  13050. /**
  13051. * Gets the current webVR device
  13052. * @returns the current webVR device (or null)
  13053. */
  13054. Engine.prototype.getVRDevice = function () {
  13055. return this._vrDisplay;
  13056. };
  13057. /**
  13058. * Initializes a webVR display and starts listening to display change events
  13059. * The onVRDisplayChangedObservable will be notified upon these changes
  13060. * @returns The onVRDisplayChangedObservable
  13061. */
  13062. Engine.prototype.initWebVR = function () {
  13063. this.initWebVRAsync();
  13064. return this.onVRDisplayChangedObservable;
  13065. };
  13066. /**
  13067. * Initializes a webVR display and starts listening to display change events
  13068. * The onVRDisplayChangedObservable will be notified upon these changes
  13069. * @returns A promise containing a VRDisplay and if vr is supported
  13070. */
  13071. Engine.prototype.initWebVRAsync = function () {
  13072. var _this = this;
  13073. var notifyObservers = function () {
  13074. var eventArgs = {
  13075. vrDisplay: _this._vrDisplay,
  13076. vrSupported: _this._vrSupported
  13077. };
  13078. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13079. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13080. };
  13081. if (!this._onVrDisplayConnect) {
  13082. this._onVrDisplayConnect = function (event) {
  13083. _this._vrDisplay = event.display;
  13084. notifyObservers();
  13085. };
  13086. this._onVrDisplayDisconnect = function () {
  13087. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13088. _this._vrDisplay = undefined;
  13089. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13090. notifyObservers();
  13091. };
  13092. this._onVrDisplayPresentChange = function () {
  13093. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13094. };
  13095. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13096. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13097. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13098. }
  13099. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13100. this._webVRInitPromise.then(notifyObservers);
  13101. return this._webVRInitPromise;
  13102. };
  13103. /**
  13104. * Call this function to switch to webVR mode
  13105. * Will do nothing if webVR is not supported or if there is no webVR device
  13106. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13107. */
  13108. Engine.prototype.enableVR = function () {
  13109. var _this = this;
  13110. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13111. var onResolved = function () {
  13112. _this.onVRRequestPresentComplete.notifyObservers(true);
  13113. _this._onVRFullScreenTriggered();
  13114. };
  13115. var onRejected = function () {
  13116. _this.onVRRequestPresentComplete.notifyObservers(false);
  13117. };
  13118. this.onVRRequestPresentStart.notifyObservers(this);
  13119. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13120. }
  13121. };
  13122. /**
  13123. * Call this function to leave webVR mode
  13124. * Will do nothing if webVR is not supported or if there is no webVR device
  13125. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13126. */
  13127. Engine.prototype.disableVR = function () {
  13128. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13129. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13130. }
  13131. };
  13132. Engine.prototype._getVRDisplaysAsync = function () {
  13133. var _this = this;
  13134. return new Promise(function (res, rej) {
  13135. if (navigator.getVRDisplays) {
  13136. navigator.getVRDisplays().then(function (devices) {
  13137. _this._vrSupported = true;
  13138. // note that devices may actually be an empty array. This is fine;
  13139. // we expect this._vrDisplay to be undefined in this case.
  13140. _this._vrDisplay = devices[0];
  13141. res({
  13142. vrDisplay: _this._vrDisplay,
  13143. vrSupported: _this._vrSupported
  13144. });
  13145. });
  13146. }
  13147. else {
  13148. _this._vrDisplay = undefined;
  13149. _this._vrSupported = false;
  13150. res({
  13151. vrDisplay: _this._vrDisplay,
  13152. vrSupported: _this._vrSupported
  13153. });
  13154. }
  13155. });
  13156. };
  13157. /**
  13158. * Binds the frame buffer to the specified texture.
  13159. * @param texture The texture to render to or null for the default canvas
  13160. * @param faceIndex The face of the texture to render to in case of cube texture
  13161. * @param requiredWidth The width of the target to render to
  13162. * @param requiredHeight The height of the target to render to
  13163. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13164. * @param depthStencilTexture The depth stencil texture to use to render
  13165. * @param lodLevel defines le lod level to bind to the frame buffer
  13166. */
  13167. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13168. if (lodLevel === void 0) { lodLevel = 0; }
  13169. if (this._currentRenderTarget) {
  13170. this.unBindFramebuffer(this._currentRenderTarget);
  13171. }
  13172. this._currentRenderTarget = texture;
  13173. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13174. var gl = this._gl;
  13175. if (texture.isCube) {
  13176. if (faceIndex === undefined) {
  13177. faceIndex = 0;
  13178. }
  13179. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13180. if (depthStencilTexture) {
  13181. if (depthStencilTexture._generateStencilBuffer) {
  13182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13183. }
  13184. else {
  13185. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13186. }
  13187. }
  13188. }
  13189. if (this._cachedViewport && !forceFullscreenViewport) {
  13190. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13191. }
  13192. else {
  13193. if (!requiredWidth) {
  13194. requiredWidth = texture.width;
  13195. if (lodLevel) {
  13196. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13197. }
  13198. }
  13199. if (!requiredHeight) {
  13200. requiredHeight = texture.height;
  13201. if (lodLevel) {
  13202. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13203. }
  13204. }
  13205. this._viewport(0, 0, requiredWidth, requiredHeight);
  13206. }
  13207. this.wipeCaches();
  13208. };
  13209. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13210. if (this._currentFramebuffer !== framebuffer) {
  13211. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13212. this._currentFramebuffer = framebuffer;
  13213. }
  13214. };
  13215. /**
  13216. * Unbind the current render target texture from the webGL context
  13217. * @param texture defines the render target texture to unbind
  13218. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13219. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13220. */
  13221. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13222. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13223. this._currentRenderTarget = null;
  13224. // If MSAA, we need to bitblt back to main texture
  13225. var gl = this._gl;
  13226. if (texture._MSAAFramebuffer) {
  13227. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13228. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13229. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13230. }
  13231. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13232. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13233. gl.generateMipmap(gl.TEXTURE_2D);
  13234. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13235. }
  13236. if (onBeforeUnbind) {
  13237. if (texture._MSAAFramebuffer) {
  13238. // Bind the correct framebuffer
  13239. this.bindUnboundFramebuffer(texture._framebuffer);
  13240. }
  13241. onBeforeUnbind();
  13242. }
  13243. this.bindUnboundFramebuffer(null);
  13244. };
  13245. /**
  13246. * Unbind a list of render target textures from the webGL context
  13247. * This is used only when drawBuffer extension or webGL2 are active
  13248. * @param textures defines the render target textures to unbind
  13249. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13250. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13251. */
  13252. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13253. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13254. this._currentRenderTarget = null;
  13255. // If MSAA, we need to bitblt back to main texture
  13256. var gl = this._gl;
  13257. if (textures[0]._MSAAFramebuffer) {
  13258. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13259. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13260. var attachments = textures[0]._attachments;
  13261. if (!attachments) {
  13262. attachments = new Array(textures.length);
  13263. textures[0]._attachments = attachments;
  13264. }
  13265. for (var i = 0; i < textures.length; i++) {
  13266. var texture = textures[i];
  13267. for (var j = 0; j < attachments.length; j++) {
  13268. attachments[j] = gl.NONE;
  13269. }
  13270. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13271. gl.readBuffer(attachments[i]);
  13272. gl.drawBuffers(attachments);
  13273. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13274. }
  13275. for (var i = 0; i < attachments.length; i++) {
  13276. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13277. }
  13278. gl.drawBuffers(attachments);
  13279. }
  13280. for (var i = 0; i < textures.length; i++) {
  13281. var texture = textures[i];
  13282. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13283. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13284. gl.generateMipmap(gl.TEXTURE_2D);
  13285. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13286. }
  13287. }
  13288. if (onBeforeUnbind) {
  13289. if (textures[0]._MSAAFramebuffer) {
  13290. // Bind the correct framebuffer
  13291. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13292. }
  13293. onBeforeUnbind();
  13294. }
  13295. this.bindUnboundFramebuffer(null);
  13296. };
  13297. /**
  13298. * Force the mipmap generation for the given render target texture
  13299. * @param texture defines the render target texture to use
  13300. */
  13301. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13302. if (texture.generateMipMaps) {
  13303. var gl = this._gl;
  13304. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13305. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13306. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13307. }
  13308. };
  13309. /**
  13310. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13311. */
  13312. Engine.prototype.flushFramebuffer = function () {
  13313. this._gl.flush();
  13314. };
  13315. /**
  13316. * Unbind the current render target and bind the default framebuffer
  13317. */
  13318. Engine.prototype.restoreDefaultFramebuffer = function () {
  13319. if (this._currentRenderTarget) {
  13320. this.unBindFramebuffer(this._currentRenderTarget);
  13321. }
  13322. else {
  13323. this.bindUnboundFramebuffer(null);
  13324. }
  13325. if (this._cachedViewport) {
  13326. this.setViewport(this._cachedViewport);
  13327. }
  13328. this.wipeCaches();
  13329. };
  13330. // UBOs
  13331. /**
  13332. * Create an uniform buffer
  13333. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13334. * @param elements defines the content of the uniform buffer
  13335. * @returns the webGL uniform buffer
  13336. */
  13337. Engine.prototype.createUniformBuffer = function (elements) {
  13338. var ubo = this._gl.createBuffer();
  13339. if (!ubo) {
  13340. throw new Error("Unable to create uniform buffer");
  13341. }
  13342. this.bindUniformBuffer(ubo);
  13343. if (elements instanceof Float32Array) {
  13344. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13345. }
  13346. else {
  13347. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13348. }
  13349. this.bindUniformBuffer(null);
  13350. ubo.references = 1;
  13351. return ubo;
  13352. };
  13353. /**
  13354. * Create a dynamic uniform buffer
  13355. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13356. * @param elements defines the content of the uniform buffer
  13357. * @returns the webGL uniform buffer
  13358. */
  13359. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13360. var ubo = this._gl.createBuffer();
  13361. if (!ubo) {
  13362. throw new Error("Unable to create dynamic uniform buffer");
  13363. }
  13364. this.bindUniformBuffer(ubo);
  13365. if (elements instanceof Float32Array) {
  13366. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13367. }
  13368. else {
  13369. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13370. }
  13371. this.bindUniformBuffer(null);
  13372. ubo.references = 1;
  13373. return ubo;
  13374. };
  13375. /**
  13376. * Update an existing uniform buffer
  13377. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13378. * @param uniformBuffer defines the target uniform buffer
  13379. * @param elements defines the content to update
  13380. * @param offset defines the offset in the uniform buffer where update should start
  13381. * @param count defines the size of the data to update
  13382. */
  13383. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13384. this.bindUniformBuffer(uniformBuffer);
  13385. if (offset === undefined) {
  13386. offset = 0;
  13387. }
  13388. if (count === undefined) {
  13389. if (elements instanceof Float32Array) {
  13390. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13391. }
  13392. else {
  13393. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13394. }
  13395. }
  13396. else {
  13397. if (elements instanceof Float32Array) {
  13398. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13399. }
  13400. else {
  13401. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13402. }
  13403. }
  13404. this.bindUniformBuffer(null);
  13405. };
  13406. // VBOs
  13407. Engine.prototype._resetVertexBufferBinding = function () {
  13408. this.bindArrayBuffer(null);
  13409. this._cachedVertexBuffers = null;
  13410. };
  13411. /**
  13412. * Creates a vertex buffer
  13413. * @param data the data for the vertex buffer
  13414. * @returns the new WebGL static buffer
  13415. */
  13416. Engine.prototype.createVertexBuffer = function (data) {
  13417. var vbo = this._gl.createBuffer();
  13418. if (!vbo) {
  13419. throw new Error("Unable to create vertex buffer");
  13420. }
  13421. this.bindArrayBuffer(vbo);
  13422. if (data instanceof Array) {
  13423. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13424. }
  13425. else {
  13426. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13427. }
  13428. this._resetVertexBufferBinding();
  13429. vbo.references = 1;
  13430. return vbo;
  13431. };
  13432. /**
  13433. * Creates a dynamic vertex buffer
  13434. * @param data the data for the dynamic vertex buffer
  13435. * @returns the new WebGL dynamic buffer
  13436. */
  13437. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13438. var vbo = this._gl.createBuffer();
  13439. if (!vbo) {
  13440. throw new Error("Unable to create dynamic vertex buffer");
  13441. }
  13442. this.bindArrayBuffer(vbo);
  13443. if (data instanceof Array) {
  13444. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13445. }
  13446. else {
  13447. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13448. }
  13449. this._resetVertexBufferBinding();
  13450. vbo.references = 1;
  13451. return vbo;
  13452. };
  13453. /**
  13454. * Update a dynamic index buffer
  13455. * @param indexBuffer defines the target index buffer
  13456. * @param indices defines the data to update
  13457. * @param offset defines the offset in the target index buffer where update should start
  13458. */
  13459. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13460. if (offset === void 0) { offset = 0; }
  13461. // Force cache update
  13462. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13463. this.bindIndexBuffer(indexBuffer);
  13464. var arrayBuffer;
  13465. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13466. arrayBuffer = indices;
  13467. }
  13468. else {
  13469. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13470. }
  13471. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13472. this._resetIndexBufferBinding();
  13473. };
  13474. /**
  13475. * Updates a dynamic vertex buffer.
  13476. * @param vertexBuffer the vertex buffer to update
  13477. * @param data the data used to update the vertex buffer
  13478. * @param byteOffset the byte offset of the data
  13479. * @param byteLength the byte length of the data
  13480. */
  13481. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13482. this.bindArrayBuffer(vertexBuffer);
  13483. if (byteOffset === undefined) {
  13484. byteOffset = 0;
  13485. }
  13486. if (byteLength === undefined) {
  13487. if (data instanceof Array) {
  13488. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13489. }
  13490. else {
  13491. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13492. }
  13493. }
  13494. else {
  13495. if (data instanceof Array) {
  13496. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13497. }
  13498. else {
  13499. if (data instanceof ArrayBuffer) {
  13500. data = new Uint8Array(data, byteOffset, byteLength);
  13501. }
  13502. else {
  13503. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13504. }
  13505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13506. }
  13507. }
  13508. this._resetVertexBufferBinding();
  13509. };
  13510. Engine.prototype._resetIndexBufferBinding = function () {
  13511. this.bindIndexBuffer(null);
  13512. this._cachedIndexBuffer = null;
  13513. };
  13514. /**
  13515. * Creates a new index buffer
  13516. * @param indices defines the content of the index buffer
  13517. * @param updatable defines if the index buffer must be updatable
  13518. * @returns a new webGL buffer
  13519. */
  13520. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13521. var vbo = this._gl.createBuffer();
  13522. if (!vbo) {
  13523. throw new Error("Unable to create index buffer");
  13524. }
  13525. this.bindIndexBuffer(vbo);
  13526. // Check for 32 bits indices
  13527. var arrayBuffer;
  13528. var need32Bits = false;
  13529. if (indices instanceof Uint16Array) {
  13530. arrayBuffer = indices;
  13531. }
  13532. else {
  13533. //check 32 bit support
  13534. if (this._caps.uintIndices) {
  13535. if (indices instanceof Uint32Array) {
  13536. arrayBuffer = indices;
  13537. need32Bits = true;
  13538. }
  13539. else {
  13540. //number[] or Int32Array, check if 32 bit is necessary
  13541. for (var index = 0; index < indices.length; index++) {
  13542. if (indices[index] > 65535) {
  13543. need32Bits = true;
  13544. break;
  13545. }
  13546. }
  13547. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13548. }
  13549. }
  13550. else {
  13551. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13552. arrayBuffer = new Uint16Array(indices);
  13553. }
  13554. }
  13555. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13556. this._resetIndexBufferBinding();
  13557. vbo.references = 1;
  13558. vbo.is32Bits = need32Bits;
  13559. return vbo;
  13560. };
  13561. /**
  13562. * Bind a webGL buffer to the webGL context
  13563. * @param buffer defines the buffer to bind
  13564. */
  13565. Engine.prototype.bindArrayBuffer = function (buffer) {
  13566. if (!this._vaoRecordInProgress) {
  13567. this._unbindVertexArrayObject();
  13568. }
  13569. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13570. };
  13571. /**
  13572. * Bind an uniform buffer to the current webGL context
  13573. * @param buffer defines the buffer to bind
  13574. */
  13575. Engine.prototype.bindUniformBuffer = function (buffer) {
  13576. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13577. };
  13578. /**
  13579. * Bind a buffer to the current webGL context at a given location
  13580. * @param buffer defines the buffer to bind
  13581. * @param location defines the index where to bind the buffer
  13582. */
  13583. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13584. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13585. };
  13586. /**
  13587. * Bind a specific block at a given index in a specific shader program
  13588. * @param shaderProgram defines the shader program
  13589. * @param blockName defines the block name
  13590. * @param index defines the index where to bind the block
  13591. */
  13592. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13593. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13594. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13595. };
  13596. ;
  13597. Engine.prototype.bindIndexBuffer = function (buffer) {
  13598. if (!this._vaoRecordInProgress) {
  13599. this._unbindVertexArrayObject();
  13600. }
  13601. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13602. };
  13603. Engine.prototype.bindBuffer = function (buffer, target) {
  13604. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13605. this._gl.bindBuffer(target, buffer);
  13606. this._currentBoundBuffer[target] = buffer;
  13607. }
  13608. };
  13609. /**
  13610. * update the bound buffer with the given data
  13611. * @param data defines the data to update
  13612. */
  13613. Engine.prototype.updateArrayBuffer = function (data) {
  13614. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13615. };
  13616. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13617. var pointer = this._currentBufferPointers[indx];
  13618. var changed = false;
  13619. if (!pointer.active) {
  13620. changed = true;
  13621. pointer.active = true;
  13622. pointer.index = indx;
  13623. pointer.size = size;
  13624. pointer.type = type;
  13625. pointer.normalized = normalized;
  13626. pointer.stride = stride;
  13627. pointer.offset = offset;
  13628. pointer.buffer = buffer;
  13629. }
  13630. else {
  13631. if (pointer.buffer !== buffer) {
  13632. pointer.buffer = buffer;
  13633. changed = true;
  13634. }
  13635. if (pointer.size !== size) {
  13636. pointer.size = size;
  13637. changed = true;
  13638. }
  13639. if (pointer.type !== type) {
  13640. pointer.type = type;
  13641. changed = true;
  13642. }
  13643. if (pointer.normalized !== normalized) {
  13644. pointer.normalized = normalized;
  13645. changed = true;
  13646. }
  13647. if (pointer.stride !== stride) {
  13648. pointer.stride = stride;
  13649. changed = true;
  13650. }
  13651. if (pointer.offset !== offset) {
  13652. pointer.offset = offset;
  13653. changed = true;
  13654. }
  13655. }
  13656. if (changed || this._vaoRecordInProgress) {
  13657. this.bindArrayBuffer(buffer);
  13658. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13659. }
  13660. };
  13661. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13662. if (indexBuffer == null) {
  13663. return;
  13664. }
  13665. if (this._cachedIndexBuffer !== indexBuffer) {
  13666. this._cachedIndexBuffer = indexBuffer;
  13667. this.bindIndexBuffer(indexBuffer);
  13668. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13669. }
  13670. };
  13671. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13672. var attributes = effect.getAttributesNames();
  13673. if (!this._vaoRecordInProgress) {
  13674. this._unbindVertexArrayObject();
  13675. }
  13676. this.unbindAllAttributes();
  13677. for (var index = 0; index < attributes.length; index++) {
  13678. var order = effect.getAttributeLocation(index);
  13679. if (order >= 0) {
  13680. var vertexBuffer = vertexBuffers[attributes[index]];
  13681. if (!vertexBuffer) {
  13682. continue;
  13683. }
  13684. this._gl.enableVertexAttribArray(order);
  13685. if (!this._vaoRecordInProgress) {
  13686. this._vertexAttribArraysEnabled[order] = true;
  13687. }
  13688. var buffer = vertexBuffer.getBuffer();
  13689. if (buffer) {
  13690. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13691. if (vertexBuffer.getIsInstanced()) {
  13692. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13693. if (!this._vaoRecordInProgress) {
  13694. this._currentInstanceLocations.push(order);
  13695. this._currentInstanceBuffers.push(buffer);
  13696. }
  13697. }
  13698. }
  13699. }
  13700. }
  13701. };
  13702. /**
  13703. * Records a vertex array object
  13704. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13705. * @param vertexBuffers defines the list of vertex buffers to store
  13706. * @param indexBuffer defines the index buffer to store
  13707. * @param effect defines the effect to store
  13708. * @returns the new vertex array object
  13709. */
  13710. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13711. var vao = this._gl.createVertexArray();
  13712. this._vaoRecordInProgress = true;
  13713. this._gl.bindVertexArray(vao);
  13714. this._mustWipeVertexAttributes = true;
  13715. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13716. this.bindIndexBuffer(indexBuffer);
  13717. this._vaoRecordInProgress = false;
  13718. this._gl.bindVertexArray(null);
  13719. return vao;
  13720. };
  13721. /**
  13722. * Bind a specific vertex array object
  13723. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13724. * @param vertexArrayObject defines the vertex array object to bind
  13725. * @param indexBuffer defines the index buffer to bind
  13726. */
  13727. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13728. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13729. this._cachedVertexArrayObject = vertexArrayObject;
  13730. this._gl.bindVertexArray(vertexArrayObject);
  13731. this._cachedVertexBuffers = null;
  13732. this._cachedIndexBuffer = null;
  13733. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13734. this._mustWipeVertexAttributes = true;
  13735. }
  13736. };
  13737. /**
  13738. * Bind webGl buffers directly to the webGL context
  13739. * @param vertexBuffer defines the vertex buffer to bind
  13740. * @param indexBuffer defines the index buffer to bind
  13741. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13742. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13743. * @param effect defines the effect associated with the vertex buffer
  13744. */
  13745. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13746. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13747. this._cachedVertexBuffers = vertexBuffer;
  13748. this._cachedEffectForVertexBuffers = effect;
  13749. var attributesCount = effect.getAttributesCount();
  13750. this._unbindVertexArrayObject();
  13751. this.unbindAllAttributes();
  13752. var offset = 0;
  13753. for (var index = 0; index < attributesCount; index++) {
  13754. if (index < vertexDeclaration.length) {
  13755. var order = effect.getAttributeLocation(index);
  13756. if (order >= 0) {
  13757. this._gl.enableVertexAttribArray(order);
  13758. this._vertexAttribArraysEnabled[order] = true;
  13759. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13760. }
  13761. offset += vertexDeclaration[index] * 4;
  13762. }
  13763. }
  13764. }
  13765. this._bindIndexBufferWithCache(indexBuffer);
  13766. };
  13767. Engine.prototype._unbindVertexArrayObject = function () {
  13768. if (!this._cachedVertexArrayObject) {
  13769. return;
  13770. }
  13771. this._cachedVertexArrayObject = null;
  13772. this._gl.bindVertexArray(null);
  13773. };
  13774. /**
  13775. * Bind a list of vertex buffers to the webGL context
  13776. * @param vertexBuffers defines the list of vertex buffers to bind
  13777. * @param indexBuffer defines the index buffer to bind
  13778. * @param effect defines the effect associated with the vertex buffers
  13779. */
  13780. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13781. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13782. this._cachedVertexBuffers = vertexBuffers;
  13783. this._cachedEffectForVertexBuffers = effect;
  13784. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13785. }
  13786. this._bindIndexBufferWithCache(indexBuffer);
  13787. };
  13788. /**
  13789. * Unbind all instance attributes
  13790. */
  13791. Engine.prototype.unbindInstanceAttributes = function () {
  13792. var boundBuffer;
  13793. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13794. var instancesBuffer = this._currentInstanceBuffers[i];
  13795. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13796. boundBuffer = instancesBuffer;
  13797. this.bindArrayBuffer(instancesBuffer);
  13798. }
  13799. var offsetLocation = this._currentInstanceLocations[i];
  13800. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13801. }
  13802. this._currentInstanceBuffers.length = 0;
  13803. this._currentInstanceLocations.length = 0;
  13804. };
  13805. /**
  13806. * Release and free the memory of a vertex array object
  13807. * @param vao defines the vertex array object to delete
  13808. */
  13809. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13810. this._gl.deleteVertexArray(vao);
  13811. };
  13812. /** @hidden */
  13813. Engine.prototype._releaseBuffer = function (buffer) {
  13814. buffer.references--;
  13815. if (buffer.references === 0) {
  13816. this._gl.deleteBuffer(buffer);
  13817. return true;
  13818. }
  13819. return false;
  13820. };
  13821. /**
  13822. * Creates a webGL buffer to use with instanciation
  13823. * @param capacity defines the size of the buffer
  13824. * @returns the webGL buffer
  13825. */
  13826. Engine.prototype.createInstancesBuffer = function (capacity) {
  13827. var buffer = this._gl.createBuffer();
  13828. if (!buffer) {
  13829. throw new Error("Unable to create instance buffer");
  13830. }
  13831. buffer.capacity = capacity;
  13832. this.bindArrayBuffer(buffer);
  13833. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13834. return buffer;
  13835. };
  13836. /**
  13837. * Delete a webGL buffer used with instanciation
  13838. * @param buffer defines the webGL buffer to delete
  13839. */
  13840. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13841. this._gl.deleteBuffer(buffer);
  13842. };
  13843. /**
  13844. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13845. * @param instancesBuffer defines the webGL buffer to update and bind
  13846. * @param data defines the data to store in the buffer
  13847. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13848. */
  13849. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13850. this.bindArrayBuffer(instancesBuffer);
  13851. if (data) {
  13852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13853. }
  13854. if (offsetLocations[0].index !== undefined) {
  13855. var stride = 0;
  13856. for (var i = 0; i < offsetLocations.length; i++) {
  13857. var ai = offsetLocations[i];
  13858. stride += ai.attributeSize * 4;
  13859. }
  13860. for (var i = 0; i < offsetLocations.length; i++) {
  13861. var ai = offsetLocations[i];
  13862. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13863. this._gl.enableVertexAttribArray(ai.index);
  13864. this._vertexAttribArraysEnabled[ai.index] = true;
  13865. }
  13866. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13867. this._gl.vertexAttribDivisor(ai.index, 1);
  13868. this._currentInstanceLocations.push(ai.index);
  13869. this._currentInstanceBuffers.push(instancesBuffer);
  13870. }
  13871. }
  13872. else {
  13873. for (var index = 0; index < 4; index++) {
  13874. var offsetLocation = offsetLocations[index];
  13875. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13876. this._gl.enableVertexAttribArray(offsetLocation);
  13877. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13878. }
  13879. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13880. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13881. this._currentInstanceLocations.push(offsetLocation);
  13882. this._currentInstanceBuffers.push(instancesBuffer);
  13883. }
  13884. }
  13885. };
  13886. /**
  13887. * Apply all cached states (depth, culling, stencil and alpha)
  13888. */
  13889. Engine.prototype.applyStates = function () {
  13890. this._depthCullingState.apply(this._gl);
  13891. this._stencilState.apply(this._gl);
  13892. this._alphaState.apply(this._gl);
  13893. };
  13894. /**
  13895. * Send a draw order
  13896. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13897. * @param indexStart defines the starting index
  13898. * @param indexCount defines the number of index to draw
  13899. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13900. */
  13901. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13902. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13903. };
  13904. /**
  13905. * Draw a list of points
  13906. * @param verticesStart defines the index of first vertex to draw
  13907. * @param verticesCount defines the count of vertices to draw
  13908. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13909. */
  13910. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13911. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13912. };
  13913. /**
  13914. * Draw a list of unindexed primitives
  13915. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13916. * @param verticesStart defines the index of first vertex to draw
  13917. * @param verticesCount defines the count of vertices to draw
  13918. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13919. */
  13920. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13921. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13922. };
  13923. /**
  13924. * Draw a list of indexed primitives
  13925. * @param fillMode defines the primitive to use
  13926. * @param indexStart defines the starting index
  13927. * @param indexCount defines the number of index to draw
  13928. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13929. */
  13930. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13931. // Apply states
  13932. this.applyStates();
  13933. this._drawCalls.addCount(1, false);
  13934. // Render
  13935. var drawMode = this._drawMode(fillMode);
  13936. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13937. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13938. if (instancesCount) {
  13939. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13940. }
  13941. else {
  13942. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13943. }
  13944. };
  13945. /**
  13946. * Draw a list of unindexed primitives
  13947. * @param fillMode defines the primitive to use
  13948. * @param verticesStart defines the index of first vertex to draw
  13949. * @param verticesCount defines the count of vertices to draw
  13950. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13951. */
  13952. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13953. // Apply states
  13954. this.applyStates();
  13955. this._drawCalls.addCount(1, false);
  13956. var drawMode = this._drawMode(fillMode);
  13957. if (instancesCount) {
  13958. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13959. }
  13960. else {
  13961. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13962. }
  13963. };
  13964. Engine.prototype._drawMode = function (fillMode) {
  13965. switch (fillMode) {
  13966. // Triangle views
  13967. case BABYLON.Material.TriangleFillMode:
  13968. return this._gl.TRIANGLES;
  13969. case BABYLON.Material.PointFillMode:
  13970. return this._gl.POINTS;
  13971. case BABYLON.Material.WireFrameFillMode:
  13972. return this._gl.LINES;
  13973. // Draw modes
  13974. case BABYLON.Material.PointListDrawMode:
  13975. return this._gl.POINTS;
  13976. case BABYLON.Material.LineListDrawMode:
  13977. return this._gl.LINES;
  13978. case BABYLON.Material.LineLoopDrawMode:
  13979. return this._gl.LINE_LOOP;
  13980. case BABYLON.Material.LineStripDrawMode:
  13981. return this._gl.LINE_STRIP;
  13982. case BABYLON.Material.TriangleStripDrawMode:
  13983. return this._gl.TRIANGLE_STRIP;
  13984. case BABYLON.Material.TriangleFanDrawMode:
  13985. return this._gl.TRIANGLE_FAN;
  13986. default:
  13987. return this._gl.TRIANGLES;
  13988. }
  13989. };
  13990. // Shaders
  13991. /** @hidden */
  13992. Engine.prototype._releaseEffect = function (effect) {
  13993. if (this._compiledEffects[effect._key]) {
  13994. delete this._compiledEffects[effect._key];
  13995. this._deleteProgram(effect.getProgram());
  13996. }
  13997. };
  13998. /** @hidden */
  13999. Engine.prototype._deleteProgram = function (program) {
  14000. if (program) {
  14001. program.__SPECTOR_rebuildProgram = null;
  14002. if (program.transformFeedback) {
  14003. this.deleteTransformFeedback(program.transformFeedback);
  14004. program.transformFeedback = null;
  14005. }
  14006. this._gl.deleteProgram(program);
  14007. }
  14008. };
  14009. /**
  14010. * Create a new effect (used to store vertex/fragment shaders)
  14011. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14012. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14013. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14014. * @param samplers defines an array of string used to represent textures
  14015. * @param defines defines the string containing the defines to use to compile the shaders
  14016. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14017. * @param onCompiled defines a function to call when the effect creation is successful
  14018. * @param onError defines a function to call when the effect creation has failed
  14019. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14020. * @returns the new Effect
  14021. */
  14022. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14023. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14024. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14025. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14026. if (this._compiledEffects[name]) {
  14027. var compiledEffect = this._compiledEffects[name];
  14028. if (onCompiled && compiledEffect.isReady()) {
  14029. onCompiled(compiledEffect);
  14030. }
  14031. return compiledEffect;
  14032. }
  14033. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14034. effect._key = name;
  14035. this._compiledEffects[name] = effect;
  14036. return effect;
  14037. };
  14038. /**
  14039. * Create an effect to use with particle systems
  14040. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14041. * @param uniformsNames defines a list of attribute names
  14042. * @param samplers defines an array of string used to represent textures
  14043. * @param defines defines the string containing the defines to use to compile the shaders
  14044. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14045. * @param onCompiled defines a function to call when the effect creation is successful
  14046. * @param onError defines a function to call when the effect creation has failed
  14047. * @returns the new Effect
  14048. */
  14049. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14050. if (uniformsNames === void 0) { uniformsNames = []; }
  14051. if (samplers === void 0) { samplers = []; }
  14052. if (defines === void 0) { defines = ""; }
  14053. return this.createEffect({
  14054. vertex: "particles",
  14055. fragmentElement: fragmentName
  14056. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14057. };
  14058. /**
  14059. * Directly creates a webGL program
  14060. * @param vertexCode defines the vertex shader code to use
  14061. * @param fragmentCode defines the fragment shader code to use
  14062. * @param context defines the webGL context to use (if not set, the current one will be used)
  14063. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14064. * @returns the new webGL program
  14065. */
  14066. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14067. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14068. context = context || this._gl;
  14069. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14070. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14071. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14072. };
  14073. /**
  14074. * Creates a webGL program
  14075. * @param vertexCode defines the vertex shader code to use
  14076. * @param fragmentCode defines the fragment shader code to use
  14077. * @param defines defines the string containing the defines to use to compile the shaders
  14078. * @param context defines the webGL context to use (if not set, the current one will be used)
  14079. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14080. * @returns the new webGL program
  14081. */
  14082. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14083. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14084. context = context || this._gl;
  14085. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14086. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14087. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14088. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14089. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14090. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14091. return program;
  14092. };
  14093. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14094. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14095. var shaderProgram = context.createProgram();
  14096. if (!shaderProgram) {
  14097. throw new Error("Unable to create program");
  14098. }
  14099. context.attachShader(shaderProgram, vertexShader);
  14100. context.attachShader(shaderProgram, fragmentShader);
  14101. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14102. var transformFeedback = this.createTransformFeedback();
  14103. this.bindTransformFeedback(transformFeedback);
  14104. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14105. shaderProgram.transformFeedback = transformFeedback;
  14106. }
  14107. context.linkProgram(shaderProgram);
  14108. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14109. this.bindTransformFeedback(null);
  14110. }
  14111. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14112. if (!linked) {
  14113. context.validateProgram(shaderProgram);
  14114. var error = context.getProgramInfoLog(shaderProgram);
  14115. if (error) {
  14116. throw new Error(error);
  14117. }
  14118. }
  14119. context.deleteShader(vertexShader);
  14120. context.deleteShader(fragmentShader);
  14121. return shaderProgram;
  14122. };
  14123. /**
  14124. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14125. * @param shaderProgram defines the webGL program to use
  14126. * @param uniformsNames defines the list of uniform names
  14127. * @returns an array of webGL uniform locations
  14128. */
  14129. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14130. var results = new Array();
  14131. for (var index = 0; index < uniformsNames.length; index++) {
  14132. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14133. }
  14134. return results;
  14135. };
  14136. /**
  14137. * Gets the lsit of active attributes for a given webGL program
  14138. * @param shaderProgram defines the webGL program to use
  14139. * @param attributesNames defines the list of attribute names to get
  14140. * @returns an array of indices indicating the offset of each attribute
  14141. */
  14142. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14143. var results = [];
  14144. for (var index = 0; index < attributesNames.length; index++) {
  14145. try {
  14146. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14147. }
  14148. catch (e) {
  14149. results.push(-1);
  14150. }
  14151. }
  14152. return results;
  14153. };
  14154. /**
  14155. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14156. * @param effect defines the effect to activate
  14157. */
  14158. Engine.prototype.enableEffect = function (effect) {
  14159. if (!effect) {
  14160. return;
  14161. }
  14162. // Use program
  14163. this.bindSamplers(effect);
  14164. this._currentEffect = effect;
  14165. if (effect.onBind) {
  14166. effect.onBind(effect);
  14167. }
  14168. effect.onBindObservable.notifyObservers(effect);
  14169. };
  14170. /**
  14171. * Set the value of an uniform to an array of int32
  14172. * @param uniform defines the webGL uniform location where to store the value
  14173. * @param array defines the array of int32 to store
  14174. */
  14175. Engine.prototype.setIntArray = function (uniform, array) {
  14176. if (!uniform)
  14177. return;
  14178. this._gl.uniform1iv(uniform, array);
  14179. };
  14180. /**
  14181. * Set the value of an uniform to an array of int32 (stored as vec2)
  14182. * @param uniform defines the webGL uniform location where to store the value
  14183. * @param array defines the array of int32 to store
  14184. */
  14185. Engine.prototype.setIntArray2 = function (uniform, array) {
  14186. if (!uniform || array.length % 2 !== 0)
  14187. return;
  14188. this._gl.uniform2iv(uniform, array);
  14189. };
  14190. /**
  14191. * Set the value of an uniform to an array of int32 (stored as vec3)
  14192. * @param uniform defines the webGL uniform location where to store the value
  14193. * @param array defines the array of int32 to store
  14194. */
  14195. Engine.prototype.setIntArray3 = function (uniform, array) {
  14196. if (!uniform || array.length % 3 !== 0)
  14197. return;
  14198. this._gl.uniform3iv(uniform, array);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to an array of int32 (stored as vec4)
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param array defines the array of int32 to store
  14204. */
  14205. Engine.prototype.setIntArray4 = function (uniform, array) {
  14206. if (!uniform || array.length % 4 !== 0)
  14207. return;
  14208. this._gl.uniform4iv(uniform, array);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to an array of float32
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param array defines the array of float32 to store
  14214. */
  14215. Engine.prototype.setFloatArray = function (uniform, array) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform1fv(uniform, array);
  14219. };
  14220. /**
  14221. * Set the value of an uniform to an array of float32 (stored as vec2)
  14222. * @param uniform defines the webGL uniform location where to store the value
  14223. * @param array defines the array of float32 to store
  14224. */
  14225. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14226. if (!uniform || array.length % 2 !== 0)
  14227. return;
  14228. this._gl.uniform2fv(uniform, array);
  14229. };
  14230. /**
  14231. * Set the value of an uniform to an array of float32 (stored as vec3)
  14232. * @param uniform defines the webGL uniform location where to store the value
  14233. * @param array defines the array of float32 to store
  14234. */
  14235. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14236. if (!uniform || array.length % 3 !== 0)
  14237. return;
  14238. this._gl.uniform3fv(uniform, array);
  14239. };
  14240. /**
  14241. * Set the value of an uniform to an array of float32 (stored as vec4)
  14242. * @param uniform defines the webGL uniform location where to store the value
  14243. * @param array defines the array of float32 to store
  14244. */
  14245. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14246. if (!uniform || array.length % 4 !== 0)
  14247. return;
  14248. this._gl.uniform4fv(uniform, array);
  14249. };
  14250. /**
  14251. * Set the value of an uniform to an array of number
  14252. * @param uniform defines the webGL uniform location where to store the value
  14253. * @param array defines the array of number to store
  14254. */
  14255. Engine.prototype.setArray = function (uniform, array) {
  14256. if (!uniform)
  14257. return;
  14258. this._gl.uniform1fv(uniform, array);
  14259. };
  14260. /**
  14261. * Set the value of an uniform to an array of number (stored as vec2)
  14262. * @param uniform defines the webGL uniform location where to store the value
  14263. * @param array defines the array of number to store
  14264. */
  14265. Engine.prototype.setArray2 = function (uniform, array) {
  14266. if (!uniform || array.length % 2 !== 0)
  14267. return;
  14268. this._gl.uniform2fv(uniform, array);
  14269. };
  14270. /**
  14271. * Set the value of an uniform to an array of number (stored as vec3)
  14272. * @param uniform defines the webGL uniform location where to store the value
  14273. * @param array defines the array of number to store
  14274. */
  14275. Engine.prototype.setArray3 = function (uniform, array) {
  14276. if (!uniform || array.length % 3 !== 0)
  14277. return;
  14278. this._gl.uniform3fv(uniform, array);
  14279. };
  14280. /**
  14281. * Set the value of an uniform to an array of number (stored as vec4)
  14282. * @param uniform defines the webGL uniform location where to store the value
  14283. * @param array defines the array of number to store
  14284. */
  14285. Engine.prototype.setArray4 = function (uniform, array) {
  14286. if (!uniform || array.length % 4 !== 0)
  14287. return;
  14288. this._gl.uniform4fv(uniform, array);
  14289. };
  14290. /**
  14291. * Set the value of an uniform to an array of float32 (stored as matrices)
  14292. * @param uniform defines the webGL uniform location where to store the value
  14293. * @param matrices defines the array of float32 to store
  14294. */
  14295. Engine.prototype.setMatrices = function (uniform, matrices) {
  14296. if (!uniform)
  14297. return;
  14298. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14299. };
  14300. /**
  14301. * Set the value of an uniform to a matrix
  14302. * @param uniform defines the webGL uniform location where to store the value
  14303. * @param matrix defines the matrix to store
  14304. */
  14305. Engine.prototype.setMatrix = function (uniform, matrix) {
  14306. if (!uniform)
  14307. return;
  14308. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14309. };
  14310. /**
  14311. * Set the value of an uniform to a matrix (3x3)
  14312. * @param uniform defines the webGL uniform location where to store the value
  14313. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14314. */
  14315. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14316. if (!uniform)
  14317. return;
  14318. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14319. };
  14320. /**
  14321. * Set the value of an uniform to a matrix (2x2)
  14322. * @param uniform defines the webGL uniform location where to store the value
  14323. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14324. */
  14325. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14326. if (!uniform)
  14327. return;
  14328. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14329. };
  14330. /**
  14331. * Set the value of an uniform to a number (int)
  14332. * @param uniform defines the webGL uniform location where to store the value
  14333. * @param value defines the int number to store
  14334. */
  14335. Engine.prototype.setInt = function (uniform, value) {
  14336. if (!uniform)
  14337. return;
  14338. this._gl.uniform1i(uniform, value);
  14339. };
  14340. /**
  14341. * Set the value of an uniform to a number (float)
  14342. * @param uniform defines the webGL uniform location where to store the value
  14343. * @param value defines the float number to store
  14344. */
  14345. Engine.prototype.setFloat = function (uniform, value) {
  14346. if (!uniform)
  14347. return;
  14348. this._gl.uniform1f(uniform, value);
  14349. };
  14350. /**
  14351. * Set the value of an uniform to a vec2
  14352. * @param uniform defines the webGL uniform location where to store the value
  14353. * @param x defines the 1st component of the value
  14354. * @param y defines the 2nd component of the value
  14355. */
  14356. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform2f(uniform, x, y);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a vec3
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param x defines the 1st component of the value
  14365. * @param y defines the 2nd component of the value
  14366. * @param z defines the 3rd component of the value
  14367. */
  14368. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14369. if (!uniform)
  14370. return;
  14371. this._gl.uniform3f(uniform, x, y, z);
  14372. };
  14373. /**
  14374. * Set the value of an uniform to a boolean
  14375. * @param uniform defines the webGL uniform location where to store the value
  14376. * @param bool defines the boolean to store
  14377. */
  14378. Engine.prototype.setBool = function (uniform, bool) {
  14379. if (!uniform)
  14380. return;
  14381. this._gl.uniform1i(uniform, bool);
  14382. };
  14383. /**
  14384. * Set the value of an uniform to a vec4
  14385. * @param uniform defines the webGL uniform location where to store the value
  14386. * @param x defines the 1st component of the value
  14387. * @param y defines the 2nd component of the value
  14388. * @param z defines the 3rd component of the value
  14389. * @param w defines the 4th component of the value
  14390. */
  14391. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14392. if (!uniform)
  14393. return;
  14394. this._gl.uniform4f(uniform, x, y, z, w);
  14395. };
  14396. /**
  14397. * Set the value of an uniform to a Color3
  14398. * @param uniform defines the webGL uniform location where to store the value
  14399. * @param color3 defines the color to store
  14400. */
  14401. Engine.prototype.setColor3 = function (uniform, color3) {
  14402. if (!uniform)
  14403. return;
  14404. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14405. };
  14406. /**
  14407. * Set the value of an uniform to a Color3 and an alpha value
  14408. * @param uniform defines the webGL uniform location where to store the value
  14409. * @param color3 defines the color to store
  14410. * @param alpha defines the alpha component to store
  14411. */
  14412. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14413. if (!uniform)
  14414. return;
  14415. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14416. };
  14417. /**
  14418. * Sets a Color4 on a uniform variable
  14419. * @param uniform defines the uniform location
  14420. * @param color4 defines the value to be set
  14421. */
  14422. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14423. if (!uniform)
  14424. return;
  14425. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14426. };
  14427. // States
  14428. /**
  14429. * Set various states to the webGL context
  14430. * @param culling defines backface culling state
  14431. * @param zOffset defines the value to apply to zOffset (0 by default)
  14432. * @param force defines if states must be applied even if cache is up to date
  14433. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14434. */
  14435. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14436. if (zOffset === void 0) { zOffset = 0; }
  14437. if (reverseSide === void 0) { reverseSide = false; }
  14438. // Culling
  14439. if (this._depthCullingState.cull !== culling || force) {
  14440. this._depthCullingState.cull = culling;
  14441. }
  14442. // Cull face
  14443. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14444. if (this._depthCullingState.cullFace !== cullFace || force) {
  14445. this._depthCullingState.cullFace = cullFace;
  14446. }
  14447. // Z offset
  14448. this.setZOffset(zOffset);
  14449. // Front face
  14450. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14451. if (this._depthCullingState.frontFace !== frontFace || force) {
  14452. this._depthCullingState.frontFace = frontFace;
  14453. }
  14454. };
  14455. /**
  14456. * Set the z offset to apply to current rendering
  14457. * @param value defines the offset to apply
  14458. */
  14459. Engine.prototype.setZOffset = function (value) {
  14460. this._depthCullingState.zOffset = value;
  14461. };
  14462. /**
  14463. * Gets the current value of the zOffset
  14464. * @returns the current zOffset state
  14465. */
  14466. Engine.prototype.getZOffset = function () {
  14467. return this._depthCullingState.zOffset;
  14468. };
  14469. /**
  14470. * Enable or disable depth buffering
  14471. * @param enable defines the state to set
  14472. */
  14473. Engine.prototype.setDepthBuffer = function (enable) {
  14474. this._depthCullingState.depthTest = enable;
  14475. };
  14476. /**
  14477. * Gets a boolean indicating if depth writing is enabled
  14478. * @returns the current depth writing state
  14479. */
  14480. Engine.prototype.getDepthWrite = function () {
  14481. return this._depthCullingState.depthMask;
  14482. };
  14483. /**
  14484. * Enable or disable depth writing
  14485. * @param enable defines the state to set
  14486. */
  14487. Engine.prototype.setDepthWrite = function (enable) {
  14488. this._depthCullingState.depthMask = enable;
  14489. };
  14490. /**
  14491. * Enable or disable color writing
  14492. * @param enable defines the state to set
  14493. */
  14494. Engine.prototype.setColorWrite = function (enable) {
  14495. this._gl.colorMask(enable, enable, enable, enable);
  14496. this._colorWrite = enable;
  14497. };
  14498. /**
  14499. * Gets a boolean indicating if color writing is enabled
  14500. * @returns the current color writing state
  14501. */
  14502. Engine.prototype.getColorWrite = function () {
  14503. return this._colorWrite;
  14504. };
  14505. /**
  14506. * Sets alpha constants used by some alpha blending modes
  14507. * @param r defines the red component
  14508. * @param g defines the green component
  14509. * @param b defines the blue component
  14510. * @param a defines the alpha component
  14511. */
  14512. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14513. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14514. };
  14515. /**
  14516. * Sets the current alpha mode
  14517. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14518. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14519. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14520. */
  14521. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14522. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14523. if (this._alphaMode === mode) {
  14524. return;
  14525. }
  14526. switch (mode) {
  14527. case Engine.ALPHA_DISABLE:
  14528. this._alphaState.alphaBlend = false;
  14529. break;
  14530. case Engine.ALPHA_PREMULTIPLIED:
  14531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14532. this._alphaState.alphaBlend = true;
  14533. break;
  14534. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14536. this._alphaState.alphaBlend = true;
  14537. break;
  14538. case Engine.ALPHA_COMBINE:
  14539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14540. this._alphaState.alphaBlend = true;
  14541. break;
  14542. case Engine.ALPHA_ONEONE:
  14543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14544. this._alphaState.alphaBlend = true;
  14545. break;
  14546. case Engine.ALPHA_ADD:
  14547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14548. this._alphaState.alphaBlend = true;
  14549. break;
  14550. case Engine.ALPHA_SUBTRACT:
  14551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14552. this._alphaState.alphaBlend = true;
  14553. break;
  14554. case Engine.ALPHA_MULTIPLY:
  14555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14556. this._alphaState.alphaBlend = true;
  14557. break;
  14558. case Engine.ALPHA_MAXIMIZED:
  14559. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14560. this._alphaState.alphaBlend = true;
  14561. break;
  14562. case Engine.ALPHA_INTERPOLATE:
  14563. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14564. this._alphaState.alphaBlend = true;
  14565. break;
  14566. case Engine.ALPHA_SCREENMODE:
  14567. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14568. this._alphaState.alphaBlend = true;
  14569. break;
  14570. }
  14571. if (!noDepthWriteChange) {
  14572. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14573. }
  14574. this._alphaMode = mode;
  14575. };
  14576. /**
  14577. * Gets the current alpha mode
  14578. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14579. * @returns the current alpha mode
  14580. */
  14581. Engine.prototype.getAlphaMode = function () {
  14582. return this._alphaMode;
  14583. };
  14584. // Textures
  14585. /**
  14586. * Clears the list of texture accessible through engine.
  14587. * This can help preventing texture load conflict due to name collision.
  14588. */
  14589. Engine.prototype.clearInternalTexturesCache = function () {
  14590. this._internalTexturesCache = [];
  14591. };
  14592. /**
  14593. * Force the entire cache to be cleared
  14594. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14595. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14596. */
  14597. Engine.prototype.wipeCaches = function (bruteForce) {
  14598. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14599. return;
  14600. }
  14601. this._currentEffect = null;
  14602. this._unpackFlipYCached = null;
  14603. this._viewportCached.x = 0;
  14604. this._viewportCached.y = 0;
  14605. this._viewportCached.z = 0;
  14606. this._viewportCached.w = 0;
  14607. if (bruteForce) {
  14608. this.resetTextureCache();
  14609. this._currentProgram = null;
  14610. this._stencilState.reset();
  14611. this._depthCullingState.reset();
  14612. this.setDepthFunctionToLessOrEqual();
  14613. this._alphaState.reset();
  14614. }
  14615. this._resetVertexBufferBinding();
  14616. this._cachedIndexBuffer = null;
  14617. this._cachedEffectForVertexBuffers = null;
  14618. this._unbindVertexArrayObject();
  14619. this.bindIndexBuffer(null);
  14620. };
  14621. /**
  14622. * Set the compressed texture format to use, based on the formats you have, and the formats
  14623. * supported by the hardware / browser.
  14624. *
  14625. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14626. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14627. * to API arguments needed to compressed textures. This puts the burden on the container
  14628. * generator to house the arcane code for determining these for current & future formats.
  14629. *
  14630. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14631. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14632. *
  14633. * Note: The result of this call is not taken into account when a texture is base64.
  14634. *
  14635. * @param formatsAvailable defines the list of those format families you have created
  14636. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14637. *
  14638. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14639. * @returns The extension selected.
  14640. */
  14641. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14642. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14643. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14644. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14645. return this._textureFormatInUse = this._texturesSupported[i];
  14646. }
  14647. }
  14648. }
  14649. // actively set format to nothing, to allow this to be called more than once
  14650. // and possibly fail the 2nd time
  14651. this._textureFormatInUse = null;
  14652. return null;
  14653. };
  14654. /** @hidden */
  14655. Engine.prototype._createTexture = function () {
  14656. var texture = this._gl.createTexture();
  14657. if (!texture) {
  14658. throw new Error("Unable to create texture");
  14659. }
  14660. return texture;
  14661. };
  14662. /**
  14663. * Usually called from BABYLON.Texture.ts.
  14664. * Passed information to create a WebGLTexture
  14665. * @param urlArg defines a value which contains one of the following:
  14666. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14667. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14668. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14669. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14670. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14671. * @param scene needed for loading to the correct scene
  14672. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14673. * @param onLoad optional callback to be called upon successful completion
  14674. * @param onError optional callback to be called upon failure
  14675. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14676. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14677. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14678. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14679. */
  14680. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14681. var _this = this;
  14682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14683. if (onLoad === void 0) { onLoad = null; }
  14684. if (onError === void 0) { onError = null; }
  14685. if (buffer === void 0) { buffer = null; }
  14686. if (fallback === void 0) { fallback = null; }
  14687. if (format === void 0) { format = null; }
  14688. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14689. var fromData = url.substr(0, 5) === "data:";
  14690. var fromBlob = url.substr(0, 5) === "blob:";
  14691. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14692. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14693. // establish the file extension, if possible
  14694. var lastDot = url.lastIndexOf('.');
  14695. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14696. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14697. var isTGA = (extension.indexOf(".tga") === 0);
  14698. // determine if a ktx file should be substituted
  14699. var isKTX = false;
  14700. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14701. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14702. isKTX = true;
  14703. }
  14704. if (scene) {
  14705. scene._addPendingData(texture);
  14706. }
  14707. texture.url = url;
  14708. texture.generateMipMaps = !noMipmap;
  14709. texture.samplingMode = samplingMode;
  14710. texture.invertY = invertY;
  14711. if (!this._doNotHandleContextLost) {
  14712. // Keep a link to the buffer only if we plan to handle context lost
  14713. texture._buffer = buffer;
  14714. }
  14715. var onLoadObserver = null;
  14716. if (onLoad && !fallback) {
  14717. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14718. }
  14719. if (!fallback)
  14720. this._internalTexturesCache.push(texture);
  14721. var onerror = function (message, exception) {
  14722. if (scene) {
  14723. scene._removePendingData(texture);
  14724. }
  14725. if (onLoadObserver && !isKTX) {
  14726. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14727. texture.onLoadedObservable.remove(onLoadObserver);
  14728. }
  14729. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14730. if (isKTX) {
  14731. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14732. }
  14733. else if (BABYLON.Tools.UseFallbackTexture) {
  14734. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14735. }
  14736. if (onError) {
  14737. onError(message || "Unknown error", exception);
  14738. }
  14739. };
  14740. var callback = null;
  14741. // processing for non-image formats
  14742. if (isKTX || isTGA || isDDS) {
  14743. if (isKTX) {
  14744. callback = function (data) {
  14745. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14746. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14747. ktx.uploadLevels(_this._gl, !noMipmap);
  14748. return false;
  14749. }, samplingMode);
  14750. };
  14751. }
  14752. else if (isTGA) {
  14753. callback = function (arrayBuffer) {
  14754. var data = new Uint8Array(arrayBuffer);
  14755. var header = BABYLON.TGATools.GetTGAHeader(data);
  14756. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14757. BABYLON.TGATools.UploadContent(_this._gl, data);
  14758. return false;
  14759. }, samplingMode);
  14760. };
  14761. }
  14762. else if (isDDS) {
  14763. callback = function (data) {
  14764. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14765. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14766. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14767. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14768. return false;
  14769. }, samplingMode);
  14770. };
  14771. }
  14772. if (!buffer) {
  14773. this._loadFile(url, function (data) {
  14774. if (callback) {
  14775. callback(data);
  14776. }
  14777. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14778. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14779. });
  14780. }
  14781. else {
  14782. if (callback) {
  14783. callback(buffer);
  14784. }
  14785. }
  14786. // image format processing
  14787. }
  14788. else {
  14789. var onload = function (img) {
  14790. if (fromBlob && !_this._doNotHandleContextLost) {
  14791. // We need to store the image if we need to rebuild the texture
  14792. // in case of a webgl context lost
  14793. texture._buffer = img;
  14794. }
  14795. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14796. var gl = _this._gl;
  14797. var isPot = (img.width === potWidth && img.height === potHeight);
  14798. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14799. if (isPot) {
  14800. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14801. return false;
  14802. }
  14803. // Using shaders to rescale because canvas.drawImage is lossy
  14804. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14805. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14806. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14807. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14808. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14811. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14812. _this._releaseTexture(source);
  14813. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14814. continuationCallback();
  14815. });
  14816. return true;
  14817. }, samplingMode);
  14818. };
  14819. if (!fromData || isBase64) {
  14820. if (buffer instanceof HTMLImageElement) {
  14821. onload(buffer);
  14822. }
  14823. else {
  14824. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14825. }
  14826. }
  14827. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14828. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14829. }
  14830. else {
  14831. onload(buffer);
  14832. }
  14833. }
  14834. return texture;
  14835. };
  14836. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14837. var _this = this;
  14838. var rtt = this.createRenderTargetTexture({
  14839. width: destination.width,
  14840. height: destination.height,
  14841. }, {
  14842. generateMipMaps: false,
  14843. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14844. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14845. generateDepthBuffer: false,
  14846. generateStencilBuffer: false
  14847. });
  14848. if (!this._rescalePostProcess) {
  14849. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14850. }
  14851. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14852. _this._rescalePostProcess.onApply = function (effect) {
  14853. effect._bindTexture("textureSampler", source);
  14854. };
  14855. var hostingScene = scene;
  14856. if (!hostingScene) {
  14857. hostingScene = _this.scenes[_this.scenes.length - 1];
  14858. }
  14859. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14860. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14861. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14862. _this.unBindFramebuffer(rtt);
  14863. _this._releaseTexture(rtt);
  14864. if (onComplete) {
  14865. onComplete();
  14866. }
  14867. });
  14868. };
  14869. /**
  14870. * Update a raw texture
  14871. * @param texture defines the texture to update
  14872. * @param data defines the data to store in the texture
  14873. * @param format defines the format of the data
  14874. * @param invertY defines if data must be stored with Y axis inverted
  14875. * @param compression defines the compression used (null by default)
  14876. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14877. */
  14878. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14879. if (compression === void 0) { compression = null; }
  14880. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14881. if (!texture) {
  14882. return;
  14883. }
  14884. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14885. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14886. // babylon's internalFormat but gl's texImage2D format
  14887. var internalFormat = this._getInternalFormat(format);
  14888. var textureType = this._getWebGLTextureType(type);
  14889. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14890. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14891. if (!this._doNotHandleContextLost) {
  14892. texture._bufferView = data;
  14893. texture.format = format;
  14894. texture.type = type;
  14895. texture.invertY = invertY;
  14896. texture._compression = compression;
  14897. }
  14898. if (texture.width % 4 !== 0) {
  14899. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14900. }
  14901. if (compression && data) {
  14902. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14903. }
  14904. else {
  14905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14906. }
  14907. if (texture.generateMipMaps) {
  14908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14909. }
  14910. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14911. // this.resetTextureCache();
  14912. texture.isReady = true;
  14913. };
  14914. /**
  14915. * Creates a raw texture
  14916. * @param data defines the data to store in the texture
  14917. * @param width defines the width of the texture
  14918. * @param height defines the height of the texture
  14919. * @param format defines the format of the data
  14920. * @param generateMipMaps defines if the engine should generate the mip levels
  14921. * @param invertY defines if data must be stored with Y axis inverted
  14922. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14923. * @param compression defines the compression used (null by default)
  14924. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14925. * @returns the raw texture inside an InternalTexture
  14926. */
  14927. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14928. if (compression === void 0) { compression = null; }
  14929. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14930. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14931. texture.baseWidth = width;
  14932. texture.baseHeight = height;
  14933. texture.width = width;
  14934. texture.height = height;
  14935. texture.format = format;
  14936. texture.generateMipMaps = generateMipMaps;
  14937. texture.samplingMode = samplingMode;
  14938. texture.invertY = invertY;
  14939. texture._compression = compression;
  14940. texture.type = type;
  14941. if (!this._doNotHandleContextLost) {
  14942. texture._bufferView = data;
  14943. }
  14944. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14945. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14946. // Filters
  14947. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14948. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14949. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14950. if (generateMipMaps) {
  14951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14952. }
  14953. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14954. this._internalTexturesCache.push(texture);
  14955. return texture;
  14956. };
  14957. /** @hidden */
  14958. Engine.prototype._unpackFlipY = function (value) {
  14959. if (this._unpackFlipYCached !== value) {
  14960. this._unpackFlipYCached = value;
  14961. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14962. }
  14963. };
  14964. /**
  14965. * Creates a dynamic texture
  14966. * @param width defines the width of the texture
  14967. * @param height defines the height of the texture
  14968. * @param generateMipMaps defines if the engine should generate the mip levels
  14969. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14970. * @returns the dynamic texture inside an InternalTexture
  14971. */
  14972. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14974. texture.baseWidth = width;
  14975. texture.baseHeight = height;
  14976. if (generateMipMaps) {
  14977. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14978. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14979. }
  14980. // this.resetTextureCache();
  14981. texture.width = width;
  14982. texture.height = height;
  14983. texture.isReady = false;
  14984. texture.generateMipMaps = generateMipMaps;
  14985. texture.samplingMode = samplingMode;
  14986. this.updateTextureSamplingMode(samplingMode, texture);
  14987. this._internalTexturesCache.push(texture);
  14988. return texture;
  14989. };
  14990. /**
  14991. * Update the sampling mode of a given texture
  14992. * @param samplingMode defines the required sampling mode
  14993. * @param texture defines the texture to update
  14994. */
  14995. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14996. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14997. if (texture.isCube) {
  14998. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14999. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15000. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15001. }
  15002. else if (texture.is3D) {
  15003. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15004. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15005. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15006. }
  15007. else {
  15008. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15009. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15010. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15011. }
  15012. texture.samplingMode = samplingMode;
  15013. };
  15014. /**
  15015. * Update the content of a dynamic texture
  15016. * @param texture defines the texture to update
  15017. * @param canvas defines the canvas containing the source
  15018. * @param invertY defines if data must be stored with Y axis inverted
  15019. * @param premulAlpha defines if alpha is stored as premultiplied
  15020. * @param format defines the format of the data
  15021. */
  15022. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15023. if (premulAlpha === void 0) { premulAlpha = false; }
  15024. if (!texture) {
  15025. return;
  15026. }
  15027. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15028. this._unpackFlipY(invertY);
  15029. if (premulAlpha) {
  15030. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15031. }
  15032. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15033. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15034. if (texture.generateMipMaps) {
  15035. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15036. }
  15037. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15038. if (premulAlpha) {
  15039. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15040. }
  15041. texture.isReady = true;
  15042. };
  15043. /**
  15044. * Update a video texture
  15045. * @param texture defines the texture to update
  15046. * @param video defines the video element to use
  15047. * @param invertY defines if data must be stored with Y axis inverted
  15048. */
  15049. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15050. if (!texture || texture._isDisabled) {
  15051. return;
  15052. }
  15053. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15054. this._unpackFlipY(!invertY); // Video are upside down by default
  15055. try {
  15056. // Testing video texture support
  15057. if (this._videoTextureSupported === undefined) {
  15058. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15059. if (this._gl.getError() !== 0) {
  15060. this._videoTextureSupported = false;
  15061. }
  15062. else {
  15063. this._videoTextureSupported = true;
  15064. }
  15065. }
  15066. // Copy video through the current working canvas if video texture is not supported
  15067. if (!this._videoTextureSupported) {
  15068. if (!texture._workingCanvas) {
  15069. texture._workingCanvas = document.createElement("canvas");
  15070. var context = texture._workingCanvas.getContext("2d");
  15071. if (!context) {
  15072. throw new Error("Unable to get 2d context");
  15073. }
  15074. texture._workingContext = context;
  15075. texture._workingCanvas.width = texture.width;
  15076. texture._workingCanvas.height = texture.height;
  15077. }
  15078. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15079. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15080. }
  15081. else {
  15082. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15083. }
  15084. if (texture.generateMipMaps) {
  15085. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15086. }
  15087. if (!wasPreviouslyBound) {
  15088. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15089. }
  15090. // this.resetTextureCache();
  15091. texture.isReady = true;
  15092. }
  15093. catch (ex) {
  15094. // Something unexpected
  15095. // Let's disable the texture
  15096. texture._isDisabled = true;
  15097. }
  15098. };
  15099. /**
  15100. * Updates a depth texture Comparison Mode and Function.
  15101. * If the comparison Function is equal to 0, the mode will be set to none.
  15102. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15103. * @param texture The texture to set the comparison function for
  15104. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15105. */
  15106. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15107. if (this.webGLVersion === 1) {
  15108. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15109. return;
  15110. }
  15111. var gl = this._gl;
  15112. if (texture.isCube) {
  15113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15114. if (comparisonFunction === 0) {
  15115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15117. }
  15118. else {
  15119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15121. }
  15122. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15123. }
  15124. else {
  15125. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15126. if (comparisonFunction === 0) {
  15127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15129. }
  15130. else {
  15131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15133. }
  15134. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15135. }
  15136. texture._comparisonFunction = comparisonFunction;
  15137. };
  15138. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15139. var width = size.width || size;
  15140. var height = size.height || size;
  15141. internalTexture.baseWidth = width;
  15142. internalTexture.baseHeight = height;
  15143. internalTexture.width = width;
  15144. internalTexture.height = height;
  15145. internalTexture.isReady = true;
  15146. internalTexture.samples = 1;
  15147. internalTexture.generateMipMaps = false;
  15148. internalTexture._generateDepthBuffer = true;
  15149. internalTexture._generateStencilBuffer = generateStencil;
  15150. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15151. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15152. internalTexture._comparisonFunction = comparisonFunction;
  15153. var gl = this._gl;
  15154. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15155. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15156. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15157. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15158. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15159. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15160. if (comparisonFunction === 0) {
  15161. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15162. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15163. }
  15164. else {
  15165. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15166. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15167. }
  15168. };
  15169. /**
  15170. * Creates a depth stencil texture.
  15171. * This is only available in WebGL 2 or with the depth texture extension available.
  15172. * @param size The size of face edge in the texture.
  15173. * @param options The options defining the texture.
  15174. * @returns The texture
  15175. */
  15176. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15177. if (options.isCube) {
  15178. var width = size.width || size;
  15179. return this._createDepthStencilCubeTexture(width, options);
  15180. }
  15181. else {
  15182. return this._createDepthStencilTexture(size, options);
  15183. }
  15184. };
  15185. /**
  15186. * Creates a depth stencil texture.
  15187. * This is only available in WebGL 2 or with the depth texture extension available.
  15188. * @param size The size of face edge in the texture.
  15189. * @param options The options defining the texture.
  15190. * @returns The texture
  15191. */
  15192. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15193. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15194. if (!this._caps.depthTextureExtension) {
  15195. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15196. return internalTexture;
  15197. }
  15198. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15199. var gl = this._gl;
  15200. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15201. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15202. if (this.webGLVersion > 1) {
  15203. if (internalOptions.generateStencil) {
  15204. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15205. }
  15206. else {
  15207. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15208. }
  15209. }
  15210. else {
  15211. if (internalOptions.generateStencil) {
  15212. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15213. }
  15214. else {
  15215. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15216. }
  15217. }
  15218. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15219. return internalTexture;
  15220. };
  15221. /**
  15222. * Creates a depth stencil cube texture.
  15223. * This is only available in WebGL 2.
  15224. * @param size The size of face edge in the cube texture.
  15225. * @param options The options defining the cube texture.
  15226. * @returns The cube texture
  15227. */
  15228. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15229. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15230. internalTexture.isCube = true;
  15231. if (this.webGLVersion === 1) {
  15232. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15233. return internalTexture;
  15234. }
  15235. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15236. var gl = this._gl;
  15237. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15238. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15239. // Create the depth/stencil buffer
  15240. for (var face = 0; face < 6; face++) {
  15241. if (internalOptions.generateStencil) {
  15242. 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);
  15243. }
  15244. else {
  15245. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15246. }
  15247. }
  15248. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15249. return internalTexture;
  15250. };
  15251. /**
  15252. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15253. * @param renderTarget The render target to set the frame buffer for
  15254. */
  15255. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15256. // Create the framebuffer
  15257. var internalTexture = renderTarget.getInternalTexture();
  15258. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15259. return;
  15260. }
  15261. var gl = this._gl;
  15262. var depthStencilTexture = renderTarget.depthStencilTexture;
  15263. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15264. if (depthStencilTexture.isCube) {
  15265. if (depthStencilTexture._generateStencilBuffer) {
  15266. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15267. }
  15268. else {
  15269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15270. }
  15271. }
  15272. else {
  15273. if (depthStencilTexture._generateStencilBuffer) {
  15274. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15275. }
  15276. else {
  15277. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15278. }
  15279. }
  15280. this.bindUnboundFramebuffer(null);
  15281. };
  15282. /**
  15283. * Creates a new render target texture
  15284. * @param size defines the size of the texture
  15285. * @param options defines the options used to create the texture
  15286. * @returns a new render target texture stored in an InternalTexture
  15287. */
  15288. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15289. var fullOptions = new RenderTargetCreationOptions();
  15290. if (options !== undefined && typeof options === "object") {
  15291. fullOptions.generateMipMaps = options.generateMipMaps;
  15292. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15293. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15294. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15295. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15296. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15297. }
  15298. else {
  15299. fullOptions.generateMipMaps = options;
  15300. fullOptions.generateDepthBuffer = true;
  15301. fullOptions.generateStencilBuffer = false;
  15302. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15303. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15304. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15305. }
  15306. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15307. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15308. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15309. }
  15310. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15311. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15312. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15313. }
  15314. var gl = this._gl;
  15315. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15316. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15317. var width = size.width || size;
  15318. var height = size.height || size;
  15319. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15320. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15321. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15322. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15323. }
  15324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15328. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15329. // Create the framebuffer
  15330. var currentFrameBuffer = this._currentFramebuffer;
  15331. var framebuffer = gl.createFramebuffer();
  15332. this.bindUnboundFramebuffer(framebuffer);
  15333. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15334. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15335. if (fullOptions.generateMipMaps) {
  15336. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15337. }
  15338. // Unbind
  15339. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15340. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15341. this.bindUnboundFramebuffer(currentFrameBuffer);
  15342. texture._framebuffer = framebuffer;
  15343. texture.baseWidth = width;
  15344. texture.baseHeight = height;
  15345. texture.width = width;
  15346. texture.height = height;
  15347. texture.isReady = true;
  15348. texture.samples = 1;
  15349. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15350. texture.samplingMode = fullOptions.samplingMode;
  15351. texture.type = fullOptions.type;
  15352. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15353. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15354. // this.resetTextureCache();
  15355. this._internalTexturesCache.push(texture);
  15356. return texture;
  15357. };
  15358. /**
  15359. * Create a multi render target texture
  15360. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15361. * @param size defines the size of the texture
  15362. * @param options defines the creation options
  15363. * @returns the cube texture as an InternalTexture
  15364. */
  15365. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15366. var generateMipMaps = false;
  15367. var generateDepthBuffer = true;
  15368. var generateStencilBuffer = false;
  15369. var generateDepthTexture = false;
  15370. var textureCount = 1;
  15371. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15372. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15373. var types = new Array();
  15374. var samplingModes = new Array();
  15375. if (options !== undefined) {
  15376. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15377. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15378. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15379. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15380. textureCount = options.textureCount || 1;
  15381. if (options.types) {
  15382. types = options.types;
  15383. }
  15384. if (options.samplingModes) {
  15385. samplingModes = options.samplingModes;
  15386. }
  15387. }
  15388. var gl = this._gl;
  15389. // Create the framebuffer
  15390. var framebuffer = gl.createFramebuffer();
  15391. this.bindUnboundFramebuffer(framebuffer);
  15392. var width = size.width || size;
  15393. var height = size.height || size;
  15394. var textures = [];
  15395. var attachments = [];
  15396. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15397. for (var i = 0; i < textureCount; i++) {
  15398. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15399. var type = types[i] || defaultType;
  15400. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15401. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15403. }
  15404. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15405. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15406. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15407. }
  15408. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15409. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15410. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15411. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15412. }
  15413. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15414. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15415. textures.push(texture);
  15416. attachments.push(attachment);
  15417. gl.activeTexture(gl["TEXTURE" + i]);
  15418. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15419. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15423. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15424. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15425. if (generateMipMaps) {
  15426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15427. }
  15428. // Unbind
  15429. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15430. texture._framebuffer = framebuffer;
  15431. texture._depthStencilBuffer = depthStencilBuffer;
  15432. texture.baseWidth = width;
  15433. texture.baseHeight = height;
  15434. texture.width = width;
  15435. texture.height = height;
  15436. texture.isReady = true;
  15437. texture.samples = 1;
  15438. texture.generateMipMaps = generateMipMaps;
  15439. texture.samplingMode = samplingMode;
  15440. texture.type = type;
  15441. texture._generateDepthBuffer = generateDepthBuffer;
  15442. texture._generateStencilBuffer = generateStencilBuffer;
  15443. texture._attachments = attachments;
  15444. this._internalTexturesCache.push(texture);
  15445. }
  15446. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15447. // Depth texture
  15448. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15449. gl.activeTexture(gl.TEXTURE0);
  15450. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15455. 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);
  15456. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15457. depthTexture._framebuffer = framebuffer;
  15458. depthTexture.baseWidth = width;
  15459. depthTexture.baseHeight = height;
  15460. depthTexture.width = width;
  15461. depthTexture.height = height;
  15462. depthTexture.isReady = true;
  15463. depthTexture.samples = 1;
  15464. depthTexture.generateMipMaps = generateMipMaps;
  15465. depthTexture.samplingMode = gl.NEAREST;
  15466. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15467. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15468. textures.push(depthTexture);
  15469. this._internalTexturesCache.push(depthTexture);
  15470. }
  15471. gl.drawBuffers(attachments);
  15472. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15473. this.bindUnboundFramebuffer(null);
  15474. this.resetTextureCache();
  15475. return textures;
  15476. };
  15477. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15478. if (samples === void 0) { samples = 1; }
  15479. var depthStencilBuffer = null;
  15480. var gl = this._gl;
  15481. // Create the depth/stencil buffer
  15482. if (generateStencilBuffer) {
  15483. depthStencilBuffer = gl.createRenderbuffer();
  15484. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15485. if (samples > 1) {
  15486. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15487. }
  15488. else {
  15489. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15490. }
  15491. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15492. }
  15493. else if (generateDepthBuffer) {
  15494. depthStencilBuffer = gl.createRenderbuffer();
  15495. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15496. if (samples > 1) {
  15497. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15498. }
  15499. else {
  15500. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15501. }
  15502. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15503. }
  15504. return depthStencilBuffer;
  15505. };
  15506. /**
  15507. * Updates the sample count of a render target texture
  15508. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15509. * @param texture defines the texture to update
  15510. * @param samples defines the sample count to set
  15511. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15512. */
  15513. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15514. if (this.webGLVersion < 2 || !texture) {
  15515. return 1;
  15516. }
  15517. if (texture.samples === samples) {
  15518. return samples;
  15519. }
  15520. var gl = this._gl;
  15521. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15522. // Dispose previous render buffers
  15523. if (texture._depthStencilBuffer) {
  15524. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15525. texture._depthStencilBuffer = null;
  15526. }
  15527. if (texture._MSAAFramebuffer) {
  15528. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15529. texture._MSAAFramebuffer = null;
  15530. }
  15531. if (texture._MSAARenderBuffer) {
  15532. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15533. texture._MSAARenderBuffer = null;
  15534. }
  15535. if (samples > 1) {
  15536. var framebuffer = gl.createFramebuffer();
  15537. if (!framebuffer) {
  15538. throw new Error("Unable to create multi sampled framebuffer");
  15539. }
  15540. texture._MSAAFramebuffer = framebuffer;
  15541. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15542. var colorRenderbuffer = gl.createRenderbuffer();
  15543. if (!colorRenderbuffer) {
  15544. throw new Error("Unable to create multi sampled framebuffer");
  15545. }
  15546. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15547. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15548. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15549. texture._MSAARenderBuffer = colorRenderbuffer;
  15550. }
  15551. else {
  15552. this.bindUnboundFramebuffer(texture._framebuffer);
  15553. }
  15554. texture.samples = samples;
  15555. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15556. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15557. this.bindUnboundFramebuffer(null);
  15558. return samples;
  15559. };
  15560. /**
  15561. * Update the sample count for a given multiple render target texture
  15562. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15563. * @param textures defines the textures to update
  15564. * @param samples defines the sample count to set
  15565. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15566. */
  15567. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15568. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15569. return 1;
  15570. }
  15571. if (textures[0].samples === samples) {
  15572. return samples;
  15573. }
  15574. var gl = this._gl;
  15575. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15576. // Dispose previous render buffers
  15577. if (textures[0]._depthStencilBuffer) {
  15578. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15579. textures[0]._depthStencilBuffer = null;
  15580. }
  15581. if (textures[0]._MSAAFramebuffer) {
  15582. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15583. textures[0]._MSAAFramebuffer = null;
  15584. }
  15585. for (var i = 0; i < textures.length; i++) {
  15586. if (textures[i]._MSAARenderBuffer) {
  15587. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15588. textures[i]._MSAARenderBuffer = null;
  15589. }
  15590. }
  15591. if (samples > 1) {
  15592. var framebuffer = gl.createFramebuffer();
  15593. if (!framebuffer) {
  15594. throw new Error("Unable to create multi sampled framebuffer");
  15595. }
  15596. this.bindUnboundFramebuffer(framebuffer);
  15597. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15598. var attachments = [];
  15599. for (var i = 0; i < textures.length; i++) {
  15600. var texture = textures[i];
  15601. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15602. var colorRenderbuffer = gl.createRenderbuffer();
  15603. if (!colorRenderbuffer) {
  15604. throw new Error("Unable to create multi sampled framebuffer");
  15605. }
  15606. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15607. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15608. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15609. texture._MSAAFramebuffer = framebuffer;
  15610. texture._MSAARenderBuffer = colorRenderbuffer;
  15611. texture.samples = samples;
  15612. texture._depthStencilBuffer = depthStencilBuffer;
  15613. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15614. attachments.push(attachment);
  15615. }
  15616. gl.drawBuffers(attachments);
  15617. }
  15618. else {
  15619. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15620. }
  15621. this.bindUnboundFramebuffer(null);
  15622. return samples;
  15623. };
  15624. /** @hidden */
  15625. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15626. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15627. };
  15628. /** @hidden */
  15629. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15630. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15631. };
  15632. /** @hidden */
  15633. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15634. var gl = this._gl;
  15635. var textureType = this._getWebGLTextureType(texture.type);
  15636. var format = this._getInternalFormat(texture.format);
  15637. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15638. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15639. this._bindTextureDirectly(bindTarget, texture, true);
  15640. this._unpackFlipY(texture.invertY);
  15641. var target = gl.TEXTURE_2D;
  15642. if (texture.isCube) {
  15643. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15644. }
  15645. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15646. this._bindTextureDirectly(bindTarget, null, true);
  15647. };
  15648. /**
  15649. * Creates a new render target cube texture
  15650. * @param size defines the size of the texture
  15651. * @param options defines the options used to create the texture
  15652. * @returns a new render target cube texture stored in an InternalTexture
  15653. */
  15654. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15655. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15656. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15657. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15658. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15659. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15660. }
  15661. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15662. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15663. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15664. }
  15665. var gl = this._gl;
  15666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15667. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15668. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15669. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15670. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15671. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15672. }
  15673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15677. for (var face = 0; face < 6; face++) {
  15678. 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);
  15679. }
  15680. // Create the framebuffer
  15681. var framebuffer = gl.createFramebuffer();
  15682. this.bindUnboundFramebuffer(framebuffer);
  15683. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15684. // MipMaps
  15685. if (fullOptions.generateMipMaps) {
  15686. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15687. }
  15688. // Unbind
  15689. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15690. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15691. this.bindUnboundFramebuffer(null);
  15692. texture._framebuffer = framebuffer;
  15693. texture.width = size;
  15694. texture.height = size;
  15695. texture.isReady = true;
  15696. texture.isCube = true;
  15697. texture.samples = 1;
  15698. texture.generateMipMaps = fullOptions.generateMipMaps;
  15699. texture.samplingMode = fullOptions.samplingMode;
  15700. texture.type = fullOptions.type;
  15701. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15702. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15703. this._internalTexturesCache.push(texture);
  15704. return texture;
  15705. };
  15706. /**
  15707. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15708. * @param rootUrl defines the url where the file to load is located
  15709. * @param scene defines the current scene
  15710. * @param lodScale defines scale to apply to the mip map selection
  15711. * @param lodOffset defines offset to apply to the mip map selection
  15712. * @param onLoad defines an optional callback raised when the texture is loaded
  15713. * @param onError defines an optional callback raised if there is an issue to load the texture
  15714. * @param format defines the format of the data
  15715. * @param forcedExtension defines the extension to use to pick the right loader
  15716. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15717. * @returns the cube texture as an InternalTexture
  15718. */
  15719. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15720. var _this = this;
  15721. if (onLoad === void 0) { onLoad = null; }
  15722. if (onError === void 0) { onError = null; }
  15723. if (forcedExtension === void 0) { forcedExtension = null; }
  15724. if (createPolynomials === void 0) { createPolynomials = true; }
  15725. var callback = function (loadData) {
  15726. if (!loadData) {
  15727. if (onLoad) {
  15728. onLoad(null);
  15729. }
  15730. return;
  15731. }
  15732. var texture = loadData.texture;
  15733. if (!createPolynomials) {
  15734. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15735. }
  15736. else if (loadData.info.sphericalPolynomial) {
  15737. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15738. }
  15739. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15740. if (_this._caps.textureLOD) {
  15741. // Do not add extra process if texture lod is supported.
  15742. if (onLoad) {
  15743. onLoad(texture);
  15744. }
  15745. return;
  15746. }
  15747. var mipSlices = 3;
  15748. var gl = _this._gl;
  15749. var width = loadData.width;
  15750. if (!width) {
  15751. return;
  15752. }
  15753. var textures = [];
  15754. for (var i = 0; i < mipSlices; i++) {
  15755. //compute LOD from even spacing in smoothness (matching shader calculation)
  15756. var smoothness = i / (mipSlices - 1);
  15757. var roughness = 1 - smoothness;
  15758. var minLODIndex = lodOffset; // roughness = 0
  15759. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15760. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15761. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15762. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15763. glTextureFromLod.isCube = true;
  15764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15769. if (loadData.isDDS) {
  15770. var info = loadData.info;
  15771. var data = loadData.data;
  15772. _this._unpackFlipY(info.isCompressed);
  15773. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15774. }
  15775. else {
  15776. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15777. }
  15778. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15779. // Wrap in a base texture for easy binding.
  15780. var lodTexture = new BABYLON.BaseTexture(scene);
  15781. lodTexture.isCube = true;
  15782. lodTexture._texture = glTextureFromLod;
  15783. glTextureFromLod.isReady = true;
  15784. textures.push(lodTexture);
  15785. }
  15786. texture._lodTextureHigh = textures[2];
  15787. texture._lodTextureMid = textures[1];
  15788. texture._lodTextureLow = textures[0];
  15789. if (onLoad) {
  15790. onLoad(texture);
  15791. }
  15792. };
  15793. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15794. };
  15795. /**
  15796. * Creates a cube texture
  15797. * @param rootUrl defines the url where the files to load is located
  15798. * @param scene defines the current scene
  15799. * @param files defines the list of files to load (1 per face)
  15800. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15801. * @param onLoad defines an optional callback raised when the texture is loaded
  15802. * @param onError defines an optional callback raised if there is an issue to load the texture
  15803. * @param format defines the format of the data
  15804. * @param forcedExtension defines the extension to use to pick the right loader
  15805. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15806. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15807. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15808. * @returns the cube texture as an InternalTexture
  15809. */
  15810. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15811. var _this = this;
  15812. if (onLoad === void 0) { onLoad = null; }
  15813. if (onError === void 0) { onError = null; }
  15814. if (forcedExtension === void 0) { forcedExtension = null; }
  15815. if (createPolynomials === void 0) { createPolynomials = false; }
  15816. if (lodScale === void 0) { lodScale = 0; }
  15817. if (lodOffset === void 0) { lodOffset = 0; }
  15818. var gl = this._gl;
  15819. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15820. texture.isCube = true;
  15821. texture.url = rootUrl;
  15822. texture.generateMipMaps = !noMipmap;
  15823. texture._lodGenerationScale = lodScale;
  15824. texture._lodGenerationOffset = lodOffset;
  15825. if (!this._doNotHandleContextLost) {
  15826. texture._extension = forcedExtension;
  15827. texture._files = files;
  15828. }
  15829. var isKTX = false;
  15830. var isDDS = false;
  15831. var isEnv = false;
  15832. var lastDot = rootUrl.lastIndexOf('.');
  15833. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15834. if (this._textureFormatInUse) {
  15835. extension = this._textureFormatInUse;
  15836. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15837. isKTX = true;
  15838. }
  15839. else {
  15840. isDDS = (extension === ".dds");
  15841. isEnv = (extension === ".env");
  15842. }
  15843. var onerror = function (request, exception) {
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. if (isKTX) {
  15849. this._loadFile(rootUrl, function (data) {
  15850. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15851. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15853. _this._unpackFlipY(true);
  15854. ktx.uploadLevels(_this._gl, !noMipmap);
  15855. _this.setCubeMapTextureParams(gl, loadMipmap);
  15856. texture.width = ktx.pixelWidth;
  15857. texture.height = ktx.pixelHeight;
  15858. texture.isReady = true;
  15859. }, undefined, undefined, true, onerror);
  15860. }
  15861. else if (isEnv) {
  15862. this._loadFile(rootUrl, function (data) {
  15863. data = data;
  15864. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15865. if (info) {
  15866. texture.width = info.width;
  15867. texture.height = info.width;
  15868. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15869. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15870. texture.isReady = true;
  15871. if (onLoad) {
  15872. onLoad();
  15873. }
  15874. });
  15875. }
  15876. else if (onError) {
  15877. onError("Can not parse the environment file", null);
  15878. }
  15879. }, undefined, undefined, true, onerror);
  15880. }
  15881. else if (isDDS) {
  15882. if (files && files.length === 6) {
  15883. this._cascadeLoadFiles(scene, function (imgs) {
  15884. var info;
  15885. var loadMipmap = false;
  15886. var width = 0;
  15887. for (var index = 0; index < imgs.length; index++) {
  15888. var data = imgs[index];
  15889. info = BABYLON.DDSTools.GetDDSInfo(data);
  15890. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15891. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15892. _this._unpackFlipY(info.isCompressed);
  15893. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15894. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15895. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15896. }
  15897. texture.width = info.width;
  15898. texture.height = info.height;
  15899. texture.type = info.textureType;
  15900. width = info.width;
  15901. }
  15902. _this.setCubeMapTextureParams(gl, loadMipmap);
  15903. texture.isReady = true;
  15904. if (onLoad) {
  15905. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15906. }
  15907. }, files, onError);
  15908. }
  15909. else {
  15910. this._loadFile(rootUrl, function (data) {
  15911. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15912. if (createPolynomials) {
  15913. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15914. }
  15915. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15917. _this._unpackFlipY(info.isCompressed);
  15918. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15919. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15920. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15921. }
  15922. _this.setCubeMapTextureParams(gl, loadMipmap);
  15923. texture.width = info.width;
  15924. texture.height = info.height;
  15925. texture.isReady = true;
  15926. texture.type = info.textureType;
  15927. if (onLoad) {
  15928. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15929. }
  15930. }, undefined, undefined, true, onerror);
  15931. }
  15932. }
  15933. else {
  15934. if (!files) {
  15935. throw new Error("Cannot load cubemap because files were not defined");
  15936. }
  15937. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15938. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15939. var height = width;
  15940. _this._prepareWorkingCanvas();
  15941. if (!_this._workingCanvas || !_this._workingContext) {
  15942. return;
  15943. }
  15944. _this._workingCanvas.width = width;
  15945. _this._workingCanvas.height = height;
  15946. var faces = [
  15947. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15948. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15949. ];
  15950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15951. _this._unpackFlipY(false);
  15952. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15953. for (var index = 0; index < faces.length; index++) {
  15954. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15955. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15956. }
  15957. if (!noMipmap) {
  15958. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15959. }
  15960. _this.setCubeMapTextureParams(gl, !noMipmap);
  15961. texture.width = width;
  15962. texture.height = height;
  15963. texture.isReady = true;
  15964. if (format) {
  15965. texture.format = format;
  15966. }
  15967. texture.onLoadedObservable.notifyObservers(texture);
  15968. texture.onLoadedObservable.clear();
  15969. if (onLoad) {
  15970. onLoad();
  15971. }
  15972. }, files, onError);
  15973. }
  15974. this._internalTexturesCache.push(texture);
  15975. return texture;
  15976. };
  15977. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15983. // this.resetTextureCache();
  15984. };
  15985. /**
  15986. * Update a raw cube texture
  15987. * @param texture defines the texture to udpdate
  15988. * @param data defines the data to store
  15989. * @param format defines the data format
  15990. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15991. * @param invertY defines if data must be stored with Y axis inverted
  15992. * @param compression defines the compression used (null by default)
  15993. * @param level defines which level of the texture to update
  15994. */
  15995. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15996. if (compression === void 0) { compression = null; }
  15997. if (level === void 0) { level = 0; }
  15998. texture._bufferViewArray = data;
  15999. texture.format = format;
  16000. texture.type = type;
  16001. texture.invertY = invertY;
  16002. texture._compression = compression;
  16003. var gl = this._gl;
  16004. var textureType = this._getWebGLTextureType(type);
  16005. var internalFormat = this._getInternalFormat(format);
  16006. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16007. var needConversion = false;
  16008. if (internalFormat === gl.RGB) {
  16009. internalFormat = gl.RGBA;
  16010. needConversion = true;
  16011. }
  16012. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16013. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16014. if (texture.width % 4 !== 0) {
  16015. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16016. }
  16017. // Data are known to be in +X +Y +Z -X -Y -Z
  16018. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16019. var faceData = data[faceIndex];
  16020. if (compression) {
  16021. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16022. }
  16023. else {
  16024. if (needConversion) {
  16025. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16026. }
  16027. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16028. }
  16029. }
  16030. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16031. if (isPot && texture.generateMipMaps && level === 0) {
  16032. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16033. }
  16034. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16035. // this.resetTextureCache();
  16036. texture.isReady = true;
  16037. };
  16038. /**
  16039. * Creates a new raw cube texture
  16040. * @param data defines the array of data to use to create each face
  16041. * @param size defines the size of the textures
  16042. * @param format defines the format of the data
  16043. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16044. * @param generateMipMaps defines if the engine should generate the mip levels
  16045. * @param invertY defines if data must be stored with Y axis inverted
  16046. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16047. * @param compression defines the compression used (null by default)
  16048. * @returns the cube texture as an InternalTexture
  16049. */
  16050. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16051. if (compression === void 0) { compression = null; }
  16052. var gl = this._gl;
  16053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16054. texture.isCube = true;
  16055. texture.generateMipMaps = generateMipMaps;
  16056. texture.format = format;
  16057. texture.type = type;
  16058. if (!this._doNotHandleContextLost) {
  16059. texture._bufferViewArray = data;
  16060. }
  16061. var textureType = this._getWebGLTextureType(type);
  16062. var internalFormat = this._getInternalFormat(format);
  16063. if (internalFormat === gl.RGB) {
  16064. internalFormat = gl.RGBA;
  16065. }
  16066. var width = size;
  16067. var height = width;
  16068. texture.width = width;
  16069. texture.height = height;
  16070. // Double check on POT to generate Mips.
  16071. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16072. if (!isPot) {
  16073. generateMipMaps = false;
  16074. }
  16075. // Upload data if needed. The texture won't be ready until then.
  16076. if (data) {
  16077. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16078. }
  16079. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16080. // Filters
  16081. if (data && generateMipMaps) {
  16082. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16083. }
  16084. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16087. }
  16088. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16089. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16091. }
  16092. else {
  16093. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16096. }
  16097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16099. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16100. return texture;
  16101. };
  16102. /**
  16103. * Creates a new raw cube texture from a specified url
  16104. * @param url defines the url where the data is located
  16105. * @param scene defines the current scene
  16106. * @param size defines the size of the textures
  16107. * @param format defines the format of the data
  16108. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16109. * @param noMipmap defines if the engine should avoid generating the mip levels
  16110. * @param callback defines a callback used to extract texture data from loaded data
  16111. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16112. * @param onLoad defines a callback called when texture is loaded
  16113. * @param onError defines a callback called if there is an error
  16114. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16115. * @param invertY defines if data must be stored with Y axis inverted
  16116. * @returns the cube texture as an InternalTexture
  16117. */
  16118. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16119. var _this = this;
  16120. if (onLoad === void 0) { onLoad = null; }
  16121. if (onError === void 0) { onError = null; }
  16122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16123. if (invertY === void 0) { invertY = false; }
  16124. var gl = this._gl;
  16125. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16126. scene._addPendingData(texture);
  16127. texture.url = url;
  16128. this._internalTexturesCache.push(texture);
  16129. var onerror = function (request, exception) {
  16130. scene._removePendingData(texture);
  16131. if (onError && request) {
  16132. onError(request.status + " " + request.statusText, exception);
  16133. }
  16134. };
  16135. var internalCallback = function (data) {
  16136. var width = texture.width;
  16137. var faceDataArrays = callback(data);
  16138. if (!faceDataArrays) {
  16139. return;
  16140. }
  16141. if (mipmapGenerator) {
  16142. var textureType = _this._getWebGLTextureType(type);
  16143. var internalFormat = _this._getInternalFormat(format);
  16144. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16145. var needConversion = false;
  16146. if (internalFormat === gl.RGB) {
  16147. internalFormat = gl.RGBA;
  16148. needConversion = true;
  16149. }
  16150. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16151. _this._unpackFlipY(false);
  16152. var mipData = mipmapGenerator(faceDataArrays);
  16153. for (var level = 0; level < mipData.length; level++) {
  16154. var mipSize = width >> level;
  16155. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16156. var mipFaceData = mipData[level][faceIndex];
  16157. if (needConversion) {
  16158. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16159. }
  16160. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16161. }
  16162. }
  16163. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16164. }
  16165. else {
  16166. texture.generateMipMaps = !noMipmap;
  16167. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16168. }
  16169. texture.isReady = true;
  16170. // this.resetTextureCache();
  16171. scene._removePendingData(texture);
  16172. if (onLoad) {
  16173. onLoad();
  16174. }
  16175. };
  16176. this._loadFile(url, function (data) {
  16177. internalCallback(data);
  16178. }, undefined, scene.database, true, onerror);
  16179. return texture;
  16180. };
  16181. ;
  16182. /**
  16183. * Update a raw 3D texture
  16184. * @param texture defines the texture to update
  16185. * @param data defines the data to store
  16186. * @param format defines the data format
  16187. * @param invertY defines if data must be stored with Y axis inverted
  16188. * @param compression defines the used compression (can be null)
  16189. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16190. */
  16191. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16192. if (compression === void 0) { compression = null; }
  16193. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16194. var internalType = this._getWebGLTextureType(textureType);
  16195. var internalFormat = this._getInternalFormat(format);
  16196. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16197. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16198. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16199. if (!this._doNotHandleContextLost) {
  16200. texture._bufferView = data;
  16201. texture.format = format;
  16202. texture.invertY = invertY;
  16203. texture._compression = compression;
  16204. }
  16205. if (texture.width % 4 !== 0) {
  16206. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16207. }
  16208. if (compression && data) {
  16209. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16210. }
  16211. else {
  16212. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16213. }
  16214. if (texture.generateMipMaps) {
  16215. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16216. }
  16217. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16218. // this.resetTextureCache();
  16219. texture.isReady = true;
  16220. };
  16221. /**
  16222. * Creates a new raw 3D texture
  16223. * @param data defines the data used to create the texture
  16224. * @param width defines the width of the texture
  16225. * @param height defines the height of the texture
  16226. * @param depth defines the depth of the texture
  16227. * @param format defines the format of the texture
  16228. * @param generateMipMaps defines if the engine must generate mip levels
  16229. * @param invertY defines if data must be stored with Y axis inverted
  16230. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16231. * @param compression defines the compressed used (can be null)
  16232. * @param textureType defines the compressed used (can be null)
  16233. * @returns a new raw 3D texture (stored in an InternalTexture)
  16234. */
  16235. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16236. if (compression === void 0) { compression = null; }
  16237. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16238. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16239. texture.baseWidth = width;
  16240. texture.baseHeight = height;
  16241. texture.baseDepth = depth;
  16242. texture.width = width;
  16243. texture.height = height;
  16244. texture.depth = depth;
  16245. texture.format = format;
  16246. texture.type = textureType;
  16247. texture.generateMipMaps = generateMipMaps;
  16248. texture.samplingMode = samplingMode;
  16249. texture.is3D = true;
  16250. if (!this._doNotHandleContextLost) {
  16251. texture._bufferView = data;
  16252. }
  16253. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16254. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16255. // Filters
  16256. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16257. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16258. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16259. if (generateMipMaps) {
  16260. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16261. }
  16262. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16263. this._internalTexturesCache.push(texture);
  16264. return texture;
  16265. };
  16266. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16267. var gl = this._gl;
  16268. if (!gl) {
  16269. return;
  16270. }
  16271. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16274. if (!noMipmap && !isCompressed) {
  16275. gl.generateMipmap(gl.TEXTURE_2D);
  16276. }
  16277. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16278. // this.resetTextureCache();
  16279. if (scene) {
  16280. scene._removePendingData(texture);
  16281. }
  16282. texture.onLoadedObservable.notifyObservers(texture);
  16283. texture.onLoadedObservable.clear();
  16284. };
  16285. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16286. var _this = this;
  16287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16288. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16289. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16290. var gl = this._gl;
  16291. if (!gl) {
  16292. return;
  16293. }
  16294. if (!texture._webGLTexture) {
  16295. // this.resetTextureCache();
  16296. if (scene) {
  16297. scene._removePendingData(texture);
  16298. }
  16299. return;
  16300. }
  16301. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16302. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16303. texture.baseWidth = width;
  16304. texture.baseHeight = height;
  16305. texture.width = potWidth;
  16306. texture.height = potHeight;
  16307. texture.isReady = true;
  16308. if (processFunction(potWidth, potHeight, function () {
  16309. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16310. })) {
  16311. // Returning as texture needs extra async steps
  16312. return;
  16313. }
  16314. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16315. };
  16316. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16317. // Create new RGBA data container.
  16318. var rgbaData;
  16319. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16320. rgbaData = new Float32Array(width * height * 4);
  16321. }
  16322. else {
  16323. rgbaData = new Uint32Array(width * height * 4);
  16324. }
  16325. // Convert each pixel.
  16326. for (var x = 0; x < width; x++) {
  16327. for (var y = 0; y < height; y++) {
  16328. var index = (y * width + x) * 3;
  16329. var newIndex = (y * width + x) * 4;
  16330. // Map Old Value to new value.
  16331. rgbaData[newIndex + 0] = rgbData[index + 0];
  16332. rgbaData[newIndex + 1] = rgbData[index + 1];
  16333. rgbaData[newIndex + 2] = rgbData[index + 2];
  16334. // Add fully opaque alpha channel.
  16335. rgbaData[newIndex + 3] = 1;
  16336. }
  16337. }
  16338. return rgbaData;
  16339. };
  16340. /** @hidden */
  16341. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16342. var gl = this._gl;
  16343. if (texture._framebuffer) {
  16344. gl.deleteFramebuffer(texture._framebuffer);
  16345. texture._framebuffer = null;
  16346. }
  16347. if (texture._depthStencilBuffer) {
  16348. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16349. texture._depthStencilBuffer = null;
  16350. }
  16351. if (texture._MSAAFramebuffer) {
  16352. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16353. texture._MSAAFramebuffer = null;
  16354. }
  16355. if (texture._MSAARenderBuffer) {
  16356. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16357. texture._MSAARenderBuffer = null;
  16358. }
  16359. };
  16360. /** @hidden */
  16361. Engine.prototype._releaseTexture = function (texture) {
  16362. var gl = this._gl;
  16363. this._releaseFramebufferObjects(texture);
  16364. gl.deleteTexture(texture._webGLTexture);
  16365. // Unbind channels
  16366. this.unbindAllTextures();
  16367. var index = this._internalTexturesCache.indexOf(texture);
  16368. if (index !== -1) {
  16369. this._internalTexturesCache.splice(index, 1);
  16370. }
  16371. // Integrated fixed lod samplers.
  16372. if (texture._lodTextureHigh) {
  16373. texture._lodTextureHigh.dispose();
  16374. }
  16375. if (texture._lodTextureMid) {
  16376. texture._lodTextureMid.dispose();
  16377. }
  16378. if (texture._lodTextureLow) {
  16379. texture._lodTextureLow.dispose();
  16380. }
  16381. // Set output texture of post process to null if the texture has been released/disposed
  16382. this.scenes.forEach(function (scene) {
  16383. scene.postProcesses.forEach(function (postProcess) {
  16384. if (postProcess._outputTexture == texture) {
  16385. postProcess._outputTexture = null;
  16386. }
  16387. });
  16388. scene.cameras.forEach(function (camera) {
  16389. camera._postProcesses.forEach(function (postProcess) {
  16390. if (postProcess) {
  16391. if (postProcess._outputTexture == texture) {
  16392. postProcess._outputTexture = null;
  16393. }
  16394. }
  16395. });
  16396. });
  16397. });
  16398. };
  16399. Engine.prototype.setProgram = function (program) {
  16400. if (this._currentProgram !== program) {
  16401. this._gl.useProgram(program);
  16402. this._currentProgram = program;
  16403. }
  16404. };
  16405. /**
  16406. * Binds an effect to the webGL context
  16407. * @param effect defines the effect to bind
  16408. */
  16409. Engine.prototype.bindSamplers = function (effect) {
  16410. this.setProgram(effect.getProgram());
  16411. var samplers = effect.getSamplers();
  16412. for (var index = 0; index < samplers.length; index++) {
  16413. var uniform = effect.getUniform(samplers[index]);
  16414. if (uniform) {
  16415. this._boundUniforms[index] = uniform;
  16416. }
  16417. }
  16418. this._currentEffect = null;
  16419. };
  16420. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16421. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16422. return;
  16423. }
  16424. // Remove
  16425. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16426. // Bind last to it
  16427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16428. // Bind to dummy
  16429. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16430. };
  16431. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16432. if (!internalTexture) {
  16433. return -1;
  16434. }
  16435. internalTexture._initialSlot = channel;
  16436. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16437. if (channel !== internalTexture._designatedSlot) {
  16438. this._textureCollisions.addCount(1, false);
  16439. }
  16440. }
  16441. else {
  16442. if (channel !== internalTexture._designatedSlot) {
  16443. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16444. return internalTexture._designatedSlot;
  16445. }
  16446. else {
  16447. // No slot for this texture, let's pick a new one (if we find a free slot)
  16448. if (this._nextFreeTextureSlots.length) {
  16449. return this._nextFreeTextureSlots[0];
  16450. }
  16451. // We need to recycle the oldest bound texture, sorry.
  16452. this._textureCollisions.addCount(1, false);
  16453. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16454. }
  16455. }
  16456. }
  16457. return channel;
  16458. };
  16459. Engine.prototype._linkTrackers = function (previous, next) {
  16460. previous.next = next;
  16461. next.previous = previous;
  16462. };
  16463. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16464. var currentSlot = internalTexture._designatedSlot;
  16465. if (currentSlot === -1) {
  16466. return -1;
  16467. }
  16468. internalTexture._designatedSlot = -1;
  16469. if (this.disableTextureBindingOptimization) {
  16470. return -1;
  16471. }
  16472. // Remove from bound list
  16473. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16474. // Free the slot
  16475. this._boundTexturesCache[currentSlot] = null;
  16476. this._nextFreeTextureSlots.push(currentSlot);
  16477. return currentSlot;
  16478. };
  16479. Engine.prototype._activateCurrentTexture = function () {
  16480. if (this._currentTextureChannel !== this._activeChannel) {
  16481. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16482. this._currentTextureChannel = this._activeChannel;
  16483. }
  16484. };
  16485. /** @hidden */
  16486. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16487. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16488. if (force === void 0) { force = false; }
  16489. var wasPreviouslyBound = false;
  16490. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16491. this._activeChannel = texture._designatedSlot;
  16492. }
  16493. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16494. var isTextureForRendering = texture && texture._initialSlot > -1;
  16495. if (currentTextureBound !== texture || force) {
  16496. if (currentTextureBound) {
  16497. this._removeDesignatedSlot(currentTextureBound);
  16498. }
  16499. this._activateCurrentTexture();
  16500. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16501. this._boundTexturesCache[this._activeChannel] = texture;
  16502. if (texture) {
  16503. if (!this.disableTextureBindingOptimization) {
  16504. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16505. if (slotIndex > -1) {
  16506. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16507. }
  16508. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16509. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16510. }
  16511. texture._designatedSlot = this._activeChannel;
  16512. }
  16513. }
  16514. else if (forTextureDataUpdate) {
  16515. wasPreviouslyBound = true;
  16516. this._activateCurrentTexture();
  16517. }
  16518. if (isTextureForRendering && !forTextureDataUpdate) {
  16519. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16520. }
  16521. return wasPreviouslyBound;
  16522. };
  16523. /** @hidden */
  16524. Engine.prototype._bindTexture = function (channel, texture) {
  16525. if (channel < 0) {
  16526. return;
  16527. }
  16528. if (texture) {
  16529. channel = this._getCorrectTextureChannel(channel, texture);
  16530. }
  16531. this._activeChannel = channel;
  16532. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16533. };
  16534. /**
  16535. * Sets a texture to the webGL context from a postprocess
  16536. * @param channel defines the channel to use
  16537. * @param postProcess defines the source postprocess
  16538. */
  16539. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16540. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16541. };
  16542. /**
  16543. * Binds the output of the passed in post process to the texture channel specified
  16544. * @param channel The channel the texture should be bound to
  16545. * @param postProcess The post process which's output should be bound
  16546. */
  16547. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16548. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16549. };
  16550. /**
  16551. * Unbind all textures from the webGL context
  16552. */
  16553. Engine.prototype.unbindAllTextures = function () {
  16554. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16555. this._activeChannel = channel;
  16556. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16557. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16558. if (this.webGLVersion > 1) {
  16559. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16560. }
  16561. }
  16562. };
  16563. /**
  16564. * Sets a texture to the according uniform.
  16565. * @param channel The texture channel
  16566. * @param uniform The uniform to set
  16567. * @param texture The texture to apply
  16568. */
  16569. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16570. if (channel < 0) {
  16571. return;
  16572. }
  16573. if (uniform) {
  16574. this._boundUniforms[channel] = uniform;
  16575. }
  16576. this._setTexture(channel, texture);
  16577. };
  16578. /**
  16579. * Sets a depth stencil texture from a render target to the according uniform.
  16580. * @param channel The texture channel
  16581. * @param uniform The uniform to set
  16582. * @param texture The render target texture containing the depth stencil texture to apply
  16583. */
  16584. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16585. if (channel < 0) {
  16586. return;
  16587. }
  16588. if (uniform) {
  16589. this._boundUniforms[channel] = uniform;
  16590. }
  16591. if (!texture || !texture.depthStencilTexture) {
  16592. this._setTexture(channel, null);
  16593. }
  16594. else {
  16595. this._setTexture(channel, texture, false, true);
  16596. }
  16597. };
  16598. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16599. var uniform = this._boundUniforms[sourceSlot];
  16600. if (uniform._currentState === destination) {
  16601. return;
  16602. }
  16603. this._gl.uniform1i(uniform, destination);
  16604. uniform._currentState = destination;
  16605. };
  16606. Engine.prototype._getTextureWrapMode = function (mode) {
  16607. switch (mode) {
  16608. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16609. return this._gl.REPEAT;
  16610. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16611. return this._gl.CLAMP_TO_EDGE;
  16612. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16613. return this._gl.MIRRORED_REPEAT;
  16614. }
  16615. return this._gl.REPEAT;
  16616. };
  16617. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16618. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16619. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16620. // Not ready?
  16621. if (!texture) {
  16622. if (this._boundTexturesCache[channel] != null) {
  16623. this._activeChannel = channel;
  16624. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16625. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16626. if (this.webGLVersion > 1) {
  16627. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16628. }
  16629. }
  16630. return false;
  16631. }
  16632. // Video
  16633. if (texture.video) {
  16634. this._activeChannel = channel;
  16635. texture.update();
  16636. }
  16637. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16638. texture.delayLoad();
  16639. return false;
  16640. }
  16641. var internalTexture;
  16642. if (depthStencilTexture) {
  16643. internalTexture = texture.depthStencilTexture;
  16644. }
  16645. else if (texture.isReady()) {
  16646. internalTexture = texture.getInternalTexture();
  16647. }
  16648. else if (texture.isCube) {
  16649. internalTexture = this.emptyCubeTexture;
  16650. }
  16651. else if (texture.is3D) {
  16652. internalTexture = this.emptyTexture3D;
  16653. }
  16654. else {
  16655. internalTexture = this.emptyTexture;
  16656. }
  16657. if (!isPartOfTextureArray) {
  16658. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16659. }
  16660. var needToBind = true;
  16661. if (this._boundTexturesCache[channel] === internalTexture) {
  16662. this._moveBoundTextureOnTop(internalTexture);
  16663. if (!isPartOfTextureArray) {
  16664. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16665. }
  16666. needToBind = false;
  16667. }
  16668. this._activeChannel = channel;
  16669. if (internalTexture && internalTexture.is3D) {
  16670. if (needToBind) {
  16671. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16672. }
  16673. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16674. internalTexture._cachedWrapU = texture.wrapU;
  16675. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16676. }
  16677. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16678. internalTexture._cachedWrapV = texture.wrapV;
  16679. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16680. }
  16681. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16682. internalTexture._cachedWrapR = texture.wrapR;
  16683. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16684. }
  16685. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16686. }
  16687. else if (internalTexture && internalTexture.isCube) {
  16688. if (needToBind) {
  16689. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16690. }
  16691. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16692. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16693. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16694. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16695. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16696. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16697. }
  16698. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16699. }
  16700. else {
  16701. if (needToBind) {
  16702. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16703. }
  16704. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16705. internalTexture._cachedWrapU = texture.wrapU;
  16706. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16707. }
  16708. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16709. internalTexture._cachedWrapV = texture.wrapV;
  16710. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16711. }
  16712. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16713. }
  16714. return true;
  16715. };
  16716. /**
  16717. * Sets an array of texture to the webGL context
  16718. * @param channel defines the channel where the texture array must be set
  16719. * @param uniform defines the associated uniform location
  16720. * @param textures defines the array of textures to bind
  16721. */
  16722. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16723. if (channel < 0 || !uniform) {
  16724. return;
  16725. }
  16726. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16727. this._textureUnits = new Int32Array(textures.length);
  16728. }
  16729. for (var i = 0; i < textures.length; i++) {
  16730. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16731. }
  16732. this._gl.uniform1iv(uniform, this._textureUnits);
  16733. for (var index = 0; index < textures.length; index++) {
  16734. this._setTexture(this._textureUnits[index], textures[index], true);
  16735. }
  16736. };
  16737. /** @hidden */
  16738. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16739. var internalTexture = texture.getInternalTexture();
  16740. if (!internalTexture) {
  16741. return;
  16742. }
  16743. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16744. var value = texture.anisotropicFilteringLevel;
  16745. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16746. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16747. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16748. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16749. }
  16750. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16751. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16752. internalTexture._cachedAnisotropicFilteringLevel = value;
  16753. }
  16754. };
  16755. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16756. this._bindTextureDirectly(target, texture, true, true);
  16757. this._gl.texParameterf(target, parameter, value);
  16758. };
  16759. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16760. if (texture) {
  16761. this._bindTextureDirectly(target, texture, true, true);
  16762. }
  16763. this._gl.texParameteri(target, parameter, value);
  16764. };
  16765. /**
  16766. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16767. * @param x defines the x coordinate of the rectangle where pixels must be read
  16768. * @param y defines the y coordinate of the rectangle where pixels must be read
  16769. * @param width defines the width of the rectangle where pixels must be read
  16770. * @param height defines the height of the rectangle where pixels must be read
  16771. * @returns a Uint8Array containing RGBA colors
  16772. */
  16773. Engine.prototype.readPixels = function (x, y, width, height) {
  16774. var data = new Uint8Array(height * width * 4);
  16775. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16776. return data;
  16777. };
  16778. /**
  16779. * Add an externaly attached data from its key.
  16780. * This method call will fail and return false, if such key already exists.
  16781. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16782. * @param key the unique key that identifies the data
  16783. * @param data the data object to associate to the key for this Engine instance
  16784. * @return true if no such key were already present and the data was added successfully, false otherwise
  16785. */
  16786. Engine.prototype.addExternalData = function (key, data) {
  16787. if (!this._externalData) {
  16788. this._externalData = new BABYLON.StringDictionary();
  16789. }
  16790. return this._externalData.add(key, data);
  16791. };
  16792. /**
  16793. * Get an externaly attached data from its key
  16794. * @param key the unique key that identifies the data
  16795. * @return the associated data, if present (can be null), or undefined if not present
  16796. */
  16797. Engine.prototype.getExternalData = function (key) {
  16798. if (!this._externalData) {
  16799. this._externalData = new BABYLON.StringDictionary();
  16800. }
  16801. return this._externalData.get(key);
  16802. };
  16803. /**
  16804. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16805. * @param key the unique key that identifies the data
  16806. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16807. * @return the associated data, can be null if the factory returned null.
  16808. */
  16809. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16810. if (!this._externalData) {
  16811. this._externalData = new BABYLON.StringDictionary();
  16812. }
  16813. return this._externalData.getOrAddWithFactory(key, factory);
  16814. };
  16815. /**
  16816. * Remove an externaly attached data from the Engine instance
  16817. * @param key the unique key that identifies the data
  16818. * @return true if the data was successfully removed, false if it doesn't exist
  16819. */
  16820. Engine.prototype.removeExternalData = function (key) {
  16821. if (!this._externalData) {
  16822. this._externalData = new BABYLON.StringDictionary();
  16823. }
  16824. return this._externalData.remove(key);
  16825. };
  16826. /**
  16827. * Unbind all vertex attributes from the webGL context
  16828. */
  16829. Engine.prototype.unbindAllAttributes = function () {
  16830. if (this._mustWipeVertexAttributes) {
  16831. this._mustWipeVertexAttributes = false;
  16832. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16833. this._gl.disableVertexAttribArray(i);
  16834. this._vertexAttribArraysEnabled[i] = false;
  16835. this._currentBufferPointers[i].active = false;
  16836. }
  16837. return;
  16838. }
  16839. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16840. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16841. continue;
  16842. }
  16843. this._gl.disableVertexAttribArray(i);
  16844. this._vertexAttribArraysEnabled[i] = false;
  16845. this._currentBufferPointers[i].active = false;
  16846. }
  16847. };
  16848. /**
  16849. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16850. */
  16851. Engine.prototype.releaseEffects = function () {
  16852. for (var name in this._compiledEffects) {
  16853. this._deleteProgram(this._compiledEffects[name]._program);
  16854. }
  16855. this._compiledEffects = {};
  16856. };
  16857. /**
  16858. * Dispose and release all associated resources
  16859. */
  16860. Engine.prototype.dispose = function () {
  16861. this.hideLoadingUI();
  16862. this.stopRenderLoop();
  16863. // Release postProcesses
  16864. while (this.postProcesses.length) {
  16865. this.postProcesses[0].dispose();
  16866. }
  16867. // Empty texture
  16868. if (this._emptyTexture) {
  16869. this._releaseTexture(this._emptyTexture);
  16870. this._emptyTexture = null;
  16871. }
  16872. if (this._emptyCubeTexture) {
  16873. this._releaseTexture(this._emptyCubeTexture);
  16874. this._emptyCubeTexture = null;
  16875. }
  16876. // Rescale PP
  16877. if (this._rescalePostProcess) {
  16878. this._rescalePostProcess.dispose();
  16879. }
  16880. // Release scenes
  16881. while (this.scenes.length) {
  16882. this.scenes[0].dispose();
  16883. }
  16884. // Release audio engine
  16885. if (Engine.audioEngine) {
  16886. Engine.audioEngine.dispose();
  16887. }
  16888. // Release effects
  16889. this.releaseEffects();
  16890. // Unbind
  16891. this.unbindAllAttributes();
  16892. this._boundUniforms = [];
  16893. if (this._dummyFramebuffer) {
  16894. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16895. }
  16896. //WebVR
  16897. this.disableVR();
  16898. // Events
  16899. if (BABYLON.Tools.IsWindowObjectExist()) {
  16900. window.removeEventListener("blur", this._onBlur);
  16901. window.removeEventListener("focus", this._onFocus);
  16902. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16903. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16904. if (this._renderingCanvas) {
  16905. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16906. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16907. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16908. if (!this._doNotHandleContextLost) {
  16909. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16910. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16911. }
  16912. }
  16913. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16914. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16915. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16916. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16917. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16918. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16919. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16920. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16921. if (this._onVrDisplayConnect) {
  16922. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16923. if (this._onVrDisplayDisconnect) {
  16924. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16925. }
  16926. if (this._onVrDisplayPresentChange) {
  16927. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16928. }
  16929. this._onVrDisplayConnect = null;
  16930. this._onVrDisplayDisconnect = null;
  16931. }
  16932. }
  16933. // Remove from Instances
  16934. var index = Engine.Instances.indexOf(this);
  16935. if (index >= 0) {
  16936. Engine.Instances.splice(index, 1);
  16937. }
  16938. this._workingCanvas = null;
  16939. this._workingContext = null;
  16940. this._currentBufferPointers = [];
  16941. this._renderingCanvas = null;
  16942. this._currentProgram = null;
  16943. this._bindedRenderFunction = null;
  16944. this.onResizeObservable.clear();
  16945. this.onCanvasBlurObservable.clear();
  16946. this.onCanvasFocusObservable.clear();
  16947. this.onCanvasPointerOutObservable.clear();
  16948. this.onBeginFrameObservable.clear();
  16949. this.onEndFrameObservable.clear();
  16950. BABYLON.Effect.ResetCache();
  16951. // Abort active requests
  16952. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16953. var request = _a[_i];
  16954. request.abort();
  16955. }
  16956. };
  16957. // Loading screen
  16958. /**
  16959. * Display the loading screen
  16960. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16961. */
  16962. Engine.prototype.displayLoadingUI = function () {
  16963. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16964. return;
  16965. }
  16966. var loadingScreen = this.loadingScreen;
  16967. if (loadingScreen) {
  16968. loadingScreen.displayLoadingUI();
  16969. }
  16970. };
  16971. /**
  16972. * Hide the loading screen
  16973. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16974. */
  16975. Engine.prototype.hideLoadingUI = function () {
  16976. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16977. return;
  16978. }
  16979. var loadingScreen = this.loadingScreen;
  16980. if (loadingScreen) {
  16981. loadingScreen.hideLoadingUI();
  16982. }
  16983. };
  16984. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16985. /**
  16986. * Gets the current loading screen object
  16987. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16988. */
  16989. get: function () {
  16990. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16991. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16992. return this._loadingScreen;
  16993. },
  16994. /**
  16995. * Sets the current loading screen object
  16996. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16997. */
  16998. set: function (loadingScreen) {
  16999. this._loadingScreen = loadingScreen;
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17005. /**
  17006. * Sets the current loading screen text
  17007. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17008. */
  17009. set: function (text) {
  17010. this.loadingScreen.loadingUIText = text;
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17016. /**
  17017. * Sets the current loading screen background color
  17018. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17019. */
  17020. set: function (color) {
  17021. this.loadingScreen.loadingUIBackgroundColor = color;
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. /**
  17027. * Attach a new callback raised when context lost event is fired
  17028. * @param callback defines the callback to call
  17029. */
  17030. Engine.prototype.attachContextLostEvent = function (callback) {
  17031. if (this._renderingCanvas) {
  17032. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17033. }
  17034. };
  17035. /**
  17036. * Attach a new callback raised when context restored event is fired
  17037. * @param callback defines the callback to call
  17038. */
  17039. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17040. if (this._renderingCanvas) {
  17041. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17042. }
  17043. };
  17044. /**
  17045. * Gets the source code of the vertex shader associated with a specific webGL program
  17046. * @param program defines the program to use
  17047. * @returns a string containing the source code of the vertex shader associated with the program
  17048. */
  17049. Engine.prototype.getVertexShaderSource = function (program) {
  17050. var shaders = this._gl.getAttachedShaders(program);
  17051. if (!shaders) {
  17052. return null;
  17053. }
  17054. return this._gl.getShaderSource(shaders[0]);
  17055. };
  17056. /**
  17057. * Gets the source code of the fragment shader associated with a specific webGL program
  17058. * @param program defines the program to use
  17059. * @returns a string containing the source code of the fragment shader associated with the program
  17060. */
  17061. Engine.prototype.getFragmentShaderSource = function (program) {
  17062. var shaders = this._gl.getAttachedShaders(program);
  17063. if (!shaders) {
  17064. return null;
  17065. }
  17066. return this._gl.getShaderSource(shaders[1]);
  17067. };
  17068. /**
  17069. * Get the current error code of the webGL context
  17070. * @returns the error code
  17071. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17072. */
  17073. Engine.prototype.getError = function () {
  17074. return this._gl.getError();
  17075. };
  17076. // FPS
  17077. /**
  17078. * Gets the current framerate
  17079. * @returns a number representing the framerate
  17080. */
  17081. Engine.prototype.getFps = function () {
  17082. return this._fps;
  17083. };
  17084. /**
  17085. * Gets the time spent between current and previous frame
  17086. * @returns a number representing the delta time in ms
  17087. */
  17088. Engine.prototype.getDeltaTime = function () {
  17089. return this._deltaTime;
  17090. };
  17091. Engine.prototype._measureFps = function () {
  17092. this._performanceMonitor.sampleFrame();
  17093. this._fps = this._performanceMonitor.averageFPS;
  17094. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17095. };
  17096. /** @hidden */
  17097. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17098. if (faceIndex === void 0) { faceIndex = -1; }
  17099. if (level === void 0) { level = 0; }
  17100. var gl = this._gl;
  17101. if (!this._dummyFramebuffer) {
  17102. var dummy = gl.createFramebuffer();
  17103. if (!dummy) {
  17104. throw new Error("Unable to create dummy framebuffer");
  17105. }
  17106. this._dummyFramebuffer = dummy;
  17107. }
  17108. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17109. if (faceIndex > -1) {
  17110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17111. }
  17112. else {
  17113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17114. }
  17115. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17116. var buffer;
  17117. switch (readType) {
  17118. case gl.UNSIGNED_BYTE:
  17119. buffer = new Uint8Array(4 * width * height);
  17120. readType = gl.UNSIGNED_BYTE;
  17121. break;
  17122. default:
  17123. buffer = new Float32Array(4 * width * height);
  17124. readType = gl.FLOAT;
  17125. break;
  17126. }
  17127. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17128. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17129. return buffer;
  17130. };
  17131. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17132. if (this._webGLVersion > 1) {
  17133. return this._caps.colorBufferFloat;
  17134. }
  17135. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17136. };
  17137. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17138. if (this._webGLVersion > 1) {
  17139. return this._caps.colorBufferFloat;
  17140. }
  17141. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17142. };
  17143. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17144. Engine.prototype._canRenderToFramebuffer = function (type) {
  17145. var gl = this._gl;
  17146. //clear existing errors
  17147. while (gl.getError() !== gl.NO_ERROR) { }
  17148. var successful = true;
  17149. var texture = gl.createTexture();
  17150. gl.bindTexture(gl.TEXTURE_2D, texture);
  17151. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17154. var fb = gl.createFramebuffer();
  17155. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17157. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17158. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17159. successful = successful && (gl.getError() === gl.NO_ERROR);
  17160. //try render by clearing frame buffer's color buffer
  17161. if (successful) {
  17162. gl.clear(gl.COLOR_BUFFER_BIT);
  17163. successful = successful && (gl.getError() === gl.NO_ERROR);
  17164. }
  17165. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17166. if (successful) {
  17167. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17168. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17169. var readFormat = gl.RGBA;
  17170. var readType = gl.UNSIGNED_BYTE;
  17171. var buffer = new Uint8Array(4);
  17172. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17173. successful = successful && (gl.getError() === gl.NO_ERROR);
  17174. }
  17175. //clean up
  17176. gl.deleteTexture(texture);
  17177. gl.deleteFramebuffer(fb);
  17178. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17179. //clear accumulated errors
  17180. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17181. return successful;
  17182. };
  17183. /** @hidden */
  17184. Engine.prototype._getWebGLTextureType = function (type) {
  17185. if (type === Engine.TEXTURETYPE_FLOAT) {
  17186. return this._gl.FLOAT;
  17187. }
  17188. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17189. // Add Half Float Constant.
  17190. return this._gl.HALF_FLOAT_OES;
  17191. }
  17192. return this._gl.UNSIGNED_BYTE;
  17193. };
  17194. ;
  17195. Engine.prototype._getInternalFormat = function (format) {
  17196. var internalFormat = this._gl.RGBA;
  17197. switch (format) {
  17198. case Engine.TEXTUREFORMAT_ALPHA:
  17199. internalFormat = this._gl.ALPHA;
  17200. break;
  17201. case Engine.TEXTUREFORMAT_LUMINANCE:
  17202. internalFormat = this._gl.LUMINANCE;
  17203. break;
  17204. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17205. internalFormat = this._gl.LUMINANCE_ALPHA;
  17206. break;
  17207. case Engine.TEXTUREFORMAT_RGB:
  17208. internalFormat = this._gl.RGB;
  17209. break;
  17210. case Engine.TEXTUREFORMAT_RGBA:
  17211. internalFormat = this._gl.RGBA;
  17212. break;
  17213. case Engine.TEXTUREFORMAT_R:
  17214. internalFormat = this._gl.RED;
  17215. break;
  17216. case Engine.TEXTUREFORMAT_RG:
  17217. internalFormat = this._gl.RG;
  17218. break;
  17219. }
  17220. return internalFormat;
  17221. };
  17222. /** @hidden */
  17223. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17224. if (this._webGLVersion === 1) {
  17225. if (format !== undefined) {
  17226. switch (format) {
  17227. case Engine.TEXTUREFORMAT_LUMINANCE:
  17228. return this._gl.LUMINANCE;
  17229. case Engine.TEXTUREFORMAT_ALPHA:
  17230. return this._gl.ALPHA;
  17231. }
  17232. }
  17233. return this._gl.RGBA;
  17234. }
  17235. if (type === Engine.TEXTURETYPE_FLOAT) {
  17236. if (format !== undefined) {
  17237. switch (format) {
  17238. case Engine.TEXTUREFORMAT_R:
  17239. return this._gl.R32F;
  17240. case Engine.TEXTUREFORMAT_RG:
  17241. return this._gl.RG32F;
  17242. case Engine.TEXTUREFORMAT_RGB:
  17243. return this._gl.RGB32F;
  17244. }
  17245. }
  17246. return this._gl.RGBA32F;
  17247. }
  17248. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17249. if (format) {
  17250. switch (format) {
  17251. case Engine.TEXTUREFORMAT_R:
  17252. return this._gl.R16F;
  17253. case Engine.TEXTUREFORMAT_RG:
  17254. return this._gl.RG16F;
  17255. case Engine.TEXTUREFORMAT_RGB:
  17256. return this._gl.RGB16F;
  17257. }
  17258. }
  17259. return this._gl.RGBA16F;
  17260. }
  17261. if (format !== undefined) {
  17262. switch (format) {
  17263. case Engine.TEXTUREFORMAT_LUMINANCE:
  17264. return this._gl.LUMINANCE;
  17265. case Engine.TEXTUREFORMAT_RGB:
  17266. return this._gl.RGB;
  17267. case Engine.TEXTUREFORMAT_R:
  17268. return this._gl.R8;
  17269. case Engine.TEXTUREFORMAT_RG:
  17270. return this._gl.RG8;
  17271. case Engine.TEXTUREFORMAT_ALPHA:
  17272. return this._gl.ALPHA;
  17273. }
  17274. }
  17275. return this._gl.RGBA;
  17276. };
  17277. ;
  17278. /** @hidden */
  17279. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17280. if (type === Engine.TEXTURETYPE_FLOAT) {
  17281. return this._gl.RGBA32F;
  17282. }
  17283. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17284. return this._gl.RGBA16F;
  17285. }
  17286. return this._gl.RGBA8;
  17287. };
  17288. ;
  17289. /**
  17290. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17291. * @return the new query
  17292. */
  17293. Engine.prototype.createQuery = function () {
  17294. return this._gl.createQuery();
  17295. };
  17296. /**
  17297. * Delete and release a webGL query
  17298. * @param query defines the query to delete
  17299. * @return the current engine
  17300. */
  17301. Engine.prototype.deleteQuery = function (query) {
  17302. this._gl.deleteQuery(query);
  17303. return this;
  17304. };
  17305. /**
  17306. * Check if a given query has resolved and got its value
  17307. * @param query defines the query to check
  17308. * @returns true if the query got its value
  17309. */
  17310. Engine.prototype.isQueryResultAvailable = function (query) {
  17311. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17312. };
  17313. /**
  17314. * Gets the value of a given query
  17315. * @param query defines the query to check
  17316. * @returns the value of the query
  17317. */
  17318. Engine.prototype.getQueryResult = function (query) {
  17319. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17320. };
  17321. /**
  17322. * Initiates an occlusion query
  17323. * @param algorithmType defines the algorithm to use
  17324. * @param query defines the query to use
  17325. * @returns the current engine
  17326. * @see http://doc.babylonjs.com/features/occlusionquery
  17327. */
  17328. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17329. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17330. this._gl.beginQuery(glAlgorithm, query);
  17331. return this;
  17332. };
  17333. /**
  17334. * Ends an occlusion query
  17335. * @see http://doc.babylonjs.com/features/occlusionquery
  17336. * @param algorithmType defines the algorithm to use
  17337. * @returns the current engine
  17338. */
  17339. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17340. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17341. this._gl.endQuery(glAlgorithm);
  17342. return this;
  17343. };
  17344. /* Time queries */
  17345. Engine.prototype._createTimeQuery = function () {
  17346. var timerQuery = this._caps.timerQuery;
  17347. if (timerQuery.createQueryEXT) {
  17348. return timerQuery.createQueryEXT();
  17349. }
  17350. return this.createQuery();
  17351. };
  17352. Engine.prototype._deleteTimeQuery = function (query) {
  17353. var timerQuery = this._caps.timerQuery;
  17354. if (timerQuery.deleteQueryEXT) {
  17355. timerQuery.deleteQueryEXT(query);
  17356. return;
  17357. }
  17358. this.deleteQuery(query);
  17359. };
  17360. Engine.prototype._getTimeQueryResult = function (query) {
  17361. var timerQuery = this._caps.timerQuery;
  17362. if (timerQuery.getQueryObjectEXT) {
  17363. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17364. }
  17365. return this.getQueryResult(query);
  17366. };
  17367. Engine.prototype._getTimeQueryAvailability = function (query) {
  17368. var timerQuery = this._caps.timerQuery;
  17369. if (timerQuery.getQueryObjectEXT) {
  17370. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17371. }
  17372. return this.isQueryResultAvailable(query);
  17373. };
  17374. /**
  17375. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17376. * Please note that only one query can be issued at a time
  17377. * @returns a time token used to track the time span
  17378. */
  17379. Engine.prototype.startTimeQuery = function () {
  17380. var timerQuery = this._caps.timerQuery;
  17381. if (!timerQuery) {
  17382. return null;
  17383. }
  17384. var token = new BABYLON._TimeToken();
  17385. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17386. if (this._caps.canUseTimestampForTimerQuery) {
  17387. token._startTimeQuery = this._createTimeQuery();
  17388. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17389. }
  17390. else {
  17391. if (this._currentNonTimestampToken) {
  17392. return this._currentNonTimestampToken;
  17393. }
  17394. token._timeElapsedQuery = this._createTimeQuery();
  17395. if (timerQuery.beginQueryEXT) {
  17396. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17397. }
  17398. else {
  17399. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17400. }
  17401. this._currentNonTimestampToken = token;
  17402. }
  17403. return token;
  17404. };
  17405. /**
  17406. * Ends a time query
  17407. * @param token defines the token used to measure the time span
  17408. * @returns the time spent (in ns)
  17409. */
  17410. Engine.prototype.endTimeQuery = function (token) {
  17411. var timerQuery = this._caps.timerQuery;
  17412. if (!timerQuery || !token) {
  17413. return -1;
  17414. }
  17415. if (this._caps.canUseTimestampForTimerQuery) {
  17416. if (!token._startTimeQuery) {
  17417. return -1;
  17418. }
  17419. if (!token._endTimeQuery) {
  17420. token._endTimeQuery = this._createTimeQuery();
  17421. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17422. }
  17423. }
  17424. else if (!token._timeElapsedQueryEnded) {
  17425. if (!token._timeElapsedQuery) {
  17426. return -1;
  17427. }
  17428. if (timerQuery.endQueryEXT) {
  17429. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17430. }
  17431. else {
  17432. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17433. }
  17434. token._timeElapsedQueryEnded = true;
  17435. }
  17436. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17437. var available = false;
  17438. if (token._endTimeQuery) {
  17439. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17440. }
  17441. else if (token._timeElapsedQuery) {
  17442. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17443. }
  17444. if (available && !disjoint) {
  17445. var result = 0;
  17446. if (this._caps.canUseTimestampForTimerQuery) {
  17447. if (!token._startTimeQuery || !token._endTimeQuery) {
  17448. return -1;
  17449. }
  17450. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17451. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17452. result = timeEnd - timeStart;
  17453. this._deleteTimeQuery(token._startTimeQuery);
  17454. this._deleteTimeQuery(token._endTimeQuery);
  17455. token._startTimeQuery = null;
  17456. token._endTimeQuery = null;
  17457. }
  17458. else {
  17459. if (!token._timeElapsedQuery) {
  17460. return -1;
  17461. }
  17462. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17463. this._deleteTimeQuery(token._timeElapsedQuery);
  17464. token._timeElapsedQuery = null;
  17465. token._timeElapsedQueryEnded = false;
  17466. this._currentNonTimestampToken = null;
  17467. }
  17468. return result;
  17469. }
  17470. return -1;
  17471. };
  17472. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17473. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17474. };
  17475. // Transform feedback
  17476. /**
  17477. * Creates a webGL transform feedback object
  17478. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17479. * @returns the webGL transform feedback object
  17480. */
  17481. Engine.prototype.createTransformFeedback = function () {
  17482. return this._gl.createTransformFeedback();
  17483. };
  17484. /**
  17485. * Delete a webGL transform feedback object
  17486. * @param value defines the webGL transform feedback object to delete
  17487. */
  17488. Engine.prototype.deleteTransformFeedback = function (value) {
  17489. this._gl.deleteTransformFeedback(value);
  17490. };
  17491. /**
  17492. * Bind a webGL transform feedback object to the webgl context
  17493. * @param value defines the webGL transform feedback object to bind
  17494. */
  17495. Engine.prototype.bindTransformFeedback = function (value) {
  17496. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17497. };
  17498. /**
  17499. * Begins a transform feedback operation
  17500. * @param usePoints defines if points or triangles must be used
  17501. */
  17502. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17503. if (usePoints === void 0) { usePoints = true; }
  17504. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17505. };
  17506. /**
  17507. * Ends a transform feedback operation
  17508. */
  17509. Engine.prototype.endTransformFeedback = function () {
  17510. this._gl.endTransformFeedback();
  17511. };
  17512. /**
  17513. * Specify the varyings to use with transform feedback
  17514. * @param program defines the associated webGL program
  17515. * @param value defines the list of strings representing the varying names
  17516. */
  17517. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17518. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17519. };
  17520. /**
  17521. * Bind a webGL buffer for a transform feedback operation
  17522. * @param value defines the webGL buffer to bind
  17523. */
  17524. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17525. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17526. };
  17527. /** @hidden */
  17528. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17529. var _this = this;
  17530. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17531. this._activeRequests.push(request);
  17532. request.onCompleteObservable.add(function (request) {
  17533. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17534. });
  17535. return request;
  17536. };
  17537. /** @hidden */
  17538. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17539. var _this = this;
  17540. return new Promise(function (resolve, reject) {
  17541. _this._loadFile(url, function (data) {
  17542. resolve(data);
  17543. }, undefined, database, useArrayBuffer, function (request, exception) {
  17544. reject(exception);
  17545. });
  17546. });
  17547. };
  17548. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17549. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17550. var onload = function (data) {
  17551. loadedFiles[index] = data;
  17552. loadedFiles._internalCount++;
  17553. if (loadedFiles._internalCount === 6) {
  17554. onfinish(loadedFiles);
  17555. }
  17556. };
  17557. var onerror = function (request, exception) {
  17558. if (onErrorCallBack && request) {
  17559. onErrorCallBack(request.status + " " + request.statusText, exception);
  17560. }
  17561. };
  17562. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17563. };
  17564. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17565. if (onError === void 0) { onError = null; }
  17566. var loadedFiles = [];
  17567. loadedFiles._internalCount = 0;
  17568. for (var index = 0; index < 6; index++) {
  17569. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17570. }
  17571. };
  17572. // Statics
  17573. /**
  17574. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17575. * @returns true if the engine can be created
  17576. * @ignorenaming
  17577. */
  17578. Engine.isSupported = function () {
  17579. try {
  17580. var tempcanvas = document.createElement("canvas");
  17581. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17582. return gl != null && !!window.WebGLRenderingContext;
  17583. }
  17584. catch (e) {
  17585. return false;
  17586. }
  17587. };
  17588. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17589. Engine.ExceptionList = [
  17590. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17591. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17592. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17593. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17594. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17595. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17596. ];
  17597. /** Gets the list of created engines */
  17598. Engine.Instances = new Array();
  17599. // Const statics
  17600. Engine._ALPHA_DISABLE = 0;
  17601. Engine._ALPHA_ADD = 1;
  17602. Engine._ALPHA_COMBINE = 2;
  17603. Engine._ALPHA_SUBTRACT = 3;
  17604. Engine._ALPHA_MULTIPLY = 4;
  17605. Engine._ALPHA_MAXIMIZED = 5;
  17606. Engine._ALPHA_ONEONE = 6;
  17607. Engine._ALPHA_PREMULTIPLIED = 7;
  17608. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17609. Engine._ALPHA_INTERPOLATE = 9;
  17610. Engine._ALPHA_SCREENMODE = 10;
  17611. Engine._DELAYLOADSTATE_NONE = 0;
  17612. Engine._DELAYLOADSTATE_LOADED = 1;
  17613. Engine._DELAYLOADSTATE_LOADING = 2;
  17614. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17615. Engine._TEXTUREFORMAT_ALPHA = 0;
  17616. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17617. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17618. Engine._TEXTUREFORMAT_RGB = 4;
  17619. Engine._TEXTUREFORMAT_RGBA = 5;
  17620. Engine._TEXTUREFORMAT_R = 6;
  17621. Engine._TEXTUREFORMAT_RG = 7;
  17622. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17623. Engine._TEXTURETYPE_FLOAT = 1;
  17624. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17625. // Depht or Stencil test Constants.
  17626. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17627. 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.
  17628. 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.
  17629. 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.
  17630. 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.
  17631. 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.
  17632. 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.
  17633. 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.
  17634. // Stencil Actions Constants.
  17635. Engine._KEEP = 0x1E00;
  17636. Engine._REPLACE = 0x1E01;
  17637. Engine._INCR = 0x1E02;
  17638. Engine._DECR = 0x1E03;
  17639. Engine._INVERT = 0x150A;
  17640. Engine._INCR_WRAP = 0x8507;
  17641. Engine._DECR_WRAP = 0x8508;
  17642. // Texture rescaling mode
  17643. Engine._SCALEMODE_FLOOR = 1;
  17644. Engine._SCALEMODE_NEAREST = 2;
  17645. Engine._SCALEMODE_CEILING = 3;
  17646. // Updatable statics so stick with vars here
  17647. /**
  17648. * Gets or sets the epsilon value used by collision engine
  17649. */
  17650. Engine.CollisionsEpsilon = 0.001;
  17651. /**
  17652. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17653. */
  17654. Engine.CodeRepository = "src/";
  17655. /**
  17656. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17657. */
  17658. Engine.ShadersRepository = "src/Shaders/";
  17659. return Engine;
  17660. }());
  17661. BABYLON.Engine = Engine;
  17662. })(BABYLON || (BABYLON = {}));
  17663. //# sourceMappingURL=babylon.engine.js.map
  17664. var BABYLON;
  17665. (function (BABYLON) {
  17666. /**
  17667. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17668. */
  17669. var Node = /** @class */ (function () {
  17670. /**
  17671. * Creates a new Node
  17672. * @param {string} name - the name and id to be given to this node
  17673. * @param {BABYLON.Scene} the scene this node will be added to
  17674. */
  17675. function Node(name, scene) {
  17676. if (scene === void 0) { scene = null; }
  17677. /**
  17678. * Gets or sets a string used to store user defined state for the node
  17679. */
  17680. this.state = "";
  17681. /**
  17682. * Gets or sets an object used to store user defined information for the node
  17683. */
  17684. this.metadata = null;
  17685. /**
  17686. * Gets or sets a boolean used to define if the node must be serialized
  17687. */
  17688. this.doNotSerialize = false;
  17689. /** @hidden */
  17690. this._isDisposed = false;
  17691. /**
  17692. * Gets a list of Animations associated with the node
  17693. */
  17694. this.animations = new Array();
  17695. this._ranges = {};
  17696. this._isEnabled = true;
  17697. this._isReady = true;
  17698. /** @hidden */
  17699. this._currentRenderId = -1;
  17700. this._parentRenderId = -1;
  17701. this._childRenderId = -1;
  17702. this._animationPropertiesOverride = null;
  17703. /**
  17704. * An event triggered when the mesh is disposed
  17705. */
  17706. this.onDisposeObservable = new BABYLON.Observable();
  17707. // Behaviors
  17708. this._behaviors = new Array();
  17709. this.name = name;
  17710. this.id = name;
  17711. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17712. this.uniqueId = this._scene.getUniqueId();
  17713. this._initCache();
  17714. }
  17715. /**
  17716. * Gets a boolean indicating if the node has been disposed
  17717. * @returns true if the node was disposed
  17718. */
  17719. Node.prototype.isDisposed = function () {
  17720. return this._isDisposed;
  17721. };
  17722. Object.defineProperty(Node.prototype, "parent", {
  17723. get: function () {
  17724. return this._parentNode;
  17725. },
  17726. /**
  17727. * Gets or sets the parent of the node
  17728. */
  17729. set: function (parent) {
  17730. if (this._parentNode === parent) {
  17731. return;
  17732. }
  17733. // Remove self from list of children of parent
  17734. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17735. var index = this._parentNode._children.indexOf(this);
  17736. if (index !== -1) {
  17737. this._parentNode._children.splice(index, 1);
  17738. }
  17739. }
  17740. // Store new parent
  17741. this._parentNode = parent;
  17742. // Add as child to new parent
  17743. if (this._parentNode) {
  17744. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17745. this._parentNode._children = new Array();
  17746. }
  17747. this._parentNode._children.push(this);
  17748. }
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17754. /**
  17755. * Gets or sets the animation properties override
  17756. */
  17757. get: function () {
  17758. if (!this._animationPropertiesOverride) {
  17759. return this._scene.animationPropertiesOverride;
  17760. }
  17761. return this._animationPropertiesOverride;
  17762. },
  17763. set: function (value) {
  17764. this._animationPropertiesOverride = value;
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. /**
  17770. * Gets a string idenfifying the name of the class
  17771. * @returns "Node" string
  17772. */
  17773. Node.prototype.getClassName = function () {
  17774. return "Node";
  17775. };
  17776. Object.defineProperty(Node.prototype, "onDispose", {
  17777. /**
  17778. * Sets a callback that will be raised when the node will be disposed
  17779. */
  17780. set: function (callback) {
  17781. if (this._onDisposeObserver) {
  17782. this.onDisposeObservable.remove(this._onDisposeObserver);
  17783. }
  17784. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. /**
  17790. * Gets the scene of the node
  17791. * @returns a {BABYLON.Scene}
  17792. */
  17793. Node.prototype.getScene = function () {
  17794. return this._scene;
  17795. };
  17796. /**
  17797. * Gets the engine of the node
  17798. * @returns a {BABYLON.Engine}
  17799. */
  17800. Node.prototype.getEngine = function () {
  17801. return this._scene.getEngine();
  17802. };
  17803. /**
  17804. * Attach a behavior to the node
  17805. * @see http://doc.babylonjs.com/features/behaviour
  17806. * @param behavior defines the behavior to attach
  17807. * @returns the current Node
  17808. */
  17809. Node.prototype.addBehavior = function (behavior) {
  17810. var _this = this;
  17811. var index = this._behaviors.indexOf(behavior);
  17812. if (index !== -1) {
  17813. return this;
  17814. }
  17815. behavior.init();
  17816. if (this._scene.isLoading) {
  17817. // We defer the attach when the scene will be loaded
  17818. this._scene.onDataLoadedObservable.addOnce(function () {
  17819. behavior.attach(_this);
  17820. });
  17821. }
  17822. else {
  17823. behavior.attach(this);
  17824. }
  17825. this._behaviors.push(behavior);
  17826. return this;
  17827. };
  17828. /**
  17829. * Remove an attached behavior
  17830. * @see http://doc.babylonjs.com/features/behaviour
  17831. * @param behavior defines the behavior to attach
  17832. * @returns the current Node
  17833. */
  17834. Node.prototype.removeBehavior = function (behavior) {
  17835. var index = this._behaviors.indexOf(behavior);
  17836. if (index === -1) {
  17837. return this;
  17838. }
  17839. this._behaviors[index].detach();
  17840. this._behaviors.splice(index, 1);
  17841. return this;
  17842. };
  17843. Object.defineProperty(Node.prototype, "behaviors", {
  17844. /**
  17845. * Gets the list of attached behaviors
  17846. * @see http://doc.babylonjs.com/features/behaviour
  17847. */
  17848. get: function () {
  17849. return this._behaviors;
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. /**
  17855. * Gets an attached behavior by name
  17856. * @param name defines the name of the behavior to look for
  17857. * @see http://doc.babylonjs.com/features/behaviour
  17858. * @returns null if behavior was not found else the requested behavior
  17859. */
  17860. Node.prototype.getBehaviorByName = function (name) {
  17861. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17862. var behavior = _a[_i];
  17863. if (behavior.name === name) {
  17864. return behavior;
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. /**
  17870. * Returns the world matrix of the node
  17871. * @returns a matrix containing the node's world matrix
  17872. */
  17873. Node.prototype.getWorldMatrix = function () {
  17874. return BABYLON.Matrix.Identity();
  17875. };
  17876. /** @hidden */
  17877. Node.prototype._getWorldMatrixDeterminant = function () {
  17878. return 1;
  17879. };
  17880. // override it in derived class if you add new variables to the cache
  17881. // and call the parent class method
  17882. /** @hidden */
  17883. Node.prototype._initCache = function () {
  17884. this._cache = {};
  17885. this._cache.parent = undefined;
  17886. };
  17887. /** @hidden */
  17888. Node.prototype.updateCache = function (force) {
  17889. if (!force && this.isSynchronized())
  17890. return;
  17891. this._cache.parent = this.parent;
  17892. this._updateCache();
  17893. };
  17894. // override it in derived class if you add new variables to the cache
  17895. // and call the parent class method if !ignoreParentClass
  17896. /** @hidden */
  17897. Node.prototype._updateCache = function (ignoreParentClass) {
  17898. };
  17899. // override it in derived class if you add new variables to the cache
  17900. /** @hidden */
  17901. Node.prototype._isSynchronized = function () {
  17902. return true;
  17903. };
  17904. /** @hidden */
  17905. Node.prototype._markSyncedWithParent = function () {
  17906. if (this.parent) {
  17907. this._parentRenderId = this.parent._childRenderId;
  17908. }
  17909. };
  17910. /** @hidden */
  17911. Node.prototype.isSynchronizedWithParent = function () {
  17912. if (!this.parent) {
  17913. return true;
  17914. }
  17915. if (this._parentRenderId !== this.parent._childRenderId) {
  17916. return false;
  17917. }
  17918. return this.parent.isSynchronized();
  17919. };
  17920. /** @hidden */
  17921. Node.prototype.isSynchronized = function (updateCache) {
  17922. var check = this.hasNewParent();
  17923. check = check || !this.isSynchronizedWithParent();
  17924. check = check || !this._isSynchronized();
  17925. if (updateCache)
  17926. this.updateCache(true);
  17927. return !check;
  17928. };
  17929. /** @hidden */
  17930. Node.prototype.hasNewParent = function (update) {
  17931. if (this._cache.parent === this.parent)
  17932. return false;
  17933. if (update)
  17934. this._cache.parent = this.parent;
  17935. return true;
  17936. };
  17937. /**
  17938. * Is this node ready to be used/rendered
  17939. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17940. * @return true if the node is ready
  17941. */
  17942. Node.prototype.isReady = function (completeCheck) {
  17943. if (completeCheck === void 0) { completeCheck = false; }
  17944. return this._isReady;
  17945. };
  17946. /**
  17947. * Is this node enabled?
  17948. * 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
  17949. * @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
  17950. * @return whether this node (and its parent) is enabled
  17951. */
  17952. Node.prototype.isEnabled = function (checkAncestors) {
  17953. if (checkAncestors === void 0) { checkAncestors = true; }
  17954. if (checkAncestors === false) {
  17955. return this._isEnabled;
  17956. }
  17957. if (this._isEnabled === false) {
  17958. return false;
  17959. }
  17960. if (this.parent !== undefined && this.parent !== null) {
  17961. return this.parent.isEnabled(checkAncestors);
  17962. }
  17963. return true;
  17964. };
  17965. /**
  17966. * Set the enabled state of this node
  17967. * @param value defines the new enabled state
  17968. */
  17969. Node.prototype.setEnabled = function (value) {
  17970. this._isEnabled = value;
  17971. };
  17972. /**
  17973. * Is this node a descendant of the given node?
  17974. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17975. * @param ancestor defines the parent node to inspect
  17976. * @returns a boolean indicating if this node is a descendant of the given node
  17977. */
  17978. Node.prototype.isDescendantOf = function (ancestor) {
  17979. if (this.parent) {
  17980. if (this.parent === ancestor) {
  17981. return true;
  17982. }
  17983. return this.parent.isDescendantOf(ancestor);
  17984. }
  17985. return false;
  17986. };
  17987. /** @hidden */
  17988. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17989. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17990. if (!this._children) {
  17991. return;
  17992. }
  17993. for (var index = 0; index < this._children.length; index++) {
  17994. var item = this._children[index];
  17995. if (!predicate || predicate(item)) {
  17996. results.push(item);
  17997. }
  17998. if (!directDescendantsOnly) {
  17999. item._getDescendants(results, false, predicate);
  18000. }
  18001. }
  18002. };
  18003. /**
  18004. * Will return all nodes that have this node as ascendant
  18005. * @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
  18006. * @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
  18007. * @return all children nodes of all types
  18008. */
  18009. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18010. var results = new Array();
  18011. this._getDescendants(results, directDescendantsOnly, predicate);
  18012. return results;
  18013. };
  18014. /**
  18015. * Get all child-meshes of this node
  18016. * @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
  18017. * @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
  18018. * @returns an array of {BABYLON.AbstractMesh}
  18019. */
  18020. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18021. var results = [];
  18022. this._getDescendants(results, directDescendantsOnly, function (node) {
  18023. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18024. });
  18025. return results;
  18026. };
  18027. /**
  18028. * Get all child-transformNodes of this node
  18029. * @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
  18030. * @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
  18031. * @returns an array of {BABYLON.TransformNode}
  18032. */
  18033. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18034. var results = [];
  18035. this._getDescendants(results, directDescendantsOnly, function (node) {
  18036. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18037. });
  18038. return results;
  18039. };
  18040. /**
  18041. * Get all direct children of this node
  18042. * @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
  18043. * @returns an array of {BABYLON.Node}
  18044. */
  18045. Node.prototype.getChildren = function (predicate) {
  18046. return this.getDescendants(true, predicate);
  18047. };
  18048. /** @hidden */
  18049. Node.prototype._setReady = function (state) {
  18050. if (state === this._isReady) {
  18051. return;
  18052. }
  18053. if (!state) {
  18054. this._isReady = false;
  18055. return;
  18056. }
  18057. if (this.onReady) {
  18058. this.onReady(this);
  18059. }
  18060. this._isReady = true;
  18061. };
  18062. /**
  18063. * Get an animation by name
  18064. * @param name defines the name of the animation to look for
  18065. * @returns null if not found else the requested animation
  18066. */
  18067. Node.prototype.getAnimationByName = function (name) {
  18068. for (var i = 0; i < this.animations.length; i++) {
  18069. var animation = this.animations[i];
  18070. if (animation.name === name) {
  18071. return animation;
  18072. }
  18073. }
  18074. return null;
  18075. };
  18076. /**
  18077. * Creates an animation range for this node
  18078. * @param name defines the name of the range
  18079. * @param from defines the starting key
  18080. * @param to defines the end key
  18081. */
  18082. Node.prototype.createAnimationRange = function (name, from, to) {
  18083. // check name not already in use
  18084. if (!this._ranges[name]) {
  18085. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18086. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18087. if (this.animations[i]) {
  18088. this.animations[i].createRange(name, from, to);
  18089. }
  18090. }
  18091. }
  18092. };
  18093. /**
  18094. * Delete a specific animation range
  18095. * @param name defines the name of the range to delete
  18096. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18097. */
  18098. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18099. if (deleteFrames === void 0) { deleteFrames = true; }
  18100. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18101. if (this.animations[i]) {
  18102. this.animations[i].deleteRange(name, deleteFrames);
  18103. }
  18104. }
  18105. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18106. };
  18107. /**
  18108. * Get an animation range by name
  18109. * @param name defines the name of the animation range to look for
  18110. * @returns null if not found else the requested animation range
  18111. */
  18112. Node.prototype.getAnimationRange = function (name) {
  18113. return this._ranges[name];
  18114. };
  18115. /**
  18116. * Will start the animation sequence
  18117. * @param name defines the range frames for animation sequence
  18118. * @param loop defines if the animation should loop (false by default)
  18119. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18120. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18121. * @returns the object created for this animation. If range does not exist, it will return null
  18122. */
  18123. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18124. var range = this.getAnimationRange(name);
  18125. if (!range) {
  18126. return null;
  18127. }
  18128. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18129. };
  18130. /**
  18131. * Serialize animation ranges into a JSON compatible object
  18132. * @returns serialization object
  18133. */
  18134. Node.prototype.serializeAnimationRanges = function () {
  18135. var serializationRanges = [];
  18136. for (var name in this._ranges) {
  18137. var localRange = this._ranges[name];
  18138. if (!localRange) {
  18139. continue;
  18140. }
  18141. var range = {};
  18142. range.name = name;
  18143. range.from = localRange.from;
  18144. range.to = localRange.to;
  18145. serializationRanges.push(range);
  18146. }
  18147. return serializationRanges;
  18148. };
  18149. /**
  18150. * Computes the world matrix of the node
  18151. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18152. * @returns the world matrix
  18153. */
  18154. Node.prototype.computeWorldMatrix = function (force) {
  18155. return BABYLON.Matrix.Identity();
  18156. };
  18157. /**
  18158. * Releases resources associated with this node.
  18159. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18160. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18161. */
  18162. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18163. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18164. if (!doNotRecurse) {
  18165. var nodes = this.getDescendants(true);
  18166. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18167. var node = nodes_1[_i];
  18168. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18169. }
  18170. }
  18171. else {
  18172. var transformNodes = this.getChildTransformNodes(true);
  18173. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18174. var transformNode = transformNodes_1[_a];
  18175. transformNode.parent = null;
  18176. transformNode.computeWorldMatrix(true);
  18177. }
  18178. }
  18179. this.parent = null;
  18180. // Callback
  18181. this.onDisposeObservable.notifyObservers(this);
  18182. this.onDisposeObservable.clear();
  18183. // Behaviors
  18184. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18185. var behavior = _c[_b];
  18186. behavior.detach();
  18187. }
  18188. this._behaviors = [];
  18189. this._isDisposed = true;
  18190. };
  18191. /**
  18192. * Parse animation range data from a serialization object and store them into a given node
  18193. * @param node defines where to store the animation ranges
  18194. * @param parsedNode defines the serialization object to read data from
  18195. * @param scene defines the hosting scene
  18196. */
  18197. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18198. if (parsedNode.ranges) {
  18199. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18200. var data = parsedNode.ranges[index];
  18201. node.createAnimationRange(data.name, data.from, data.to);
  18202. }
  18203. }
  18204. };
  18205. __decorate([
  18206. BABYLON.serialize()
  18207. ], Node.prototype, "name", void 0);
  18208. __decorate([
  18209. BABYLON.serialize()
  18210. ], Node.prototype, "id", void 0);
  18211. __decorate([
  18212. BABYLON.serialize()
  18213. ], Node.prototype, "uniqueId", void 0);
  18214. __decorate([
  18215. BABYLON.serialize()
  18216. ], Node.prototype, "state", void 0);
  18217. __decorate([
  18218. BABYLON.serialize()
  18219. ], Node.prototype, "metadata", void 0);
  18220. return Node;
  18221. }());
  18222. BABYLON.Node = Node;
  18223. })(BABYLON || (BABYLON = {}));
  18224. //# sourceMappingURL=babylon.node.js.map
  18225. var BABYLON;
  18226. (function (BABYLON) {
  18227. var BoundingSphere = /** @class */ (function () {
  18228. /**
  18229. * Creates a new bounding sphere
  18230. * @param min defines the minimum vector (in local space)
  18231. * @param max defines the maximum vector (in local space)
  18232. */
  18233. function BoundingSphere(min, max) {
  18234. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18235. this.reConstruct(min, max);
  18236. }
  18237. /**
  18238. * Recreates the entire bounding sphere from scratch
  18239. * @param min defines the new minimum vector (in local space)
  18240. * @param max defines the new maximum vector (in local space)
  18241. */
  18242. BoundingSphere.prototype.reConstruct = function (min, max) {
  18243. this.minimum = min.clone();
  18244. this.maximum = max.clone();
  18245. var distance = BABYLON.Vector3.Distance(min, max);
  18246. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18247. this.radius = distance * 0.5;
  18248. this.centerWorld = BABYLON.Vector3.Zero();
  18249. this._update(BABYLON.Matrix.Identity());
  18250. };
  18251. // Methods
  18252. BoundingSphere.prototype._update = function (world) {
  18253. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18254. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18255. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18256. };
  18257. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18258. for (var i = 0; i < 6; i++) {
  18259. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18260. return false;
  18261. }
  18262. return true;
  18263. };
  18264. BoundingSphere.prototype.intersectsPoint = function (point) {
  18265. var x = this.centerWorld.x - point.x;
  18266. var y = this.centerWorld.y - point.y;
  18267. var z = this.centerWorld.z - point.z;
  18268. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18269. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18270. return false;
  18271. return true;
  18272. };
  18273. // Statics
  18274. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18275. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18276. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18277. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18278. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18279. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18280. return false;
  18281. return true;
  18282. };
  18283. return BoundingSphere;
  18284. }());
  18285. BABYLON.BoundingSphere = BoundingSphere;
  18286. })(BABYLON || (BABYLON = {}));
  18287. //# sourceMappingURL=babylon.boundingSphere.js.map
  18288. var BABYLON;
  18289. (function (BABYLON) {
  18290. var BoundingBox = /** @class */ (function () {
  18291. /**
  18292. * Creates a new bounding box
  18293. * @param min defines the minimum vector (in local space)
  18294. * @param max defines the maximum vector (in local space)
  18295. */
  18296. function BoundingBox(min, max) {
  18297. this.vectorsWorld = new Array();
  18298. this.reConstruct(min, max);
  18299. }
  18300. // Methods
  18301. /**
  18302. * Recreates the entire bounding box from scratch
  18303. * @param min defines the new minimum vector (in local space)
  18304. * @param max defines the new maximum vector (in local space)
  18305. */
  18306. BoundingBox.prototype.reConstruct = function (min, max) {
  18307. this.minimum = min.clone();
  18308. this.maximum = max.clone();
  18309. // Bounding vectors
  18310. this.vectors = new Array();
  18311. this.vectors.push(this.minimum.clone());
  18312. this.vectors.push(this.maximum.clone());
  18313. this.vectors.push(this.minimum.clone());
  18314. this.vectors[2].x = this.maximum.x;
  18315. this.vectors.push(this.minimum.clone());
  18316. this.vectors[3].y = this.maximum.y;
  18317. this.vectors.push(this.minimum.clone());
  18318. this.vectors[4].z = this.maximum.z;
  18319. this.vectors.push(this.maximum.clone());
  18320. this.vectors[5].z = this.minimum.z;
  18321. this.vectors.push(this.maximum.clone());
  18322. this.vectors[6].x = this.minimum.x;
  18323. this.vectors.push(this.maximum.clone());
  18324. this.vectors[7].y = this.minimum.y;
  18325. // OBB
  18326. this.center = this.maximum.add(this.minimum).scale(0.5);
  18327. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18328. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18329. // World
  18330. for (var index = 0; index < this.vectors.length; index++) {
  18331. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18332. }
  18333. this.minimumWorld = BABYLON.Vector3.Zero();
  18334. this.maximumWorld = BABYLON.Vector3.Zero();
  18335. this.centerWorld = BABYLON.Vector3.Zero();
  18336. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18337. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18338. };
  18339. BoundingBox.prototype.getWorldMatrix = function () {
  18340. return this._worldMatrix;
  18341. };
  18342. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18343. this._worldMatrix.copyFrom(matrix);
  18344. return this;
  18345. };
  18346. BoundingBox.prototype._update = function (world) {
  18347. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18348. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18349. for (var index = 0; index < this.vectors.length; index++) {
  18350. var v = this.vectorsWorld[index];
  18351. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18352. if (v.x < this.minimumWorld.x)
  18353. this.minimumWorld.x = v.x;
  18354. if (v.y < this.minimumWorld.y)
  18355. this.minimumWorld.y = v.y;
  18356. if (v.z < this.minimumWorld.z)
  18357. this.minimumWorld.z = v.z;
  18358. if (v.x > this.maximumWorld.x)
  18359. this.maximumWorld.x = v.x;
  18360. if (v.y > this.maximumWorld.y)
  18361. this.maximumWorld.y = v.y;
  18362. if (v.z > this.maximumWorld.z)
  18363. this.maximumWorld.z = v.z;
  18364. }
  18365. // Extend
  18366. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18367. this.extendSizeWorld.scaleInPlace(0.5);
  18368. // OBB
  18369. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18370. this.centerWorld.scaleInPlace(0.5);
  18371. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18372. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18373. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18374. this._worldMatrix = world;
  18375. };
  18376. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18377. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18378. };
  18379. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18380. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18381. };
  18382. BoundingBox.prototype.intersectsPoint = function (point) {
  18383. var delta = -BABYLON.Epsilon;
  18384. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18385. return false;
  18386. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18387. return false;
  18388. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18389. return false;
  18390. return true;
  18391. };
  18392. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18393. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18394. };
  18395. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18396. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18397. return false;
  18398. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18399. return false;
  18400. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18401. return false;
  18402. return true;
  18403. };
  18404. // Statics
  18405. BoundingBox.Intersects = function (box0, box1) {
  18406. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18407. return false;
  18408. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18409. return false;
  18410. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18411. return false;
  18412. return true;
  18413. };
  18414. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18415. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18416. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18417. return (num <= (sphereRadius * sphereRadius));
  18418. };
  18419. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18420. for (var p = 0; p < 6; p++) {
  18421. for (var i = 0; i < 8; i++) {
  18422. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18423. return false;
  18424. }
  18425. }
  18426. }
  18427. return true;
  18428. };
  18429. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18430. for (var p = 0; p < 6; p++) {
  18431. var inCount = 8;
  18432. for (var i = 0; i < 8; i++) {
  18433. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18434. --inCount;
  18435. }
  18436. else {
  18437. break;
  18438. }
  18439. }
  18440. if (inCount === 0)
  18441. return false;
  18442. }
  18443. return true;
  18444. };
  18445. return BoundingBox;
  18446. }());
  18447. BABYLON.BoundingBox = BoundingBox;
  18448. })(BABYLON || (BABYLON = {}));
  18449. //# sourceMappingURL=babylon.boundingBox.js.map
  18450. var BABYLON;
  18451. (function (BABYLON) {
  18452. var computeBoxExtents = function (axis, box) {
  18453. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18454. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18455. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18456. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18457. var r = r0 + r1 + r2;
  18458. return {
  18459. min: p - r,
  18460. max: p + r
  18461. };
  18462. };
  18463. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18464. var axisOverlap = function (axis, box0, box1) {
  18465. var result0 = computeBoxExtents(axis, box0);
  18466. var result1 = computeBoxExtents(axis, box1);
  18467. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18468. };
  18469. var BoundingInfo = /** @class */ (function () {
  18470. function BoundingInfo(minimum, maximum) {
  18471. this.minimum = minimum;
  18472. this.maximum = maximum;
  18473. this._isLocked = false;
  18474. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18475. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18476. }
  18477. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18478. get: function () {
  18479. return this._isLocked;
  18480. },
  18481. set: function (value) {
  18482. this._isLocked = value;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. // Methods
  18488. BoundingInfo.prototype.update = function (world) {
  18489. if (this._isLocked) {
  18490. return;
  18491. }
  18492. this.boundingBox._update(world);
  18493. this.boundingSphere._update(world);
  18494. };
  18495. /**
  18496. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18497. * @param center New center of the bounding info
  18498. * @param extend New extend of the bounding info
  18499. */
  18500. BoundingInfo.prototype.centerOn = function (center, extend) {
  18501. this.minimum = center.subtract(extend);
  18502. this.maximum = center.add(extend);
  18503. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18504. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18505. return this;
  18506. };
  18507. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18508. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18509. return false;
  18510. return this.boundingBox.isInFrustum(frustumPlanes);
  18511. };
  18512. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18513. /**
  18514. * Gets the world distance between the min and max points of the bounding box
  18515. */
  18516. get: function () {
  18517. var boundingBox = this.boundingBox;
  18518. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18519. return size.length();
  18520. },
  18521. enumerable: true,
  18522. configurable: true
  18523. });
  18524. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18525. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18526. };
  18527. BoundingInfo.prototype._checkCollision = function (collider) {
  18528. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18529. };
  18530. BoundingInfo.prototype.intersectsPoint = function (point) {
  18531. if (!this.boundingSphere.centerWorld) {
  18532. return false;
  18533. }
  18534. if (!this.boundingSphere.intersectsPoint(point)) {
  18535. return false;
  18536. }
  18537. if (!this.boundingBox.intersectsPoint(point)) {
  18538. return false;
  18539. }
  18540. return true;
  18541. };
  18542. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18543. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18544. return false;
  18545. }
  18546. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18547. return false;
  18548. }
  18549. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18550. return false;
  18551. }
  18552. if (!precise) {
  18553. return true;
  18554. }
  18555. var box0 = this.boundingBox;
  18556. var box1 = boundingInfo.boundingBox;
  18557. if (!axisOverlap(box0.directions[0], box0, box1))
  18558. return false;
  18559. if (!axisOverlap(box0.directions[1], box0, box1))
  18560. return false;
  18561. if (!axisOverlap(box0.directions[2], box0, box1))
  18562. return false;
  18563. if (!axisOverlap(box1.directions[0], box0, box1))
  18564. return false;
  18565. if (!axisOverlap(box1.directions[1], box0, box1))
  18566. return false;
  18567. if (!axisOverlap(box1.directions[2], box0, box1))
  18568. return false;
  18569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18570. return false;
  18571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18572. return false;
  18573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18574. return false;
  18575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18576. return false;
  18577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18578. return false;
  18579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18580. return false;
  18581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18582. return false;
  18583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18584. return false;
  18585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18586. return false;
  18587. return true;
  18588. };
  18589. return BoundingInfo;
  18590. }());
  18591. BABYLON.BoundingInfo = BoundingInfo;
  18592. })(BABYLON || (BABYLON = {}));
  18593. //# sourceMappingURL=babylon.boundingInfo.js.map
  18594. var BABYLON;
  18595. (function (BABYLON) {
  18596. var TransformNode = /** @class */ (function (_super) {
  18597. __extends(TransformNode, _super);
  18598. function TransformNode(name, scene, isPure) {
  18599. if (scene === void 0) { scene = null; }
  18600. if (isPure === void 0) { isPure = true; }
  18601. var _this = _super.call(this, name, scene) || this;
  18602. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18603. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18604. _this._up = new BABYLON.Vector3(0, 1, 0);
  18605. _this._right = new BABYLON.Vector3(1, 0, 0);
  18606. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18607. // Properties
  18608. _this._rotation = BABYLON.Vector3.Zero();
  18609. _this._scaling = BABYLON.Vector3.One();
  18610. _this._isDirty = false;
  18611. /**
  18612. * Set the billboard mode. Default is 0.
  18613. *
  18614. * | Value | Type | Description |
  18615. * | --- | --- | --- |
  18616. * | 0 | BILLBOARDMODE_NONE | |
  18617. * | 1 | BILLBOARDMODE_X | |
  18618. * | 2 | BILLBOARDMODE_Y | |
  18619. * | 4 | BILLBOARDMODE_Z | |
  18620. * | 7 | BILLBOARDMODE_ALL | |
  18621. *
  18622. */
  18623. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18624. _this.scalingDeterminant = 1;
  18625. _this.infiniteDistance = false;
  18626. /**
  18627. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18628. * By default the system will update normals to compensate
  18629. */
  18630. _this.ignoreNonUniformScaling = false;
  18631. _this.position = BABYLON.Vector3.Zero();
  18632. _this._localWorld = BABYLON.Matrix.Zero();
  18633. _this._worldMatrix = BABYLON.Matrix.Zero();
  18634. _this._worldMatrixDeterminant = 0;
  18635. _this._absolutePosition = BABYLON.Vector3.Zero();
  18636. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18637. _this._postMultiplyPivotMatrix = false;
  18638. _this._isWorldMatrixFrozen = false;
  18639. /**
  18640. * An event triggered after the world matrix is updated
  18641. */
  18642. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18643. _this._nonUniformScaling = false;
  18644. if (isPure) {
  18645. _this.getScene().addTransformNode(_this);
  18646. }
  18647. return _this;
  18648. }
  18649. /**
  18650. * Gets a string idenfifying the name of the class
  18651. * @returns "TransformNode" string
  18652. */
  18653. TransformNode.prototype.getClassName = function () {
  18654. return "TransformNode";
  18655. };
  18656. Object.defineProperty(TransformNode.prototype, "rotation", {
  18657. /**
  18658. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18659. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18660. * Default : (0.0, 0.0, 0.0)
  18661. */
  18662. get: function () {
  18663. return this._rotation;
  18664. },
  18665. set: function (newRotation) {
  18666. this._rotation = newRotation;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. Object.defineProperty(TransformNode.prototype, "scaling", {
  18672. /**
  18673. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18674. * Default : (1.0, 1.0, 1.0)
  18675. */
  18676. get: function () {
  18677. return this._scaling;
  18678. },
  18679. /**
  18680. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18681. * Default : (1.0, 1.0, 1.0)
  18682. */
  18683. set: function (newScaling) {
  18684. this._scaling = newScaling;
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18690. /**
  18691. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18692. * It's null by default.
  18693. * 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)
  18694. */
  18695. get: function () {
  18696. return this._rotationQuaternion;
  18697. },
  18698. set: function (quaternion) {
  18699. this._rotationQuaternion = quaternion;
  18700. //reset the rotation vector.
  18701. if (quaternion && this.rotation.length()) {
  18702. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18703. }
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(TransformNode.prototype, "forward", {
  18709. /**
  18710. * The forward direction of that transform in world space.
  18711. */
  18712. get: function () {
  18713. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. Object.defineProperty(TransformNode.prototype, "up", {
  18719. /**
  18720. * The up direction of that transform in world space.
  18721. */
  18722. get: function () {
  18723. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18724. },
  18725. enumerable: true,
  18726. configurable: true
  18727. });
  18728. Object.defineProperty(TransformNode.prototype, "right", {
  18729. /**
  18730. * The right direction of that transform in world space.
  18731. */
  18732. get: function () {
  18733. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18734. },
  18735. enumerable: true,
  18736. configurable: true
  18737. });
  18738. /**
  18739. * Returns the latest update of the World matrix
  18740. * Returns a Matrix.
  18741. */
  18742. TransformNode.prototype.getWorldMatrix = function () {
  18743. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18744. this.computeWorldMatrix();
  18745. }
  18746. return this._worldMatrix;
  18747. };
  18748. /** @hidden */
  18749. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18750. return this._worldMatrixDeterminant;
  18751. };
  18752. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18753. /**
  18754. * Returns directly the latest state of the mesh World matrix.
  18755. * A Matrix is returned.
  18756. */
  18757. get: function () {
  18758. return this._worldMatrix;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. /**
  18764. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18765. * Returns the TransformNode.
  18766. */
  18767. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18768. this._poseMatrix.copyFrom(matrix);
  18769. return this;
  18770. };
  18771. /**
  18772. * Returns the mesh Pose matrix.
  18773. * Returned object : Matrix
  18774. */
  18775. TransformNode.prototype.getPoseMatrix = function () {
  18776. return this._poseMatrix;
  18777. };
  18778. TransformNode.prototype._isSynchronized = function () {
  18779. if (this._isDirty) {
  18780. return false;
  18781. }
  18782. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18783. return false;
  18784. if (this._cache.pivotMatrixUpdated) {
  18785. return false;
  18786. }
  18787. if (this.infiniteDistance) {
  18788. return false;
  18789. }
  18790. if (!this._cache.position.equals(this.position))
  18791. return false;
  18792. if (this.rotationQuaternion) {
  18793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18794. return false;
  18795. }
  18796. if (!this._cache.rotation.equals(this.rotation))
  18797. return false;
  18798. if (!this._cache.scaling.equals(this.scaling))
  18799. return false;
  18800. return true;
  18801. };
  18802. TransformNode.prototype._initCache = function () {
  18803. _super.prototype._initCache.call(this);
  18804. this._cache.localMatrixUpdated = false;
  18805. this._cache.position = BABYLON.Vector3.Zero();
  18806. this._cache.scaling = BABYLON.Vector3.Zero();
  18807. this._cache.rotation = BABYLON.Vector3.Zero();
  18808. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18809. this._cache.billboardMode = -1;
  18810. };
  18811. TransformNode.prototype.markAsDirty = function (property) {
  18812. if (property === "rotation") {
  18813. this.rotationQuaternion = null;
  18814. }
  18815. this._currentRenderId = Number.MAX_VALUE;
  18816. this._isDirty = true;
  18817. return this;
  18818. };
  18819. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18820. /**
  18821. * Returns the current mesh absolute position.
  18822. * Retuns a Vector3.
  18823. */
  18824. get: function () {
  18825. return this._absolutePosition;
  18826. },
  18827. enumerable: true,
  18828. configurable: true
  18829. });
  18830. /**
  18831. * Sets a new matrix to apply before all other transformation
  18832. * @param matrix defines the transform matrix
  18833. * @returns the current TransformNode
  18834. */
  18835. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18836. return this.setPivotMatrix(matrix, false);
  18837. };
  18838. /**
  18839. * Sets a new pivot matrix to the current node
  18840. * @param matrix defines the new pivot matrix to use
  18841. * @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
  18842. * @returns the current TransformNode
  18843. */
  18844. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18845. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18846. this._pivotMatrix = matrix.clone();
  18847. this._cache.pivotMatrixUpdated = true;
  18848. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18849. if (this._postMultiplyPivotMatrix) {
  18850. if (!this._pivotMatrixInverse) {
  18851. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18852. }
  18853. else {
  18854. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18855. }
  18856. }
  18857. return this;
  18858. };
  18859. /**
  18860. * Returns the mesh pivot matrix.
  18861. * Default : Identity.
  18862. * A Matrix is returned.
  18863. */
  18864. TransformNode.prototype.getPivotMatrix = function () {
  18865. return this._pivotMatrix;
  18866. };
  18867. /**
  18868. * Prevents the World matrix to be computed any longer.
  18869. * Returns the TransformNode.
  18870. */
  18871. TransformNode.prototype.freezeWorldMatrix = function () {
  18872. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18873. this.computeWorldMatrix(true);
  18874. this._isWorldMatrixFrozen = true;
  18875. return this;
  18876. };
  18877. /**
  18878. * Allows back the World matrix computation.
  18879. * Returns the TransformNode.
  18880. */
  18881. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18882. this._isWorldMatrixFrozen = false;
  18883. this.computeWorldMatrix(true);
  18884. return this;
  18885. };
  18886. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18887. /**
  18888. * True if the World matrix has been frozen.
  18889. * Returns a boolean.
  18890. */
  18891. get: function () {
  18892. return this._isWorldMatrixFrozen;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. /**
  18898. * Retuns the mesh absolute position in the World.
  18899. * Returns a Vector3.
  18900. */
  18901. TransformNode.prototype.getAbsolutePosition = function () {
  18902. this.computeWorldMatrix();
  18903. return this._absolutePosition;
  18904. };
  18905. /**
  18906. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18907. * Returns the TransformNode.
  18908. */
  18909. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18910. if (!absolutePosition) {
  18911. return this;
  18912. }
  18913. var absolutePositionX;
  18914. var absolutePositionY;
  18915. var absolutePositionZ;
  18916. if (absolutePosition.x === undefined) {
  18917. if (arguments.length < 3) {
  18918. return this;
  18919. }
  18920. absolutePositionX = arguments[0];
  18921. absolutePositionY = arguments[1];
  18922. absolutePositionZ = arguments[2];
  18923. }
  18924. else {
  18925. absolutePositionX = absolutePosition.x;
  18926. absolutePositionY = absolutePosition.y;
  18927. absolutePositionZ = absolutePosition.z;
  18928. }
  18929. if (this.parent) {
  18930. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18931. invertParentWorldMatrix.invert();
  18932. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18933. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18934. }
  18935. else {
  18936. this.position.x = absolutePositionX;
  18937. this.position.y = absolutePositionY;
  18938. this.position.z = absolutePositionZ;
  18939. }
  18940. return this;
  18941. };
  18942. /**
  18943. * Sets the mesh position in its local space.
  18944. * Returns the TransformNode.
  18945. */
  18946. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18947. this.computeWorldMatrix();
  18948. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18949. return this;
  18950. };
  18951. /**
  18952. * Returns the mesh position in the local space from the current World matrix values.
  18953. * Returns a new Vector3.
  18954. */
  18955. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18956. this.computeWorldMatrix();
  18957. var invLocalWorldMatrix = this._localWorld.clone();
  18958. invLocalWorldMatrix.invert();
  18959. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18960. };
  18961. /**
  18962. * Translates the mesh along the passed Vector3 in its local space.
  18963. * Returns the TransformNode.
  18964. */
  18965. TransformNode.prototype.locallyTranslate = function (vector3) {
  18966. this.computeWorldMatrix(true);
  18967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18968. return this;
  18969. };
  18970. /**
  18971. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18972. * @param targetPoint the position (must be in same space as current mesh) to look at
  18973. * @param yawCor optional yaw (y-axis) correction in radians
  18974. * @param pitchCor optional pitch (x-axis) correction in radians
  18975. * @param rollCor optional roll (z-axis) correction in radians
  18976. * @param space the choosen space of the target
  18977. * @returns the TransformNode.
  18978. */
  18979. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18980. if (yawCor === void 0) { yawCor = 0; }
  18981. if (pitchCor === void 0) { pitchCor = 0; }
  18982. if (rollCor === void 0) { rollCor = 0; }
  18983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18984. var dv = TransformNode._lookAtVectorCache;
  18985. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18986. targetPoint.subtractToRef(pos, dv);
  18987. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18988. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18989. var pitch = Math.atan2(dv.y, len);
  18990. if (this.rotationQuaternion) {
  18991. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18992. }
  18993. else {
  18994. this.rotation.x = pitch + pitchCor;
  18995. this.rotation.y = yaw + yawCor;
  18996. this.rotation.z = rollCor;
  18997. }
  18998. return this;
  18999. };
  19000. /**
  19001. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19002. * This Vector3 is expressed in the World space.
  19003. */
  19004. TransformNode.prototype.getDirection = function (localAxis) {
  19005. var result = BABYLON.Vector3.Zero();
  19006. this.getDirectionToRef(localAxis, result);
  19007. return result;
  19008. };
  19009. /**
  19010. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19011. * localAxis is expressed in the mesh local space.
  19012. * result is computed in the Wordl space from the mesh World matrix.
  19013. * Returns the TransformNode.
  19014. */
  19015. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19016. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19017. return this;
  19018. };
  19019. /**
  19020. * Sets a new pivot point to the current node
  19021. * @param point defines the new pivot point to use
  19022. * @param space defines if the point is in world or local space (local by default)
  19023. * @returns the current TransformNode
  19024. */
  19025. TransformNode.prototype.setPivotPoint = function (point, space) {
  19026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19027. if (this.getScene().getRenderId() == 0) {
  19028. this.computeWorldMatrix(true);
  19029. }
  19030. var wm = this.getWorldMatrix();
  19031. if (space == BABYLON.Space.WORLD) {
  19032. var tmat = BABYLON.Tmp.Matrix[0];
  19033. wm.invertToRef(tmat);
  19034. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19035. }
  19036. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19037. };
  19038. /**
  19039. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19040. */
  19041. TransformNode.prototype.getPivotPoint = function () {
  19042. var point = BABYLON.Vector3.Zero();
  19043. this.getPivotPointToRef(point);
  19044. return point;
  19045. };
  19046. /**
  19047. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19048. * Returns the TransformNode.
  19049. */
  19050. TransformNode.prototype.getPivotPointToRef = function (result) {
  19051. result.x = -this._pivotMatrix.m[12];
  19052. result.y = -this._pivotMatrix.m[13];
  19053. result.z = -this._pivotMatrix.m[14];
  19054. return this;
  19055. };
  19056. /**
  19057. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19058. */
  19059. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19060. var point = BABYLON.Vector3.Zero();
  19061. this.getAbsolutePivotPointToRef(point);
  19062. return point;
  19063. };
  19064. /**
  19065. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19066. * Returns the TransformNode.
  19067. */
  19068. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19069. result.x = this._pivotMatrix.m[12];
  19070. result.y = this._pivotMatrix.m[13];
  19071. result.z = this._pivotMatrix.m[14];
  19072. this.getPivotPointToRef(result);
  19073. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19074. return this;
  19075. };
  19076. /**
  19077. * Defines the passed node as the parent of the current node.
  19078. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19079. * Returns the TransformNode.
  19080. */
  19081. TransformNode.prototype.setParent = function (node) {
  19082. if (node === null) {
  19083. var rotation = BABYLON.Tmp.Quaternion[0];
  19084. var position = BABYLON.Tmp.Vector3[0];
  19085. var scale = BABYLON.Tmp.Vector3[1];
  19086. if (this.parent && this.parent.computeWorldMatrix) {
  19087. this.parent.computeWorldMatrix(true);
  19088. }
  19089. this.computeWorldMatrix(true);
  19090. this.getWorldMatrix().decompose(scale, rotation, position);
  19091. if (this.rotationQuaternion) {
  19092. this.rotationQuaternion.copyFrom(rotation);
  19093. }
  19094. else {
  19095. rotation.toEulerAnglesToRef(this.rotation);
  19096. }
  19097. this.scaling.x = scale.x;
  19098. this.scaling.y = scale.y;
  19099. this.scaling.z = scale.z;
  19100. this.position.x = position.x;
  19101. this.position.y = position.y;
  19102. this.position.z = position.z;
  19103. }
  19104. else {
  19105. var rotation = BABYLON.Tmp.Quaternion[0];
  19106. var position = BABYLON.Tmp.Vector3[0];
  19107. var scale = BABYLON.Tmp.Vector3[1];
  19108. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19109. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19110. this.computeWorldMatrix(true);
  19111. node.computeWorldMatrix(true);
  19112. node.getWorldMatrix().invertToRef(invParentMatrix);
  19113. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19114. diffMatrix.decompose(scale, rotation, position);
  19115. if (this.rotationQuaternion) {
  19116. this.rotationQuaternion.copyFrom(rotation);
  19117. }
  19118. else {
  19119. rotation.toEulerAnglesToRef(this.rotation);
  19120. }
  19121. this.position.x = position.x;
  19122. this.position.y = position.y;
  19123. this.position.z = position.z;
  19124. this.scaling.x = scale.x;
  19125. this.scaling.y = scale.y;
  19126. this.scaling.z = scale.z;
  19127. }
  19128. this.parent = node;
  19129. return this;
  19130. };
  19131. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19132. get: function () {
  19133. return this._nonUniformScaling;
  19134. },
  19135. enumerable: true,
  19136. configurable: true
  19137. });
  19138. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19139. if (this._nonUniformScaling === value) {
  19140. return false;
  19141. }
  19142. this._nonUniformScaling = value;
  19143. return true;
  19144. };
  19145. /**
  19146. * Attach the current TransformNode to another TransformNode associated with a bone
  19147. * @param bone Bone affecting the TransformNode
  19148. * @param affectedTransformNode TransformNode associated with the bone
  19149. */
  19150. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19151. this._transformToBoneReferal = affectedTransformNode;
  19152. this.parent = bone;
  19153. if (bone.getWorldMatrix().determinant() < 0) {
  19154. this.scalingDeterminant *= -1;
  19155. }
  19156. return this;
  19157. };
  19158. TransformNode.prototype.detachFromBone = function () {
  19159. if (!this.parent) {
  19160. return this;
  19161. }
  19162. if (this.parent.getWorldMatrix().determinant() < 0) {
  19163. this.scalingDeterminant *= -1;
  19164. }
  19165. this._transformToBoneReferal = null;
  19166. this.parent = null;
  19167. return this;
  19168. };
  19169. /**
  19170. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19171. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19172. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19173. * The passed axis is also normalized.
  19174. * Returns the TransformNode.
  19175. */
  19176. TransformNode.prototype.rotate = function (axis, amount, space) {
  19177. axis.normalize();
  19178. if (!this.rotationQuaternion) {
  19179. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19180. this.rotation = BABYLON.Vector3.Zero();
  19181. }
  19182. var rotationQuaternion;
  19183. if (!space || space === BABYLON.Space.LOCAL) {
  19184. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19185. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19186. }
  19187. else {
  19188. if (this.parent) {
  19189. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19190. invertParentWorldMatrix.invert();
  19191. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19192. }
  19193. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19194. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19195. }
  19196. return this;
  19197. };
  19198. /**
  19199. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19200. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19201. * The passed axis is also normalized.
  19202. * Returns the TransformNode.
  19203. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19204. */
  19205. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19206. axis.normalize();
  19207. if (!this.rotationQuaternion) {
  19208. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19209. this.rotation.copyFromFloats(0, 0, 0);
  19210. }
  19211. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19212. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19213. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19214. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19215. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19216. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19217. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19218. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19219. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19220. return this;
  19221. };
  19222. /**
  19223. * Translates the mesh along the axis vector for the passed distance in the given space.
  19224. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19225. * Returns the TransformNode.
  19226. */
  19227. TransformNode.prototype.translate = function (axis, distance, space) {
  19228. var displacementVector = axis.scale(distance);
  19229. if (!space || space === BABYLON.Space.LOCAL) {
  19230. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19231. this.setPositionWithLocalVector(tempV3);
  19232. }
  19233. else {
  19234. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19235. }
  19236. return this;
  19237. };
  19238. /**
  19239. * Adds a rotation step to the mesh current rotation.
  19240. * x, y, z are Euler angles expressed in radians.
  19241. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19242. * This means this rotation is made in the mesh local space only.
  19243. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19244. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19245. * ```javascript
  19246. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19247. * ```
  19248. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19249. * 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.
  19250. * Returns the TransformNode.
  19251. */
  19252. TransformNode.prototype.addRotation = function (x, y, z) {
  19253. var rotationQuaternion;
  19254. if (this.rotationQuaternion) {
  19255. rotationQuaternion = this.rotationQuaternion;
  19256. }
  19257. else {
  19258. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19259. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19260. }
  19261. var accumulation = BABYLON.Tmp.Quaternion[0];
  19262. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19263. rotationQuaternion.multiplyInPlace(accumulation);
  19264. if (!this.rotationQuaternion) {
  19265. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19266. }
  19267. return this;
  19268. };
  19269. /**
  19270. * Computes the mesh World matrix and returns it.
  19271. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19272. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19273. * If the parameter `force`is set to `true`, the actual computation is done.
  19274. * Returns the mesh World Matrix.
  19275. */
  19276. TransformNode.prototype.computeWorldMatrix = function (force) {
  19277. if (this._isWorldMatrixFrozen) {
  19278. return this._worldMatrix;
  19279. }
  19280. if (!force && this.isSynchronized(true)) {
  19281. this._currentRenderId = this.getScene().getRenderId();
  19282. return this._worldMatrix;
  19283. }
  19284. this._cache.position.copyFrom(this.position);
  19285. this._cache.scaling.copyFrom(this.scaling);
  19286. this._cache.pivotMatrixUpdated = false;
  19287. this._cache.billboardMode = this.billboardMode;
  19288. this._currentRenderId = this.getScene().getRenderId();
  19289. this._childRenderId = this.getScene().getRenderId();
  19290. this._isDirty = false;
  19291. // Scaling
  19292. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19293. // Rotation
  19294. //rotate, if quaternion is set and rotation was used
  19295. if (this.rotationQuaternion) {
  19296. var len = this.rotation.length();
  19297. if (len) {
  19298. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19299. this.rotation.copyFromFloats(0, 0, 0);
  19300. }
  19301. }
  19302. if (this.rotationQuaternion) {
  19303. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19304. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19305. }
  19306. else {
  19307. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19308. this._cache.rotation.copyFrom(this.rotation);
  19309. }
  19310. // Translation
  19311. var camera = this.getScene().activeCamera;
  19312. if (this.infiniteDistance && !this.parent && camera) {
  19313. var cameraWorldMatrix = camera.getWorldMatrix();
  19314. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19315. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19316. }
  19317. else {
  19318. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19319. }
  19320. // Composing transformations
  19321. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19322. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19323. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19324. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19325. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19326. // Need to decompose each rotation here
  19327. var currentPosition = BABYLON.Tmp.Vector3[3];
  19328. if (this.parent && this.parent.getWorldMatrix) {
  19329. if (this._transformToBoneReferal) {
  19330. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19331. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19332. }
  19333. else {
  19334. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19335. }
  19336. }
  19337. else {
  19338. currentPosition.copyFrom(this.position);
  19339. }
  19340. currentPosition.subtractInPlace(camera.globalPosition);
  19341. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19342. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19343. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19344. }
  19345. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19346. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19347. }
  19348. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19349. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19350. }
  19351. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19352. }
  19353. else {
  19354. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19355. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19356. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19357. }
  19358. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19359. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19360. }
  19361. // Local world
  19362. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19363. // Parent
  19364. if (this.parent && this.parent.getWorldMatrix) {
  19365. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19366. if (this._transformToBoneReferal) {
  19367. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19368. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19369. }
  19370. else {
  19371. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19372. }
  19373. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19374. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19375. this._worldMatrix.copyFrom(this._localWorld);
  19376. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19377. }
  19378. else {
  19379. if (this._transformToBoneReferal) {
  19380. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19381. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19382. }
  19383. else {
  19384. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19385. }
  19386. }
  19387. this._markSyncedWithParent();
  19388. }
  19389. else {
  19390. this._worldMatrix.copyFrom(this._localWorld);
  19391. }
  19392. // Post multiply inverse of pivotMatrix
  19393. if (this._postMultiplyPivotMatrix) {
  19394. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19395. }
  19396. // Normal matrix
  19397. if (!this.ignoreNonUniformScaling) {
  19398. if (this.scaling.isNonUniform) {
  19399. this._updateNonUniformScalingState(true);
  19400. }
  19401. else if (this.parent && this.parent._nonUniformScaling) {
  19402. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19403. }
  19404. else {
  19405. this._updateNonUniformScalingState(false);
  19406. }
  19407. }
  19408. else {
  19409. this._updateNonUniformScalingState(false);
  19410. }
  19411. this._afterComputeWorldMatrix();
  19412. // Absolute position
  19413. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19414. // Callbacks
  19415. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19416. if (!this._poseMatrix) {
  19417. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19418. }
  19419. // Cache the determinant
  19420. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19421. return this._worldMatrix;
  19422. };
  19423. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19424. };
  19425. /**
  19426. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19427. * @param func: callback function to add
  19428. *
  19429. * Returns the TransformNode.
  19430. */
  19431. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19432. this.onAfterWorldMatrixUpdateObservable.add(func);
  19433. return this;
  19434. };
  19435. /**
  19436. * Removes a registered callback function.
  19437. * Returns the TransformNode.
  19438. */
  19439. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19440. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19441. return this;
  19442. };
  19443. /**
  19444. * Clone the current transform node
  19445. * Returns the new transform node
  19446. * @param name Name of the new clone
  19447. * @param newParent New parent for the clone
  19448. * @param doNotCloneChildren Do not clone children hierarchy
  19449. */
  19450. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19451. var _this = this;
  19452. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19453. result.name = name;
  19454. result.id = name;
  19455. if (newParent) {
  19456. result.parent = newParent;
  19457. }
  19458. if (!doNotCloneChildren) {
  19459. // Children
  19460. var directDescendants = this.getDescendants(true);
  19461. for (var index = 0; index < directDescendants.length; index++) {
  19462. var child = directDescendants[index];
  19463. if (child.clone) {
  19464. child.clone(name + "." + child.name, result);
  19465. }
  19466. }
  19467. }
  19468. return result;
  19469. };
  19470. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19471. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19472. serializationObject.type = this.getClassName();
  19473. // Parent
  19474. if (this.parent) {
  19475. serializationObject.parentId = this.parent.id;
  19476. }
  19477. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19478. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19479. }
  19480. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19481. serializationObject.isEnabled = this.isEnabled();
  19482. // Parent
  19483. if (this.parent) {
  19484. serializationObject.parentId = this.parent.id;
  19485. }
  19486. return serializationObject;
  19487. };
  19488. // Statics
  19489. /**
  19490. * Returns a new TransformNode object parsed from the source provided.
  19491. * The parameter `parsedMesh` is the source.
  19492. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19493. */
  19494. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19495. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19496. if (BABYLON.Tags) {
  19497. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19498. }
  19499. if (parsedTransformNode.localMatrix) {
  19500. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19501. }
  19502. else if (parsedTransformNode.pivotMatrix) {
  19503. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19504. }
  19505. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19506. // Parent
  19507. if (parsedTransformNode.parentId) {
  19508. transformNode._waitingParentId = parsedTransformNode.parentId;
  19509. }
  19510. return transformNode;
  19511. };
  19512. /**
  19513. * Releases resources associated with this transform node.
  19514. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19515. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19516. */
  19517. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19518. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19519. // Animations
  19520. this.getScene().stopAnimation(this);
  19521. // Remove from scene
  19522. this.getScene().removeTransformNode(this);
  19523. this.onAfterWorldMatrixUpdateObservable.clear();
  19524. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19525. };
  19526. // Statics
  19527. TransformNode.BILLBOARDMODE_NONE = 0;
  19528. TransformNode.BILLBOARDMODE_X = 1;
  19529. TransformNode.BILLBOARDMODE_Y = 2;
  19530. TransformNode.BILLBOARDMODE_Z = 4;
  19531. TransformNode.BILLBOARDMODE_ALL = 7;
  19532. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19533. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19534. __decorate([
  19535. BABYLON.serializeAsVector3()
  19536. ], TransformNode.prototype, "_rotation", void 0);
  19537. __decorate([
  19538. BABYLON.serializeAsQuaternion()
  19539. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19540. __decorate([
  19541. BABYLON.serializeAsVector3()
  19542. ], TransformNode.prototype, "_scaling", void 0);
  19543. __decorate([
  19544. BABYLON.serialize()
  19545. ], TransformNode.prototype, "billboardMode", void 0);
  19546. __decorate([
  19547. BABYLON.serialize()
  19548. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19549. __decorate([
  19550. BABYLON.serialize()
  19551. ], TransformNode.prototype, "infiniteDistance", void 0);
  19552. __decorate([
  19553. BABYLON.serialize()
  19554. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19555. __decorate([
  19556. BABYLON.serializeAsVector3()
  19557. ], TransformNode.prototype, "position", void 0);
  19558. return TransformNode;
  19559. }(BABYLON.Node));
  19560. BABYLON.TransformNode = TransformNode;
  19561. })(BABYLON || (BABYLON = {}));
  19562. //# sourceMappingURL=babylon.transformNode.js.map
  19563. var BABYLON;
  19564. (function (BABYLON) {
  19565. /**
  19566. * Class used to store all common mesh properties
  19567. */
  19568. var AbstractMesh = /** @class */ (function (_super) {
  19569. __extends(AbstractMesh, _super);
  19570. // Constructor
  19571. /**
  19572. * Creates a new AbstractMesh
  19573. * @param name defines the name of the mesh
  19574. * @param scene defines the hosting scene
  19575. */
  19576. function AbstractMesh(name, scene) {
  19577. if (scene === void 0) { scene = null; }
  19578. var _this = _super.call(this, name, scene, false) || this;
  19579. _this._facetNb = 0; // facet number
  19580. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19581. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19582. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19583. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19584. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19585. _this._subDiv = {
  19586. max: 1,
  19587. X: 1,
  19588. Y: 1,
  19589. Z: 1
  19590. };
  19591. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19592. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19593. // Events
  19594. /**
  19595. * An event triggered when this mesh collides with another one
  19596. */
  19597. _this.onCollideObservable = new BABYLON.Observable();
  19598. /**
  19599. * An event triggered when the collision's position changes
  19600. */
  19601. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19602. /**
  19603. * An event triggered when material is changed
  19604. */
  19605. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19606. // Properties
  19607. /**
  19608. * Gets or sets the orientation for POV movement & rotation
  19609. */
  19610. _this.definedFacingForward = true;
  19611. /**
  19612. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19613. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19614. * * 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.
  19615. * @see http://doc.babylonjs.com/features/occlusionquery
  19616. */
  19617. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19618. /**
  19619. * 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:
  19620. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19621. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19622. * * 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.
  19623. * @see http://doc.babylonjs.com/features/occlusionquery
  19624. */
  19625. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19626. /**
  19627. * 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.
  19628. * The default value is -1 which means don't break the query and wait till the result
  19629. * @see http://doc.babylonjs.com/features/occlusionquery
  19630. */
  19631. _this.occlusionRetryCount = -1;
  19632. _this._occlusionInternalRetryCounter = 0;
  19633. _this._isOccluded = false;
  19634. _this._isOcclusionQueryInProgress = false;
  19635. _this._visibility = 1.0;
  19636. /** Gets or sets the alpha index used to sort transparent meshes
  19637. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19638. */
  19639. _this.alphaIndex = Number.MAX_VALUE;
  19640. /**
  19641. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19642. */
  19643. _this.isVisible = true;
  19644. /**
  19645. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19646. */
  19647. _this.isPickable = true;
  19648. /**
  19649. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19650. */
  19651. _this.showBoundingBox = false;
  19652. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19653. _this.showSubMeshesBoundingBox = false;
  19654. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19655. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19656. */
  19657. _this.isBlocker = false;
  19658. /**
  19659. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19660. */
  19661. _this.enablePointerMoveEvents = false;
  19662. /**
  19663. * Specifies the rendering group id for this mesh (0 by default)
  19664. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19665. */
  19666. _this.renderingGroupId = 0;
  19667. _this._receiveShadows = false;
  19668. /**
  19669. * Gets or sets a boolean indicating if the outline must be rendered as well
  19670. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19671. */
  19672. _this.renderOutline = false;
  19673. /** Defines color to use when rendering outline */
  19674. _this.outlineColor = BABYLON.Color3.Red();
  19675. /** Define width to use when rendering outline */
  19676. _this.outlineWidth = 0.02;
  19677. /**
  19678. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19679. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19680. */
  19681. _this.renderOverlay = false;
  19682. /** Defines color to use when rendering overlay */
  19683. _this.overlayColor = BABYLON.Color3.Red();
  19684. /** Defines alpha to use when rendering overlay */
  19685. _this.overlayAlpha = 0.5;
  19686. _this._hasVertexAlpha = false;
  19687. _this._useVertexColors = true;
  19688. _this._computeBonesUsingShaders = true;
  19689. _this._numBoneInfluencers = 4;
  19690. _this._applyFog = true;
  19691. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19692. _this.useOctreeForRenderingSelection = true;
  19693. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19694. _this.useOctreeForPicking = true;
  19695. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19696. _this.useOctreeForCollisions = true;
  19697. _this._layerMask = 0x0FFFFFFF;
  19698. /**
  19699. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19700. */
  19701. _this.alwaysSelectAsActiveMesh = false;
  19702. /**
  19703. * Gets or sets the current action manager
  19704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19705. */
  19706. _this.actionManager = null;
  19707. /**
  19708. * Gets or sets impostor used for physic simulation
  19709. * @see http://doc.babylonjs.com/features/physics_engine
  19710. */
  19711. _this.physicsImpostor = null;
  19712. // Collisions
  19713. _this._checkCollisions = false;
  19714. _this._collisionMask = -1;
  19715. _this._collisionGroup = -1;
  19716. /**
  19717. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19718. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19719. */
  19720. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19721. /**
  19722. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19723. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19724. */
  19725. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19726. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19727. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19728. // Edges
  19729. /**
  19730. * Defines edge width used when edgesRenderer is enabled
  19731. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19732. */
  19733. _this.edgesWidth = 1;
  19734. /**
  19735. * Defines edge color used when edgesRenderer is enabled
  19736. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19737. */
  19738. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19739. // Cache
  19740. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19741. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19742. /** @hidden */
  19743. _this._renderId = 0;
  19744. /** @hidden */
  19745. _this._intersectionsInProgress = new Array();
  19746. /** @hidden */
  19747. _this._unIndexed = false;
  19748. /** @hidden */
  19749. _this._lightSources = new Array();
  19750. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19751. if (collidedMesh === void 0) { collidedMesh = null; }
  19752. //TODO move this to the collision coordinator!
  19753. if (_this.getScene().workerCollisions)
  19754. newPosition.multiplyInPlace(_this._collider._radius);
  19755. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19756. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19757. _this.position.addInPlace(_this._diffPositionForCollisions);
  19758. }
  19759. if (collidedMesh) {
  19760. _this.onCollideObservable.notifyObservers(collidedMesh);
  19761. }
  19762. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19763. };
  19764. _this.getScene().addMesh(_this);
  19765. _this._resyncLightSources();
  19766. return _this;
  19767. }
  19768. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19769. /**
  19770. * No billboard
  19771. */
  19772. get: function () {
  19773. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19779. /** Billboard on X axis */
  19780. get: function () {
  19781. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19787. /** Billboard on Y axis */
  19788. get: function () {
  19789. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19795. /** Billboard on Z axis */
  19796. get: function () {
  19797. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19803. /** Billboard on all axes */
  19804. get: function () {
  19805. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19811. /**
  19812. * Gets the number of facets in the mesh
  19813. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19814. */
  19815. get: function () {
  19816. return this._facetNb;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19822. /**
  19823. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19824. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19825. */
  19826. get: function () {
  19827. return this._partitioningSubdivisions;
  19828. },
  19829. set: function (nb) {
  19830. this._partitioningSubdivisions = nb;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19836. /**
  19837. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19838. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19839. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19840. */
  19841. get: function () {
  19842. return this._partitioningBBoxRatio;
  19843. },
  19844. set: function (ratio) {
  19845. this._partitioningBBoxRatio = ratio;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19851. /**
  19852. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19853. * Works only for updatable meshes.
  19854. * Doesn't work with multi-materials
  19855. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19856. */
  19857. get: function () {
  19858. return this._facetDepthSort;
  19859. },
  19860. set: function (sort) {
  19861. this._facetDepthSort = sort;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19867. /**
  19868. * The location (Vector3) where the facet depth sort must be computed from.
  19869. * By default, the active camera position.
  19870. * Used only when facet depth sort is enabled
  19871. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19872. */
  19873. get: function () {
  19874. return this._facetDepthSortFrom;
  19875. },
  19876. set: function (location) {
  19877. this._facetDepthSortFrom = location;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19883. /**
  19884. * gets a boolean indicating if facetData is enabled
  19885. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19886. */
  19887. get: function () {
  19888. return this._facetDataEnabled;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. /** @hidden */
  19894. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19895. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19896. return false;
  19897. }
  19898. this._markSubMeshesAsMiscDirty();
  19899. return true;
  19900. };
  19901. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19902. /** Set a function to call when this mesh collides with another one */
  19903. set: function (callback) {
  19904. if (this._onCollideObserver) {
  19905. this.onCollideObservable.remove(this._onCollideObserver);
  19906. }
  19907. this._onCollideObserver = this.onCollideObservable.add(callback);
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19913. /** Set a function to call when the collision's position changes */
  19914. set: function (callback) {
  19915. if (this._onCollisionPositionChangeObserver) {
  19916. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19917. }
  19918. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19924. /**
  19925. * 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
  19926. * @see http://doc.babylonjs.com/features/occlusionquery
  19927. */
  19928. get: function () {
  19929. return this._isOccluded;
  19930. },
  19931. set: function (value) {
  19932. this._isOccluded = value;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19938. /**
  19939. * Flag to check the progress status of the query
  19940. * @see http://doc.babylonjs.com/features/occlusionquery
  19941. */
  19942. get: function () {
  19943. return this._isOcclusionQueryInProgress;
  19944. },
  19945. enumerable: true,
  19946. configurable: true
  19947. });
  19948. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19949. /**
  19950. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19951. */
  19952. get: function () {
  19953. return this._visibility;
  19954. },
  19955. /**
  19956. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19957. */
  19958. set: function (value) {
  19959. if (this._visibility === value) {
  19960. return;
  19961. }
  19962. this._visibility = value;
  19963. this._markSubMeshesAsMiscDirty();
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(AbstractMesh.prototype, "material", {
  19969. /** Gets or sets current material */
  19970. get: function () {
  19971. return this._material;
  19972. },
  19973. set: function (value) {
  19974. if (this._material === value) {
  19975. return;
  19976. }
  19977. this._material = value;
  19978. if (this.onMaterialChangedObservable.hasObservers) {
  19979. this.onMaterialChangedObservable.notifyObservers(this);
  19980. }
  19981. if (!this.subMeshes) {
  19982. return;
  19983. }
  19984. this._unBindEffect();
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19990. /**
  19991. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19992. * @see http://doc.babylonjs.com/babylon101/shadows
  19993. */
  19994. get: function () {
  19995. return this._receiveShadows;
  19996. },
  19997. set: function (value) {
  19998. if (this._receiveShadows === value) {
  19999. return;
  20000. }
  20001. this._receiveShadows = value;
  20002. this._markSubMeshesAsLightDirty();
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20008. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20009. get: function () {
  20010. return this._hasVertexAlpha;
  20011. },
  20012. set: function (value) {
  20013. if (this._hasVertexAlpha === value) {
  20014. return;
  20015. }
  20016. this._hasVertexAlpha = value;
  20017. this._markSubMeshesAsAttributesDirty();
  20018. this._markSubMeshesAsMiscDirty();
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20024. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20025. get: function () {
  20026. return this._useVertexColors;
  20027. },
  20028. set: function (value) {
  20029. if (this._useVertexColors === value) {
  20030. return;
  20031. }
  20032. this._useVertexColors = value;
  20033. this._markSubMeshesAsAttributesDirty();
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20039. /**
  20040. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20041. */
  20042. get: function () {
  20043. return this._computeBonesUsingShaders;
  20044. },
  20045. set: function (value) {
  20046. if (this._computeBonesUsingShaders === value) {
  20047. return;
  20048. }
  20049. this._computeBonesUsingShaders = value;
  20050. this._markSubMeshesAsAttributesDirty();
  20051. },
  20052. enumerable: true,
  20053. configurable: true
  20054. });
  20055. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20056. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20057. get: function () {
  20058. return this._numBoneInfluencers;
  20059. },
  20060. set: function (value) {
  20061. if (this._numBoneInfluencers === value) {
  20062. return;
  20063. }
  20064. this._numBoneInfluencers = value;
  20065. this._markSubMeshesAsAttributesDirty();
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20071. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20072. get: function () {
  20073. return this._applyFog;
  20074. },
  20075. set: function (value) {
  20076. if (this._applyFog === value) {
  20077. return;
  20078. }
  20079. this._applyFog = value;
  20080. this._markSubMeshesAsMiscDirty();
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20086. /**
  20087. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20088. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20089. */
  20090. get: function () {
  20091. return this._layerMask;
  20092. },
  20093. set: function (value) {
  20094. if (value === this._layerMask) {
  20095. return;
  20096. }
  20097. this._layerMask = value;
  20098. this._resyncLightSources();
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20104. /**
  20105. * Gets or sets a collision mask used to mask collisions (default is -1).
  20106. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20107. */
  20108. get: function () {
  20109. return this._collisionMask;
  20110. },
  20111. set: function (mask) {
  20112. this._collisionMask = !isNaN(mask) ? mask : -1;
  20113. },
  20114. enumerable: true,
  20115. configurable: true
  20116. });
  20117. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20118. /**
  20119. * Gets or sets the current collision group mask (-1 by default).
  20120. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20121. */
  20122. get: function () {
  20123. return this._collisionGroup;
  20124. },
  20125. set: function (mask) {
  20126. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20127. },
  20128. enumerable: true,
  20129. configurable: true
  20130. });
  20131. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20132. /** @hidden */
  20133. get: function () {
  20134. return null;
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20140. get: function () {
  20141. return this._skeleton;
  20142. },
  20143. /**
  20144. * Gets or sets a skeleton to apply skining transformations
  20145. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20146. */
  20147. set: function (value) {
  20148. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20149. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20150. }
  20151. if (value && value.needInitialSkinMatrix) {
  20152. value._registerMeshWithPoseMatrix(this);
  20153. }
  20154. this._skeleton = value;
  20155. if (!this._skeleton) {
  20156. this._bonesTransformMatrices = null;
  20157. }
  20158. this._markSubMeshesAsAttributesDirty();
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. /**
  20164. * Returns the string "AbstractMesh"
  20165. * @returns "AbstractMesh"
  20166. */
  20167. AbstractMesh.prototype.getClassName = function () {
  20168. return "AbstractMesh";
  20169. };
  20170. /**
  20171. * Gets a string representation of the current mesh
  20172. * @param fullDetails defines a boolean indicating if full details must be included
  20173. * @returns a string representation of the current mesh
  20174. */
  20175. AbstractMesh.prototype.toString = function (fullDetails) {
  20176. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20177. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20178. if (this._skeleton) {
  20179. ret += ", skeleton: " + this._skeleton.name;
  20180. }
  20181. if (fullDetails) {
  20182. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20183. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20184. }
  20185. return ret;
  20186. };
  20187. /** @hidden */
  20188. AbstractMesh.prototype._rebuild = function () {
  20189. if (this._occlusionQuery) {
  20190. this._occlusionQuery = null;
  20191. }
  20192. if (this._edgesRenderer) {
  20193. this._edgesRenderer._rebuild();
  20194. }
  20195. if (!this.subMeshes) {
  20196. return;
  20197. }
  20198. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20199. var subMesh = _a[_i];
  20200. subMesh._rebuild();
  20201. }
  20202. };
  20203. /** @hidden */
  20204. AbstractMesh.prototype._resyncLightSources = function () {
  20205. this._lightSources.length = 0;
  20206. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20207. var light = _a[_i];
  20208. if (!light.isEnabled()) {
  20209. continue;
  20210. }
  20211. if (light.canAffectMesh(this)) {
  20212. this._lightSources.push(light);
  20213. }
  20214. }
  20215. this._markSubMeshesAsLightDirty();
  20216. };
  20217. /** @hidden */
  20218. AbstractMesh.prototype._resyncLighSource = function (light) {
  20219. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20220. var index = this._lightSources.indexOf(light);
  20221. if (index === -1) {
  20222. if (!isIn) {
  20223. return;
  20224. }
  20225. this._lightSources.push(light);
  20226. }
  20227. else {
  20228. if (isIn) {
  20229. return;
  20230. }
  20231. this._lightSources.splice(index, 1);
  20232. }
  20233. this._markSubMeshesAsLightDirty();
  20234. };
  20235. /** @hidden */
  20236. AbstractMesh.prototype._unBindEffect = function () {
  20237. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20238. var subMesh = _a[_i];
  20239. subMesh.setEffect(null);
  20240. }
  20241. };
  20242. /** @hidden */
  20243. AbstractMesh.prototype._removeLightSource = function (light) {
  20244. var index = this._lightSources.indexOf(light);
  20245. if (index === -1) {
  20246. return;
  20247. }
  20248. this._lightSources.splice(index, 1);
  20249. this._markSubMeshesAsLightDirty();
  20250. };
  20251. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20252. if (!this.subMeshes) {
  20253. return;
  20254. }
  20255. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20256. var subMesh = _a[_i];
  20257. if (subMesh._materialDefines) {
  20258. func(subMesh._materialDefines);
  20259. }
  20260. }
  20261. };
  20262. /** @hidden */
  20263. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20264. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20265. };
  20266. /** @hidden */
  20267. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20268. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20269. };
  20270. /** @hidden */
  20271. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20272. if (!this.subMeshes) {
  20273. return;
  20274. }
  20275. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20276. var subMesh = _a[_i];
  20277. var material = subMesh.getMaterial();
  20278. if (material) {
  20279. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20280. }
  20281. }
  20282. };
  20283. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20284. /**
  20285. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20286. */
  20287. get: function () {
  20288. return this._scaling;
  20289. },
  20290. set: function (newScaling) {
  20291. this._scaling = newScaling;
  20292. if (this.physicsImpostor) {
  20293. this.physicsImpostor.forceUpdate();
  20294. }
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. // Methods
  20300. /**
  20301. * Disables the mesh edge rendering mode
  20302. * @returns the currentAbstractMesh
  20303. */
  20304. AbstractMesh.prototype.disableEdgesRendering = function () {
  20305. if (this._edgesRenderer) {
  20306. this._edgesRenderer.dispose();
  20307. this._edgesRenderer = null;
  20308. }
  20309. return this;
  20310. };
  20311. /**
  20312. * Enables the edge rendering mode on the mesh.
  20313. * This mode makes the mesh edges visible
  20314. * @param epsilon defines the maximal distance between two angles to detect a face
  20315. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20316. * @returns the currentAbstractMesh
  20317. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20318. */
  20319. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20320. if (epsilon === void 0) { epsilon = 0.95; }
  20321. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20322. this.disableEdgesRendering();
  20323. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20324. return this;
  20325. };
  20326. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20327. /**
  20328. * Gets the edgesRenderer associated with the mesh
  20329. */
  20330. get: function () {
  20331. return this._edgesRenderer;
  20332. },
  20333. enumerable: true,
  20334. configurable: true
  20335. });
  20336. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20337. /**
  20338. * Returns true if the mesh is blocked. Implemented by child classes
  20339. */
  20340. get: function () {
  20341. return false;
  20342. },
  20343. enumerable: true,
  20344. configurable: true
  20345. });
  20346. /**
  20347. * Returns the mesh itself by default. Implemented by child classes
  20348. * @param camera defines the camera to use to pick the right LOD level
  20349. * @returns the currentAbstractMesh
  20350. */
  20351. AbstractMesh.prototype.getLOD = function (camera) {
  20352. return this;
  20353. };
  20354. /**
  20355. * Returns 0 by default. Implemented by child classes
  20356. * @returns an integer
  20357. */
  20358. AbstractMesh.prototype.getTotalVertices = function () {
  20359. return 0;
  20360. };
  20361. /**
  20362. * Returns null by default. Implemented by child classes
  20363. * @returns null
  20364. */
  20365. AbstractMesh.prototype.getIndices = function () {
  20366. return null;
  20367. };
  20368. /**
  20369. * Returns the array of the requested vertex data kind. Implemented by child classes
  20370. * @param kind defines the vertex data kind to use
  20371. * @returns null
  20372. */
  20373. AbstractMesh.prototype.getVerticesData = function (kind) {
  20374. return null;
  20375. };
  20376. /**
  20377. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20378. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20379. * Note that a new underlying VertexBuffer object is created each call.
  20380. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20381. * @param kind defines vertex data kind:
  20382. * * BABYLON.VertexBuffer.PositionKind
  20383. * * BABYLON.VertexBuffer.UVKind
  20384. * * BABYLON.VertexBuffer.UV2Kind
  20385. * * BABYLON.VertexBuffer.UV3Kind
  20386. * * BABYLON.VertexBuffer.UV4Kind
  20387. * * BABYLON.VertexBuffer.UV5Kind
  20388. * * BABYLON.VertexBuffer.UV6Kind
  20389. * * BABYLON.VertexBuffer.ColorKind
  20390. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20391. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20392. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20393. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20394. * @param data defines the data source
  20395. * @param updatable defines if the data must be flagged as updatable (or static)
  20396. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20397. * @returns the current mesh
  20398. */
  20399. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20400. return this;
  20401. };
  20402. /**
  20403. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20404. * If the mesh has no geometry, it is simply returned as it is.
  20405. * @param kind defines vertex data kind:
  20406. * * BABYLON.VertexBuffer.PositionKind
  20407. * * BABYLON.VertexBuffer.UVKind
  20408. * * BABYLON.VertexBuffer.UV2Kind
  20409. * * BABYLON.VertexBuffer.UV3Kind
  20410. * * BABYLON.VertexBuffer.UV4Kind
  20411. * * BABYLON.VertexBuffer.UV5Kind
  20412. * * BABYLON.VertexBuffer.UV6Kind
  20413. * * BABYLON.VertexBuffer.ColorKind
  20414. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20415. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20416. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20417. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20418. * @param data defines the data source
  20419. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20420. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20421. * @returns the current mesh
  20422. */
  20423. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20424. return this;
  20425. };
  20426. /**
  20427. * Sets the mesh indices,
  20428. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20429. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20430. * @param totalVertices Defines the total number of vertices
  20431. * @returns the current mesh
  20432. */
  20433. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20434. return this;
  20435. };
  20436. /**
  20437. * Gets a boolean indicating if specific vertex data is present
  20438. * @param kind defines the vertex data kind to use
  20439. * @returns true is data kind is present
  20440. */
  20441. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20442. return false;
  20443. };
  20444. /**
  20445. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20446. * @returns a BoundingInfo
  20447. */
  20448. AbstractMesh.prototype.getBoundingInfo = function () {
  20449. if (this._masterMesh) {
  20450. return this._masterMesh.getBoundingInfo();
  20451. }
  20452. if (!this._boundingInfo) {
  20453. // this._boundingInfo is being created here
  20454. this._updateBoundingInfo();
  20455. }
  20456. // cannot be null.
  20457. return this._boundingInfo;
  20458. };
  20459. /**
  20460. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20461. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20462. * @returns the current mesh
  20463. */
  20464. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20465. if (includeDescendants === void 0) { includeDescendants = true; }
  20466. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20467. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20468. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20469. if (maxDimension === 0) {
  20470. return this;
  20471. }
  20472. var scale = 1 / maxDimension;
  20473. this.scaling.scaleInPlace(scale);
  20474. return this;
  20475. };
  20476. /**
  20477. * Overwrite the current bounding info
  20478. * @param boundingInfo defines the new bounding info
  20479. * @returns the current mesh
  20480. */
  20481. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20482. this._boundingInfo = boundingInfo;
  20483. return this;
  20484. };
  20485. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20486. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20487. get: function () {
  20488. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. /** @hidden */
  20494. AbstractMesh.prototype._preActivate = function () {
  20495. };
  20496. /** @hidden */
  20497. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20498. };
  20499. /** @hidden */
  20500. AbstractMesh.prototype._activate = function (renderId) {
  20501. this._renderId = renderId;
  20502. };
  20503. /**
  20504. * Gets the current world matrix
  20505. * @returns a Matrix
  20506. */
  20507. AbstractMesh.prototype.getWorldMatrix = function () {
  20508. if (this._masterMesh) {
  20509. return this._masterMesh.getWorldMatrix();
  20510. }
  20511. return _super.prototype.getWorldMatrix.call(this);
  20512. };
  20513. /** @hidden */
  20514. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20515. if (this._masterMesh) {
  20516. return this._masterMesh._getWorldMatrixDeterminant();
  20517. }
  20518. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20519. };
  20520. // ================================== Point of View Movement =================================
  20521. /**
  20522. * Perform relative position change from the point of view of behind the front of the mesh.
  20523. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20524. * Supports definition of mesh facing forward or backward
  20525. * @param amountRight defines the distance on the right axis
  20526. * @param amountUp defines the distance on the up axis
  20527. * @param amountForward defines the distance on the forward axis
  20528. * @returns the current mesh
  20529. */
  20530. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20531. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20532. return this;
  20533. };
  20534. /**
  20535. * Calculate relative position change from the point of view of behind the front of the mesh.
  20536. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20537. * Supports definition of mesh facing forward or backward
  20538. * @param amountRight defines the distance on the right axis
  20539. * @param amountUp defines the distance on the up axis
  20540. * @param amountForward defines the distance on the forward axis
  20541. * @returns the new displacement vector
  20542. */
  20543. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20544. var rotMatrix = new BABYLON.Matrix();
  20545. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20546. rotQuaternion.toRotationMatrix(rotMatrix);
  20547. var translationDelta = BABYLON.Vector3.Zero();
  20548. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20549. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20550. return translationDelta;
  20551. };
  20552. // ================================== Point of View Rotation =================================
  20553. /**
  20554. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20555. * Supports definition of mesh facing forward or backward
  20556. * @param flipBack defines the flip
  20557. * @param twirlClockwise defines the twirl
  20558. * @param tiltRight defines the tilt
  20559. * @returns the current mesh
  20560. */
  20561. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20562. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20563. return this;
  20564. };
  20565. /**
  20566. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20567. * Supports definition of mesh facing forward or backward.
  20568. * @param flipBack defines the flip
  20569. * @param twirlClockwise defines the twirl
  20570. * @param tiltRight defines the tilt
  20571. * @returns the new rotation vector
  20572. */
  20573. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20574. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20575. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20576. };
  20577. /**
  20578. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20579. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20580. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20581. * @returns the new bounding vectors
  20582. */
  20583. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20584. if (includeDescendants === void 0) { includeDescendants = true; }
  20585. if (predicate === void 0) { predicate = null; }
  20586. // Ensures that all world matrix will be recomputed.
  20587. this.getScene().incrementRenderId();
  20588. this.computeWorldMatrix(true);
  20589. var min;
  20590. var max;
  20591. var boundingInfo = this.getBoundingInfo();
  20592. if (!this.subMeshes) {
  20593. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20594. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20595. }
  20596. else {
  20597. min = boundingInfo.boundingBox.minimumWorld;
  20598. max = boundingInfo.boundingBox.maximumWorld;
  20599. }
  20600. if (includeDescendants) {
  20601. var descendants = this.getDescendants(false);
  20602. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20603. var descendant = descendants_1[_i];
  20604. var childMesh = descendant;
  20605. childMesh.computeWorldMatrix(true);
  20606. // Filters meshes based on custom predicate function.
  20607. if (predicate && !predicate(childMesh)) {
  20608. continue;
  20609. }
  20610. //make sure we have the needed params to get mix and max
  20611. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20612. continue;
  20613. }
  20614. var childBoundingInfo = childMesh.getBoundingInfo();
  20615. var boundingBox = childBoundingInfo.boundingBox;
  20616. var minBox = boundingBox.minimumWorld;
  20617. var maxBox = boundingBox.maximumWorld;
  20618. BABYLON.Tools.CheckExtends(minBox, min, max);
  20619. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20620. }
  20621. }
  20622. return {
  20623. min: min,
  20624. max: max
  20625. };
  20626. };
  20627. /** @hidden */
  20628. AbstractMesh.prototype._updateBoundingInfo = function () {
  20629. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20630. this._boundingInfo.update(this.worldMatrixFromCache);
  20631. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20632. return this;
  20633. };
  20634. /** @hidden */
  20635. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20636. if (!this.subMeshes) {
  20637. return this;
  20638. }
  20639. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20640. var subMesh = this.subMeshes[subIndex];
  20641. if (!subMesh.IsGlobal) {
  20642. subMesh.updateBoundingInfo(matrix);
  20643. }
  20644. }
  20645. return this;
  20646. };
  20647. /** @hidden */
  20648. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20649. // Bounding info
  20650. this._updateBoundingInfo();
  20651. };
  20652. /**
  20653. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20654. * A mesh is in the frustum if its bounding box intersects the frustum
  20655. * @param frustumPlanes defines the frustum to test
  20656. * @returns true if the mesh is in the frustum planes
  20657. */
  20658. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20659. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20660. };
  20661. /**
  20662. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20663. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20664. * @param frustumPlanes defines the frustum to test
  20665. * @returns true if the mesh is completely in the frustum planes
  20666. */
  20667. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20668. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20669. };
  20670. /**
  20671. * True if the mesh intersects another mesh or a SolidParticle object
  20672. * @param mesh defines a target mesh or SolidParticle to test
  20673. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20674. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20675. * @returns true if there is an intersection
  20676. */
  20677. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20678. if (precise === void 0) { precise = false; }
  20679. if (!this._boundingInfo || !mesh._boundingInfo) {
  20680. return false;
  20681. }
  20682. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20683. return true;
  20684. }
  20685. if (includeDescendants) {
  20686. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20687. var child = _a[_i];
  20688. if (child.intersectsMesh(mesh, precise, true)) {
  20689. return true;
  20690. }
  20691. }
  20692. }
  20693. return false;
  20694. };
  20695. /**
  20696. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20697. * @param point defines the point to test
  20698. * @returns true if there is an intersection
  20699. */
  20700. AbstractMesh.prototype.intersectsPoint = function (point) {
  20701. if (!this._boundingInfo) {
  20702. return false;
  20703. }
  20704. return this._boundingInfo.intersectsPoint(point);
  20705. };
  20706. /**
  20707. * Gets the current physics impostor
  20708. * @see http://doc.babylonjs.com/features/physics_engine
  20709. * @returns a physics impostor or null
  20710. */
  20711. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20712. return this.physicsImpostor;
  20713. };
  20714. /**
  20715. * Gets the position of the current mesh in camera space
  20716. * @param camera defines the camera to use
  20717. * @returns a position
  20718. */
  20719. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20720. if (camera === void 0) { camera = null; }
  20721. if (!camera) {
  20722. camera = this.getScene().activeCamera;
  20723. }
  20724. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20725. };
  20726. /**
  20727. * Returns the distance from the mesh to the active camera
  20728. * @param camera defines the camera to use
  20729. * @returns the distance
  20730. */
  20731. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20732. if (camera === void 0) { camera = null; }
  20733. if (!camera) {
  20734. camera = this.getScene().activeCamera;
  20735. }
  20736. return this.absolutePosition.subtract(camera.position).length();
  20737. };
  20738. /**
  20739. * Apply a physic impulse to the mesh
  20740. * @param force defines the force to apply
  20741. * @param contactPoint defines where to apply the force
  20742. * @returns the current mesh
  20743. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20744. */
  20745. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20746. if (!this.physicsImpostor) {
  20747. return this;
  20748. }
  20749. this.physicsImpostor.applyImpulse(force, contactPoint);
  20750. return this;
  20751. };
  20752. /**
  20753. * Creates a physic joint between two meshes
  20754. * @param otherMesh defines the other mesh to use
  20755. * @param pivot1 defines the pivot to use on this mesh
  20756. * @param pivot2 defines the pivot to use on the other mesh
  20757. * @param options defines additional options (can be plugin dependent)
  20758. * @returns the current mesh
  20759. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20760. */
  20761. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20762. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20763. return this;
  20764. }
  20765. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20766. mainPivot: pivot1,
  20767. connectedPivot: pivot2,
  20768. nativeParams: options
  20769. });
  20770. return this;
  20771. };
  20772. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20773. // Collisions
  20774. /**
  20775. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20776. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20777. */
  20778. get: function () {
  20779. return this._checkCollisions;
  20780. },
  20781. set: function (collisionEnabled) {
  20782. this._checkCollisions = collisionEnabled;
  20783. if (this.getScene().workerCollisions) {
  20784. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20785. }
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20791. /**
  20792. * Gets Collider object used to compute collisions (not physics)
  20793. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20794. */
  20795. get: function () {
  20796. return this._collider;
  20797. },
  20798. enumerable: true,
  20799. configurable: true
  20800. });
  20801. /**
  20802. * Move the mesh using collision engine
  20803. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20804. * @param displacement defines the requested displacement vector
  20805. * @returns the current mesh
  20806. */
  20807. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20808. var globalPosition = this.getAbsolutePosition();
  20809. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20810. if (!this._collider) {
  20811. this._collider = new BABYLON.Collider();
  20812. }
  20813. this._collider._radius = this.ellipsoid;
  20814. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20815. return this;
  20816. };
  20817. // Submeshes octree
  20818. /**
  20819. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20820. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20821. * @param maxCapacity defines the maximum size of each block (64 by default)
  20822. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20823. * @returns the new octree
  20824. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20825. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20826. */
  20827. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20828. if (maxCapacity === void 0) { maxCapacity = 64; }
  20829. if (maxDepth === void 0) { maxDepth = 2; }
  20830. if (!this._submeshesOctree) {
  20831. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20832. }
  20833. this.computeWorldMatrix(true);
  20834. var boundingInfo = this.getBoundingInfo();
  20835. // Update octree
  20836. var bbox = boundingInfo.boundingBox;
  20837. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20838. return this._submeshesOctree;
  20839. };
  20840. // Collisions
  20841. /** @hidden */
  20842. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20843. this._generatePointsArray();
  20844. if (!this._positions) {
  20845. return this;
  20846. }
  20847. // Transformation
  20848. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20849. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20850. subMesh._lastColliderWorldVertices = [];
  20851. subMesh._trianglePlanes = [];
  20852. var start = subMesh.verticesStart;
  20853. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20854. for (var i = start; i < end; i++) {
  20855. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20856. }
  20857. }
  20858. // Collide
  20859. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20860. if (collider.collisionFound) {
  20861. collider.collidedMesh = this;
  20862. }
  20863. return this;
  20864. };
  20865. /** @hidden */
  20866. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20867. var subMeshes;
  20868. var len;
  20869. // Octrees
  20870. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20871. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20872. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20873. len = intersections.length;
  20874. subMeshes = intersections.data;
  20875. }
  20876. else {
  20877. subMeshes = this.subMeshes;
  20878. len = subMeshes.length;
  20879. }
  20880. for (var index = 0; index < len; index++) {
  20881. var subMesh = subMeshes[index];
  20882. // Bounding test
  20883. if (len > 1 && !subMesh._checkCollision(collider))
  20884. continue;
  20885. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20886. }
  20887. return this;
  20888. };
  20889. /** @hidden */
  20890. AbstractMesh.prototype._checkCollision = function (collider) {
  20891. // Bounding box test
  20892. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20893. return this;
  20894. // Transformation matrix
  20895. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20896. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20897. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20898. return this;
  20899. };
  20900. // Picking
  20901. /** @hidden */
  20902. AbstractMesh.prototype._generatePointsArray = function () {
  20903. return false;
  20904. };
  20905. /**
  20906. * Checks if the passed Ray intersects with the mesh
  20907. * @param ray defines the ray to use
  20908. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20909. * @returns the picking info
  20910. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20911. */
  20912. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20913. var pickingInfo = new BABYLON.PickingInfo();
  20914. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20915. return pickingInfo;
  20916. }
  20917. if (!this._generatePointsArray()) {
  20918. return pickingInfo;
  20919. }
  20920. var intersectInfo = null;
  20921. // Octrees
  20922. var subMeshes;
  20923. var len;
  20924. if (this._submeshesOctree && this.useOctreeForPicking) {
  20925. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20926. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20927. len = intersections.length;
  20928. subMeshes = intersections.data;
  20929. }
  20930. else {
  20931. subMeshes = this.subMeshes;
  20932. len = subMeshes.length;
  20933. }
  20934. for (var index = 0; index < len; index++) {
  20935. var subMesh = subMeshes[index];
  20936. // Bounding test
  20937. if (len > 1 && !subMesh.canIntersects(ray))
  20938. continue;
  20939. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20940. if (currentIntersectInfo) {
  20941. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20942. intersectInfo = currentIntersectInfo;
  20943. intersectInfo.subMeshId = index;
  20944. if (fastCheck) {
  20945. break;
  20946. }
  20947. }
  20948. }
  20949. }
  20950. if (intersectInfo) {
  20951. // Get picked point
  20952. var world = this.getWorldMatrix();
  20953. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20954. var direction = ray.direction.clone();
  20955. direction = direction.scale(intersectInfo.distance);
  20956. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20957. var pickedPoint = worldOrigin.add(worldDirection);
  20958. // Return result
  20959. pickingInfo.hit = true;
  20960. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20961. pickingInfo.pickedPoint = pickedPoint;
  20962. pickingInfo.pickedMesh = this;
  20963. pickingInfo.bu = intersectInfo.bu || 0;
  20964. pickingInfo.bv = intersectInfo.bv || 0;
  20965. pickingInfo.faceId = intersectInfo.faceId;
  20966. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20967. return pickingInfo;
  20968. }
  20969. return pickingInfo;
  20970. };
  20971. /**
  20972. * Clones the current mesh
  20973. * @param name defines the mesh name
  20974. * @param newParent defines the new mesh parent
  20975. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20976. * @returns the new mesh
  20977. */
  20978. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20979. return null;
  20980. };
  20981. /**
  20982. * Disposes all the submeshes of the current meshnp
  20983. * @returns the current mesh
  20984. */
  20985. AbstractMesh.prototype.releaseSubMeshes = function () {
  20986. if (this.subMeshes) {
  20987. while (this.subMeshes.length) {
  20988. this.subMeshes[0].dispose();
  20989. }
  20990. }
  20991. else {
  20992. this.subMeshes = new Array();
  20993. }
  20994. return this;
  20995. };
  20996. /**
  20997. * Releases resources associated with this abstract mesh.
  20998. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20999. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21000. */
  21001. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21002. var _this = this;
  21003. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21004. var index;
  21005. // Smart Array Retainers.
  21006. this.getScene().freeActiveMeshes();
  21007. this.getScene().freeRenderingGroups();
  21008. // Action manager
  21009. if (this.actionManager !== undefined && this.actionManager !== null) {
  21010. this.actionManager.dispose();
  21011. this.actionManager = null;
  21012. }
  21013. // Skeleton
  21014. this._skeleton = null;
  21015. // Physics
  21016. if (this.physicsImpostor) {
  21017. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21018. }
  21019. // Intersections in progress
  21020. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21021. var other = this._intersectionsInProgress[index];
  21022. var pos = other._intersectionsInProgress.indexOf(this);
  21023. other._intersectionsInProgress.splice(pos, 1);
  21024. }
  21025. this._intersectionsInProgress = [];
  21026. // Lights
  21027. var lights = this.getScene().lights;
  21028. lights.forEach(function (light) {
  21029. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21030. if (meshIndex !== -1) {
  21031. light.includedOnlyMeshes.splice(meshIndex, 1);
  21032. }
  21033. meshIndex = light.excludedMeshes.indexOf(_this);
  21034. if (meshIndex !== -1) {
  21035. light.excludedMeshes.splice(meshIndex, 1);
  21036. }
  21037. // Shadow generators
  21038. var generator = light.getShadowGenerator();
  21039. if (generator) {
  21040. var shadowMap = generator.getShadowMap();
  21041. if (shadowMap && shadowMap.renderList) {
  21042. meshIndex = shadowMap.renderList.indexOf(_this);
  21043. if (meshIndex !== -1) {
  21044. shadowMap.renderList.splice(meshIndex, 1);
  21045. }
  21046. }
  21047. }
  21048. });
  21049. // Edges
  21050. if (this._edgesRenderer) {
  21051. this._edgesRenderer.dispose();
  21052. this._edgesRenderer = null;
  21053. }
  21054. // SubMeshes
  21055. if (this.getClassName() !== "InstancedMesh") {
  21056. this.releaseSubMeshes();
  21057. }
  21058. // Octree
  21059. var sceneOctree = this.getScene().selectionOctree;
  21060. if (sceneOctree !== undefined && sceneOctree !== null) {
  21061. var index = sceneOctree.dynamicContent.indexOf(this);
  21062. if (index !== -1) {
  21063. sceneOctree.dynamicContent.splice(index, 1);
  21064. }
  21065. }
  21066. // Query
  21067. var engine = this.getScene().getEngine();
  21068. if (this._occlusionQuery) {
  21069. this._isOcclusionQueryInProgress = false;
  21070. engine.deleteQuery(this._occlusionQuery);
  21071. this._occlusionQuery = null;
  21072. }
  21073. // Engine
  21074. engine.wipeCaches();
  21075. // Remove from scene
  21076. this.getScene().removeMesh(this);
  21077. if (disposeMaterialAndTextures) {
  21078. if (this.material) {
  21079. this.material.dispose(false, true);
  21080. }
  21081. }
  21082. if (!doNotRecurse) {
  21083. // Particles
  21084. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21085. if (this.getScene().particleSystems[index].emitter === this) {
  21086. this.getScene().particleSystems[index].dispose();
  21087. index--;
  21088. }
  21089. }
  21090. }
  21091. // facet data
  21092. if (this._facetDataEnabled) {
  21093. this.disableFacetData();
  21094. }
  21095. this.onAfterWorldMatrixUpdateObservable.clear();
  21096. this.onCollideObservable.clear();
  21097. this.onCollisionPositionChangeObservable.clear();
  21098. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21099. };
  21100. /**
  21101. * Adds the passed mesh as a child to the current mesh
  21102. * @param mesh defines the child mesh
  21103. * @returns the current mesh
  21104. */
  21105. AbstractMesh.prototype.addChild = function (mesh) {
  21106. mesh.setParent(this);
  21107. return this;
  21108. };
  21109. /**
  21110. * Removes the passed mesh from the current mesh children list
  21111. * @param mesh defines the child mesh
  21112. * @returns the current mesh
  21113. */
  21114. AbstractMesh.prototype.removeChild = function (mesh) {
  21115. mesh.setParent(null);
  21116. return this;
  21117. };
  21118. // Facet data
  21119. /** @hidden */
  21120. AbstractMesh.prototype._initFacetData = function () {
  21121. if (!this._facetNormals) {
  21122. this._facetNormals = new Array();
  21123. }
  21124. if (!this._facetPositions) {
  21125. this._facetPositions = new Array();
  21126. }
  21127. if (!this._facetPartitioning) {
  21128. this._facetPartitioning = new Array();
  21129. }
  21130. this._facetNb = (this.getIndices().length / 3) | 0;
  21131. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21132. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21133. for (var f = 0; f < this._facetNb; f++) {
  21134. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21135. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21136. }
  21137. this._facetDataEnabled = true;
  21138. return this;
  21139. };
  21140. /**
  21141. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21142. * This method can be called within the render loop.
  21143. * 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
  21144. * @returns the current mesh
  21145. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21146. */
  21147. AbstractMesh.prototype.updateFacetData = function () {
  21148. if (!this._facetDataEnabled) {
  21149. this._initFacetData();
  21150. }
  21151. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21152. var indices = this.getIndices();
  21153. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21154. var bInfo = this.getBoundingInfo();
  21155. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21156. // init arrays, matrix and sort function on first call
  21157. this._facetDepthSortEnabled = true;
  21158. if (indices instanceof Uint16Array) {
  21159. this._depthSortedIndices = new Uint16Array(indices);
  21160. }
  21161. else if (indices instanceof Uint32Array) {
  21162. this._depthSortedIndices = new Uint32Array(indices);
  21163. }
  21164. else {
  21165. var needs32bits = false;
  21166. for (var i = 0; i < indices.length; i++) {
  21167. if (indices[i] > 65535) {
  21168. needs32bits = true;
  21169. break;
  21170. }
  21171. }
  21172. if (needs32bits) {
  21173. this._depthSortedIndices = new Uint32Array(indices);
  21174. }
  21175. else {
  21176. this._depthSortedIndices = new Uint16Array(indices);
  21177. }
  21178. }
  21179. this._facetDepthSortFunction = function (f1, f2) {
  21180. return (f2.sqDistance - f1.sqDistance);
  21181. };
  21182. if (!this._facetDepthSortFrom) {
  21183. var camera = this.getScene().activeCamera;
  21184. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21185. }
  21186. this._depthSortedFacets = [];
  21187. for (var f = 0; f < this._facetNb; f++) {
  21188. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21189. this._depthSortedFacets.push(depthSortedFacet);
  21190. }
  21191. this._invertedMatrix = BABYLON.Matrix.Identity();
  21192. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21193. }
  21194. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21195. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21196. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21197. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21198. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21199. this._subDiv.max = this._partitioningSubdivisions;
  21200. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21201. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21202. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21203. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21204. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21205. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21206. // set the parameters for ComputeNormals()
  21207. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21208. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21209. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21210. this._facetParameters.bInfo = bInfo;
  21211. this._facetParameters.bbSize = this._bbSize;
  21212. this._facetParameters.subDiv = this._subDiv;
  21213. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21214. this._facetParameters.depthSort = this._facetDepthSort;
  21215. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21216. this.computeWorldMatrix(true);
  21217. this._worldMatrix.invertToRef(this._invertedMatrix);
  21218. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21219. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21220. }
  21221. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21222. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21223. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21224. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21225. var l = (this._depthSortedIndices.length / 3) | 0;
  21226. for (var f = 0; f < l; f++) {
  21227. var sind = this._depthSortedFacets[f].ind;
  21228. this._depthSortedIndices[f * 3] = indices[sind];
  21229. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21230. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21231. }
  21232. this.updateIndices(this._depthSortedIndices);
  21233. }
  21234. return this;
  21235. };
  21236. /**
  21237. * Returns the facetLocalNormals array.
  21238. * The normals are expressed in the mesh local spac
  21239. * @returns an array of Vector3
  21240. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21241. */
  21242. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21243. if (!this._facetNormals) {
  21244. this.updateFacetData();
  21245. }
  21246. return this._facetNormals;
  21247. };
  21248. /**
  21249. * Returns the facetLocalPositions array.
  21250. * The facet positions are expressed in the mesh local space
  21251. * @returns an array of Vector3
  21252. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21253. */
  21254. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21255. if (!this._facetPositions) {
  21256. this.updateFacetData();
  21257. }
  21258. return this._facetPositions;
  21259. };
  21260. /**
  21261. * Returns the facetLocalPartioning array
  21262. * @returns an array of array of numbers
  21263. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21264. */
  21265. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21266. if (!this._facetPartitioning) {
  21267. this.updateFacetData();
  21268. }
  21269. return this._facetPartitioning;
  21270. };
  21271. /**
  21272. * Returns the i-th facet position in the world system.
  21273. * This method allocates a new Vector3 per call
  21274. * @param i defines the facet index
  21275. * @returns a new Vector3
  21276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21277. */
  21278. AbstractMesh.prototype.getFacetPosition = function (i) {
  21279. var pos = BABYLON.Vector3.Zero();
  21280. this.getFacetPositionToRef(i, pos);
  21281. return pos;
  21282. };
  21283. /**
  21284. * Sets the reference Vector3 with the i-th facet position in the world system
  21285. * @param i defines the facet index
  21286. * @param ref defines the target vector
  21287. * @returns the current mesh
  21288. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21289. */
  21290. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21291. var localPos = (this.getFacetLocalPositions())[i];
  21292. var world = this.getWorldMatrix();
  21293. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21294. return this;
  21295. };
  21296. /**
  21297. * Returns the i-th facet normal in the world system.
  21298. * This method allocates a new Vector3 per call
  21299. * @param i defines the facet index
  21300. * @returns a new Vector3
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21302. */
  21303. AbstractMesh.prototype.getFacetNormal = function (i) {
  21304. var norm = BABYLON.Vector3.Zero();
  21305. this.getFacetNormalToRef(i, norm);
  21306. return norm;
  21307. };
  21308. /**
  21309. * Sets the reference Vector3 with the i-th facet normal in the world system
  21310. * @param i defines the facet index
  21311. * @param ref defines the target vector
  21312. * @returns the current mesh
  21313. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21314. */
  21315. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21316. var localNorm = (this.getFacetLocalNormals())[i];
  21317. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21318. return this;
  21319. };
  21320. /**
  21321. * 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)
  21322. * @param x defines x coordinate
  21323. * @param y defines y coordinate
  21324. * @param z defines z coordinate
  21325. * @returns the array of facet indexes
  21326. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21327. */
  21328. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21329. var bInfo = this.getBoundingInfo();
  21330. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21331. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21332. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21333. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21334. return null;
  21335. }
  21336. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21337. };
  21338. /**
  21339. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21340. * @param projected sets as the (x,y,z) world projection on the facet
  21341. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21342. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21343. * @param x defines x coordinate
  21344. * @param y defines y coordinate
  21345. * @param z defines z coordinate
  21346. * @returns the face index if found (or null instead)
  21347. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21348. */
  21349. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21350. if (checkFace === void 0) { checkFace = false; }
  21351. if (facing === void 0) { facing = true; }
  21352. var world = this.getWorldMatrix();
  21353. var invMat = BABYLON.Tmp.Matrix[5];
  21354. world.invertToRef(invMat);
  21355. var invVect = BABYLON.Tmp.Vector3[8];
  21356. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21357. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21358. if (projected) {
  21359. // tranform the local computed projected vector to world coordinates
  21360. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21361. }
  21362. return closest;
  21363. };
  21364. /**
  21365. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21366. * @param projected sets as the (x,y,z) local projection on the facet
  21367. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21368. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21369. * @param x defines x coordinate
  21370. * @param y defines y coordinate
  21371. * @param z defines z coordinate
  21372. * @returns the face index if found (or null instead)
  21373. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21374. */
  21375. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21376. if (checkFace === void 0) { checkFace = false; }
  21377. if (facing === void 0) { facing = true; }
  21378. var closest = null;
  21379. var tmpx = 0.0;
  21380. var tmpy = 0.0;
  21381. var tmpz = 0.0;
  21382. var d = 0.0; // tmp dot facet normal * facet position
  21383. var t0 = 0.0;
  21384. var projx = 0.0;
  21385. var projy = 0.0;
  21386. var projz = 0.0;
  21387. // Get all the facets in the same partitioning block than (x, y, z)
  21388. var facetPositions = this.getFacetLocalPositions();
  21389. var facetNormals = this.getFacetLocalNormals();
  21390. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21391. if (!facetsInBlock) {
  21392. return null;
  21393. }
  21394. // Get the closest facet to (x, y, z)
  21395. var shortest = Number.MAX_VALUE; // init distance vars
  21396. var tmpDistance = shortest;
  21397. var fib; // current facet in the block
  21398. var norm; // current facet normal
  21399. var p0; // current facet barycenter position
  21400. // loop on all the facets in the current partitioning block
  21401. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21402. fib = facetsInBlock[idx];
  21403. norm = facetNormals[fib];
  21404. p0 = facetPositions[fib];
  21405. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21406. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21407. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21408. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21409. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21410. projx = x + norm.x * t0;
  21411. projy = y + norm.y * t0;
  21412. projz = z + norm.z * t0;
  21413. tmpx = projx - x;
  21414. tmpy = projy - y;
  21415. tmpz = projz - z;
  21416. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21417. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21418. shortest = tmpDistance;
  21419. closest = fib;
  21420. if (projected) {
  21421. projected.x = projx;
  21422. projected.y = projy;
  21423. projected.z = projz;
  21424. }
  21425. }
  21426. }
  21427. }
  21428. return closest;
  21429. };
  21430. /**
  21431. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21432. * @returns the parameters
  21433. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21434. */
  21435. AbstractMesh.prototype.getFacetDataParameters = function () {
  21436. return this._facetParameters;
  21437. };
  21438. /**
  21439. * Disables the feature FacetData and frees the related memory
  21440. * @returns the current mesh
  21441. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21442. */
  21443. AbstractMesh.prototype.disableFacetData = function () {
  21444. if (this._facetDataEnabled) {
  21445. this._facetDataEnabled = false;
  21446. this._facetPositions = new Array();
  21447. this._facetNormals = new Array();
  21448. this._facetPartitioning = new Array();
  21449. this._facetParameters = null;
  21450. this._depthSortedIndices = new Uint32Array(0);
  21451. }
  21452. return this;
  21453. };
  21454. /**
  21455. * Updates the AbstractMesh indices array
  21456. * @param indices defines the data source
  21457. * @returns the current mesh
  21458. */
  21459. AbstractMesh.prototype.updateIndices = function (indices) {
  21460. return this;
  21461. };
  21462. /**
  21463. * Creates new normals data for the mesh
  21464. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21465. * @returns the current mesh
  21466. */
  21467. AbstractMesh.prototype.createNormals = function (updatable) {
  21468. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21469. var indices = this.getIndices();
  21470. var normals;
  21471. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21472. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21473. }
  21474. else {
  21475. normals = [];
  21476. }
  21477. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21478. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21479. return this;
  21480. };
  21481. /**
  21482. * Align the mesh with a normal
  21483. * @param normal defines the normal to use
  21484. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21485. * @returns the current mesh
  21486. */
  21487. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21488. if (!upDirection) {
  21489. upDirection = BABYLON.Axis.Y;
  21490. }
  21491. var axisX = BABYLON.Tmp.Vector3[0];
  21492. var axisZ = BABYLON.Tmp.Vector3[1];
  21493. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21494. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21495. if (this.rotationQuaternion) {
  21496. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21497. }
  21498. else {
  21499. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21500. }
  21501. return this;
  21502. };
  21503. /** @hidden */
  21504. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21505. var engine = this.getEngine();
  21506. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21507. this._isOccluded = false;
  21508. return;
  21509. }
  21510. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21511. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21512. if (isOcclusionQueryAvailable) {
  21513. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21514. this._isOcclusionQueryInProgress = false;
  21515. this._occlusionInternalRetryCounter = 0;
  21516. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21517. }
  21518. else {
  21519. this._occlusionInternalRetryCounter++;
  21520. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21521. this._isOcclusionQueryInProgress = false;
  21522. this._occlusionInternalRetryCounter = 0;
  21523. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21524. // if strict continue the last state of the object.
  21525. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21526. }
  21527. else {
  21528. return;
  21529. }
  21530. }
  21531. }
  21532. var scene = this.getScene();
  21533. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21534. if (!this._occlusionQuery) {
  21535. this._occlusionQuery = engine.createQuery();
  21536. }
  21537. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21538. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21539. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21540. this._isOcclusionQueryInProgress = true;
  21541. };
  21542. /** No occlusion */
  21543. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21544. /** Occlusion set to optimisitic */
  21545. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21546. /** Occlusion set to strict */
  21547. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21548. /** Use an accurante occlusion algorithm */
  21549. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21550. /** Use a conservative occlusion algorithm */
  21551. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21552. return AbstractMesh;
  21553. }(BABYLON.TransformNode));
  21554. BABYLON.AbstractMesh = AbstractMesh;
  21555. })(BABYLON || (BABYLON = {}));
  21556. //# sourceMappingURL=babylon.abstractMesh.js.map
  21557. var BABYLON;
  21558. (function (BABYLON) {
  21559. /**
  21560. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21561. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21562. * 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.
  21563. */
  21564. var Light = /** @class */ (function (_super) {
  21565. __extends(Light, _super);
  21566. /**
  21567. * Creates a Light object in the scene.
  21568. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21569. * @param name The firendly name of the light
  21570. * @param scene The scene the light belongs too
  21571. */
  21572. function Light(name, scene) {
  21573. var _this = _super.call(this, name, scene) || this;
  21574. /**
  21575. * Diffuse gives the basic color to an object.
  21576. */
  21577. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21578. /**
  21579. * Specular produces a highlight color on an object.
  21580. * Note: This is note affecting PBR materials.
  21581. */
  21582. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21583. /**
  21584. * Strength of the light.
  21585. * Note: By default it is define in the framework own unit.
  21586. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21587. */
  21588. _this.intensity = 1.0;
  21589. /**
  21590. * Defines how far from the source the light is impacting in scene units.
  21591. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21592. */
  21593. _this.range = Number.MAX_VALUE;
  21594. /**
  21595. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21596. * of light.
  21597. */
  21598. _this._photometricScale = 1.0;
  21599. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21600. _this._radius = 0.00001;
  21601. /**
  21602. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21603. * exceeding the number allowed of the materials.
  21604. */
  21605. _this.renderPriority = 0;
  21606. _this._shadowEnabled = true;
  21607. _this._excludeWithLayerMask = 0;
  21608. _this._includeOnlyWithLayerMask = 0;
  21609. _this._lightmapMode = 0;
  21610. /**
  21611. * @hidden Internal use only.
  21612. */
  21613. _this._excludedMeshesIds = new Array();
  21614. /**
  21615. * @hidden Internal use only.
  21616. */
  21617. _this._includedOnlyMeshesIds = new Array();
  21618. _this.getScene().addLight(_this);
  21619. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21620. _this._buildUniformLayout();
  21621. _this.includedOnlyMeshes = new Array();
  21622. _this.excludedMeshes = new Array();
  21623. _this._resyncMeshes();
  21624. return _this;
  21625. }
  21626. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21627. /**
  21628. * If every light affecting the material is in this lightmapMode,
  21629. * material.lightmapTexture adds or multiplies
  21630. * (depends on material.useLightmapAsShadowmap)
  21631. * after every other light calculations.
  21632. */
  21633. get: function () {
  21634. return Light._LIGHTMAP_DEFAULT;
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21640. /**
  21641. * material.lightmapTexture as only diffuse lighting from this light
  21642. * adds only specular lighting from this light
  21643. * adds dynamic shadows
  21644. */
  21645. get: function () {
  21646. return Light._LIGHTMAP_SPECULAR;
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21652. /**
  21653. * material.lightmapTexture as only lighting
  21654. * no light calculation from this light
  21655. * only adds dynamic shadows from this light
  21656. */
  21657. get: function () {
  21658. return Light._LIGHTMAP_SHADOWSONLY;
  21659. },
  21660. enumerable: true,
  21661. configurable: true
  21662. });
  21663. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21664. /**
  21665. * Each light type uses the default quantity according to its type:
  21666. * point/spot lights use luminous intensity
  21667. * directional lights use illuminance
  21668. */
  21669. get: function () {
  21670. return Light._INTENSITYMODE_AUTOMATIC;
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21676. /**
  21677. * lumen (lm)
  21678. */
  21679. get: function () {
  21680. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21686. /**
  21687. * candela (lm/sr)
  21688. */
  21689. get: function () {
  21690. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21696. /**
  21697. * lux (lm/m^2)
  21698. */
  21699. get: function () {
  21700. return Light._INTENSITYMODE_ILLUMINANCE;
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21706. /**
  21707. * nit (cd/m^2)
  21708. */
  21709. get: function () {
  21710. return Light._INTENSITYMODE_LUMINANCE;
  21711. },
  21712. enumerable: true,
  21713. configurable: true
  21714. });
  21715. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21716. /**
  21717. * Light type const id of the point light.
  21718. */
  21719. get: function () {
  21720. return Light._LIGHTTYPEID_POINTLIGHT;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21726. /**
  21727. * Light type const id of the directional light.
  21728. */
  21729. get: function () {
  21730. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21736. /**
  21737. * Light type const id of the spot light.
  21738. */
  21739. get: function () {
  21740. return Light._LIGHTTYPEID_SPOTLIGHT;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21746. /**
  21747. * Light type const id of the hemispheric light.
  21748. */
  21749. get: function () {
  21750. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Light.prototype, "intensityMode", {
  21756. /**
  21757. * Gets the photometric scale used to interpret the intensity.
  21758. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21759. */
  21760. get: function () {
  21761. return this._intensityMode;
  21762. },
  21763. /**
  21764. * Sets the photometric scale used to interpret the intensity.
  21765. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21766. */
  21767. set: function (value) {
  21768. this._intensityMode = value;
  21769. this._computePhotometricScale();
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. ;
  21775. ;
  21776. Object.defineProperty(Light.prototype, "radius", {
  21777. /**
  21778. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21779. */
  21780. get: function () {
  21781. return this._radius;
  21782. },
  21783. /**
  21784. * sets the light radius used by PBR Materials to simulate soft area lights.
  21785. */
  21786. set: function (value) {
  21787. this._radius = value;
  21788. this._computePhotometricScale();
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. ;
  21794. ;
  21795. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21796. /**
  21797. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21798. * the current shadow generator.
  21799. */
  21800. get: function () {
  21801. return this._shadowEnabled;
  21802. },
  21803. /**
  21804. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21805. * the current shadow generator.
  21806. */
  21807. set: function (value) {
  21808. if (this._shadowEnabled === value) {
  21809. return;
  21810. }
  21811. this._shadowEnabled = value;
  21812. this._markMeshesAsLightDirty();
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21818. /**
  21819. * Gets the only meshes impacted by this light.
  21820. */
  21821. get: function () {
  21822. return this._includedOnlyMeshes;
  21823. },
  21824. /**
  21825. * Sets the only meshes impacted by this light.
  21826. */
  21827. set: function (value) {
  21828. this._includedOnlyMeshes = value;
  21829. this._hookArrayForIncludedOnly(value);
  21830. },
  21831. enumerable: true,
  21832. configurable: true
  21833. });
  21834. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21835. /**
  21836. * Gets the meshes not impacted by this light.
  21837. */
  21838. get: function () {
  21839. return this._excludedMeshes;
  21840. },
  21841. /**
  21842. * Sets the meshes not impacted by this light.
  21843. */
  21844. set: function (value) {
  21845. this._excludedMeshes = value;
  21846. this._hookArrayForExcluded(value);
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21852. /**
  21853. * Gets the layer id use to find what meshes are not impacted by the light.
  21854. * Inactive if 0
  21855. */
  21856. get: function () {
  21857. return this._excludeWithLayerMask;
  21858. },
  21859. /**
  21860. * Sets the layer id use to find what meshes are not impacted by the light.
  21861. * Inactive if 0
  21862. */
  21863. set: function (value) {
  21864. this._excludeWithLayerMask = value;
  21865. this._resyncMeshes();
  21866. },
  21867. enumerable: true,
  21868. configurable: true
  21869. });
  21870. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21871. /**
  21872. * Gets the layer id use to find what meshes are impacted by the light.
  21873. * Inactive if 0
  21874. */
  21875. get: function () {
  21876. return this._includeOnlyWithLayerMask;
  21877. },
  21878. /**
  21879. * Sets the layer id use to find what meshes are impacted by the light.
  21880. * Inactive if 0
  21881. */
  21882. set: function (value) {
  21883. this._includeOnlyWithLayerMask = value;
  21884. this._resyncMeshes();
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(Light.prototype, "lightmapMode", {
  21890. /**
  21891. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21892. */
  21893. get: function () {
  21894. return this._lightmapMode;
  21895. },
  21896. /**
  21897. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21898. */
  21899. set: function (value) {
  21900. if (this._lightmapMode === value) {
  21901. return;
  21902. }
  21903. this._lightmapMode = value;
  21904. this._markMeshesAsLightDirty();
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. /**
  21910. * Returns the string "Light".
  21911. * @returns the class name
  21912. */
  21913. Light.prototype.getClassName = function () {
  21914. return "Light";
  21915. };
  21916. /**
  21917. * Converts the light information to a readable string for debug purpose.
  21918. * @param fullDetails Supports for multiple levels of logging within scene loading
  21919. * @returns the human readable light info
  21920. */
  21921. Light.prototype.toString = function (fullDetails) {
  21922. var ret = "Name: " + this.name;
  21923. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21924. if (this.animations) {
  21925. for (var i = 0; i < this.animations.length; i++) {
  21926. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21927. }
  21928. }
  21929. if (fullDetails) {
  21930. }
  21931. return ret;
  21932. };
  21933. /**
  21934. * Set the enabled state of this node.
  21935. * @param value - the new enabled state
  21936. */
  21937. Light.prototype.setEnabled = function (value) {
  21938. _super.prototype.setEnabled.call(this, value);
  21939. this._resyncMeshes();
  21940. };
  21941. /**
  21942. * Returns the Light associated shadow generator if any.
  21943. * @return the associated shadow generator.
  21944. */
  21945. Light.prototype.getShadowGenerator = function () {
  21946. return this._shadowGenerator;
  21947. };
  21948. /**
  21949. * Returns a Vector3, the absolute light position in the World.
  21950. * @returns the world space position of the light
  21951. */
  21952. Light.prototype.getAbsolutePosition = function () {
  21953. return BABYLON.Vector3.Zero();
  21954. };
  21955. /**
  21956. * Specifies if the light will affect the passed mesh.
  21957. * @param mesh The mesh to test against the light
  21958. * @return true the mesh is affected otherwise, false.
  21959. */
  21960. Light.prototype.canAffectMesh = function (mesh) {
  21961. if (!mesh) {
  21962. return true;
  21963. }
  21964. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21965. return false;
  21966. }
  21967. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21968. return false;
  21969. }
  21970. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21971. return false;
  21972. }
  21973. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21974. return false;
  21975. }
  21976. return true;
  21977. };
  21978. /**
  21979. * Computes and Returns the light World matrix.
  21980. * @returns the world matrix
  21981. */
  21982. Light.prototype.getWorldMatrix = function () {
  21983. this._currentRenderId = this.getScene().getRenderId();
  21984. this._childRenderId = this._currentRenderId;
  21985. var worldMatrix = this._getWorldMatrix();
  21986. if (this.parent && this.parent.getWorldMatrix) {
  21987. if (!this._parentedWorldMatrix) {
  21988. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21989. }
  21990. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21991. this._markSyncedWithParent();
  21992. return this._parentedWorldMatrix;
  21993. }
  21994. return worldMatrix;
  21995. };
  21996. /**
  21997. * Sort function to order lights for rendering.
  21998. * @param a First Light object to compare to second.
  21999. * @param b Second Light object to compare first.
  22000. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22001. */
  22002. Light.CompareLightsPriority = function (a, b) {
  22003. //shadow-casting lights have priority over non-shadow-casting lights
  22004. //the renderPrioirty is a secondary sort criterion
  22005. if (a.shadowEnabled !== b.shadowEnabled) {
  22006. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22007. }
  22008. return b.renderPriority - a.renderPriority;
  22009. };
  22010. /**
  22011. * Releases resources associated with this node.
  22012. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22013. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22014. */
  22015. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22016. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22017. if (this._shadowGenerator) {
  22018. this._shadowGenerator.dispose();
  22019. this._shadowGenerator = null;
  22020. }
  22021. // Animations
  22022. this.getScene().stopAnimation(this);
  22023. // Remove from meshes
  22024. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22025. var mesh = _a[_i];
  22026. mesh._removeLightSource(this);
  22027. }
  22028. this._uniformBuffer.dispose();
  22029. // Remove from scene
  22030. this.getScene().removeLight(this);
  22031. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22032. };
  22033. /**
  22034. * Returns the light type ID (integer).
  22035. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22036. */
  22037. Light.prototype.getTypeID = function () {
  22038. return 0;
  22039. };
  22040. /**
  22041. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22042. * @returns the scaled intensity in intensity mode unit
  22043. */
  22044. Light.prototype.getScaledIntensity = function () {
  22045. return this._photometricScale * this.intensity;
  22046. };
  22047. /**
  22048. * Returns a new Light object, named "name", from the current one.
  22049. * @param name The name of the cloned light
  22050. * @returns the new created light
  22051. */
  22052. Light.prototype.clone = function (name) {
  22053. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22054. if (!constructor) {
  22055. return null;
  22056. }
  22057. return BABYLON.SerializationHelper.Clone(constructor, this);
  22058. };
  22059. /**
  22060. * Serializes the current light into a Serialization object.
  22061. * @returns the serialized object.
  22062. */
  22063. Light.prototype.serialize = function () {
  22064. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22065. // Type
  22066. serializationObject.type = this.getTypeID();
  22067. // Parent
  22068. if (this.parent) {
  22069. serializationObject.parentId = this.parent.id;
  22070. }
  22071. // Inclusion / exclusions
  22072. if (this.excludedMeshes.length > 0) {
  22073. serializationObject.excludedMeshesIds = [];
  22074. this.excludedMeshes.forEach(function (mesh) {
  22075. serializationObject.excludedMeshesIds.push(mesh.id);
  22076. });
  22077. }
  22078. if (this.includedOnlyMeshes.length > 0) {
  22079. serializationObject.includedOnlyMeshesIds = [];
  22080. this.includedOnlyMeshes.forEach(function (mesh) {
  22081. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22082. });
  22083. }
  22084. // Animations
  22085. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22086. serializationObject.ranges = this.serializeAnimationRanges();
  22087. return serializationObject;
  22088. };
  22089. /**
  22090. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22091. * This new light is named "name" and added to the passed scene.
  22092. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22093. * @param name The friendly name of the light
  22094. * @param scene The scene the new light will belong to
  22095. * @returns the constructor function
  22096. */
  22097. Light.GetConstructorFromName = function (type, name, scene) {
  22098. switch (type) {
  22099. case 0:
  22100. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22101. case 1:
  22102. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22103. case 2:
  22104. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22105. case 3:
  22106. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22107. }
  22108. return null;
  22109. };
  22110. /**
  22111. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22112. * @param parsedLight The JSON representation of the light
  22113. * @param scene The scene to create the parsed light in
  22114. * @returns the created light after parsing
  22115. */
  22116. Light.Parse = function (parsedLight, scene) {
  22117. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22118. if (!constructor) {
  22119. return null;
  22120. }
  22121. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22122. // Inclusion / exclusions
  22123. if (parsedLight.excludedMeshesIds) {
  22124. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22125. }
  22126. if (parsedLight.includedOnlyMeshesIds) {
  22127. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22128. }
  22129. // Parent
  22130. if (parsedLight.parentId) {
  22131. light._waitingParentId = parsedLight.parentId;
  22132. }
  22133. // Animations
  22134. if (parsedLight.animations) {
  22135. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22136. var parsedAnimation = parsedLight.animations[animationIndex];
  22137. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22138. }
  22139. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22140. }
  22141. if (parsedLight.autoAnimate) {
  22142. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22143. }
  22144. return light;
  22145. };
  22146. Light.prototype._hookArrayForExcluded = function (array) {
  22147. var _this = this;
  22148. var oldPush = array.push;
  22149. array.push = function () {
  22150. var items = [];
  22151. for (var _i = 0; _i < arguments.length; _i++) {
  22152. items[_i] = arguments[_i];
  22153. }
  22154. var result = oldPush.apply(array, items);
  22155. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22156. var item = items_1[_a];
  22157. item._resyncLighSource(_this);
  22158. }
  22159. return result;
  22160. };
  22161. var oldSplice = array.splice;
  22162. array.splice = function (index, deleteCount) {
  22163. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22164. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22165. var item = deleted_1[_i];
  22166. item._resyncLighSource(_this);
  22167. }
  22168. return deleted;
  22169. };
  22170. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22171. var item = array_1[_i];
  22172. item._resyncLighSource(this);
  22173. }
  22174. };
  22175. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22176. var _this = this;
  22177. var oldPush = array.push;
  22178. array.push = function () {
  22179. var items = [];
  22180. for (var _i = 0; _i < arguments.length; _i++) {
  22181. items[_i] = arguments[_i];
  22182. }
  22183. var result = oldPush.apply(array, items);
  22184. _this._resyncMeshes();
  22185. return result;
  22186. };
  22187. var oldSplice = array.splice;
  22188. array.splice = function (index, deleteCount) {
  22189. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22190. _this._resyncMeshes();
  22191. return deleted;
  22192. };
  22193. this._resyncMeshes();
  22194. };
  22195. Light.prototype._resyncMeshes = function () {
  22196. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22197. var mesh = _a[_i];
  22198. mesh._resyncLighSource(this);
  22199. }
  22200. };
  22201. /**
  22202. * Forces the meshes to update their light related information in their rendering used effects
  22203. * @hidden Internal Use Only
  22204. */
  22205. Light.prototype._markMeshesAsLightDirty = function () {
  22206. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22207. var mesh = _a[_i];
  22208. if (mesh._lightSources.indexOf(this) !== -1) {
  22209. mesh._markSubMeshesAsLightDirty();
  22210. }
  22211. }
  22212. };
  22213. /**
  22214. * Recomputes the cached photometric scale if needed.
  22215. */
  22216. Light.prototype._computePhotometricScale = function () {
  22217. this._photometricScale = this._getPhotometricScale();
  22218. this.getScene().resetCachedMaterial();
  22219. };
  22220. /**
  22221. * Returns the Photometric Scale according to the light type and intensity mode.
  22222. */
  22223. Light.prototype._getPhotometricScale = function () {
  22224. var photometricScale = 0.0;
  22225. var lightTypeID = this.getTypeID();
  22226. //get photometric mode
  22227. var photometricMode = this.intensityMode;
  22228. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22229. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22230. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22231. }
  22232. else {
  22233. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22234. }
  22235. }
  22236. //compute photometric scale
  22237. switch (lightTypeID) {
  22238. case Light.LIGHTTYPEID_POINTLIGHT:
  22239. case Light.LIGHTTYPEID_SPOTLIGHT:
  22240. switch (photometricMode) {
  22241. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22242. photometricScale = 1.0 / (4.0 * Math.PI);
  22243. break;
  22244. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22245. photometricScale = 1.0;
  22246. break;
  22247. case Light.INTENSITYMODE_LUMINANCE:
  22248. photometricScale = this.radius * this.radius;
  22249. break;
  22250. }
  22251. break;
  22252. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22253. switch (photometricMode) {
  22254. case Light.INTENSITYMODE_ILLUMINANCE:
  22255. photometricScale = 1.0;
  22256. break;
  22257. case Light.INTENSITYMODE_LUMINANCE:
  22258. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22259. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22260. var apexAngleRadians = this.radius;
  22261. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22262. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22263. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22264. photometricScale = solidAngle;
  22265. break;
  22266. }
  22267. break;
  22268. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22269. // No fall off in hemisperic light.
  22270. photometricScale = 1.0;
  22271. break;
  22272. }
  22273. return photometricScale;
  22274. };
  22275. /**
  22276. * Reorder the light in the scene according to their defined priority.
  22277. * @hidden Internal Use Only
  22278. */
  22279. Light.prototype._reorderLightsInScene = function () {
  22280. var scene = this.getScene();
  22281. if (this._renderPriority != 0) {
  22282. scene.requireLightSorting = true;
  22283. }
  22284. this.getScene().sortLightsByPriority();
  22285. };
  22286. //lightmapMode Consts
  22287. Light._LIGHTMAP_DEFAULT = 0;
  22288. Light._LIGHTMAP_SPECULAR = 1;
  22289. Light._LIGHTMAP_SHADOWSONLY = 2;
  22290. // Intensity Mode Consts
  22291. Light._INTENSITYMODE_AUTOMATIC = 0;
  22292. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22293. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22294. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22295. Light._INTENSITYMODE_LUMINANCE = 4;
  22296. // Light types ids const.
  22297. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22298. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22299. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22300. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22301. __decorate([
  22302. BABYLON.serializeAsColor3()
  22303. ], Light.prototype, "diffuse", void 0);
  22304. __decorate([
  22305. BABYLON.serializeAsColor3()
  22306. ], Light.prototype, "specular", void 0);
  22307. __decorate([
  22308. BABYLON.serialize()
  22309. ], Light.prototype, "intensity", void 0);
  22310. __decorate([
  22311. BABYLON.serialize()
  22312. ], Light.prototype, "range", void 0);
  22313. __decorate([
  22314. BABYLON.serialize()
  22315. ], Light.prototype, "intensityMode", null);
  22316. __decorate([
  22317. BABYLON.serialize()
  22318. ], Light.prototype, "radius", null);
  22319. __decorate([
  22320. BABYLON.serialize()
  22321. ], Light.prototype, "_renderPriority", void 0);
  22322. __decorate([
  22323. BABYLON.expandToProperty("_reorderLightsInScene")
  22324. ], Light.prototype, "renderPriority", void 0);
  22325. __decorate([
  22326. BABYLON.serialize("shadowEnabled")
  22327. ], Light.prototype, "_shadowEnabled", void 0);
  22328. __decorate([
  22329. BABYLON.serialize("excludeWithLayerMask")
  22330. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22331. __decorate([
  22332. BABYLON.serialize("includeOnlyWithLayerMask")
  22333. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22334. __decorate([
  22335. BABYLON.serialize("lightmapMode")
  22336. ], Light.prototype, "_lightmapMode", void 0);
  22337. return Light;
  22338. }(BABYLON.Node));
  22339. BABYLON.Light = Light;
  22340. })(BABYLON || (BABYLON = {}));
  22341. //# sourceMappingURL=babylon.light.js.map
  22342. var BABYLON;
  22343. (function (BABYLON) {
  22344. var Camera = /** @class */ (function (_super) {
  22345. __extends(Camera, _super);
  22346. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22347. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22348. var _this = _super.call(this, name, scene) || this;
  22349. /**
  22350. * The vector the camera should consider as up.
  22351. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22352. */
  22353. _this.upVector = BABYLON.Vector3.Up();
  22354. _this.orthoLeft = null;
  22355. _this.orthoRight = null;
  22356. _this.orthoBottom = null;
  22357. _this.orthoTop = null;
  22358. /**
  22359. * FOV is set in Radians. (default is 0.8)
  22360. */
  22361. _this.fov = 0.8;
  22362. _this.minZ = 1;
  22363. _this.maxZ = 10000.0;
  22364. _this.inertia = 0.9;
  22365. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22366. _this.isIntermediate = false;
  22367. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22368. /**
  22369. * Restricts the camera to viewing objects with the same layerMask.
  22370. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22371. */
  22372. _this.layerMask = 0x0FFFFFFF;
  22373. /**
  22374. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22375. */
  22376. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22377. // Camera rig members
  22378. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22379. _this._rigCameras = new Array();
  22380. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22381. _this._skipRendering = false;
  22382. _this.customRenderTargets = new Array();
  22383. // Observables
  22384. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22385. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22386. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22387. _this.onRestoreStateObservable = new BABYLON.Observable();
  22388. // Cache
  22389. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22390. _this._projectionMatrix = new BABYLON.Matrix();
  22391. _this._doNotComputeProjectionMatrix = false;
  22392. _this._worldMatrix = BABYLON.Matrix.Identity();
  22393. _this._postProcesses = new Array();
  22394. _this._transformMatrix = BABYLON.Matrix.Zero();
  22395. _this._activeMeshes = new BABYLON.SmartArray(256);
  22396. _this._globalPosition = BABYLON.Vector3.Zero();
  22397. _this._refreshFrustumPlanes = true;
  22398. _this.getScene().addCamera(_this);
  22399. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22400. _this.getScene().activeCamera = _this;
  22401. }
  22402. _this.position = position;
  22403. return _this;
  22404. }
  22405. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22406. get: function () {
  22407. return Camera._PERSPECTIVE_CAMERA;
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22413. get: function () {
  22414. return Camera._ORTHOGRAPHIC_CAMERA;
  22415. },
  22416. enumerable: true,
  22417. configurable: true
  22418. });
  22419. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22420. /**
  22421. * This is the default FOV mode for perspective cameras.
  22422. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22423. *
  22424. */
  22425. get: function () {
  22426. return Camera._FOVMODE_VERTICAL_FIXED;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22432. /**
  22433. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22434. *
  22435. */
  22436. get: function () {
  22437. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22443. get: function () {
  22444. return Camera._RIG_MODE_NONE;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22450. get: function () {
  22451. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22457. get: function () {
  22458. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22464. get: function () {
  22465. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22466. },
  22467. enumerable: true,
  22468. configurable: true
  22469. });
  22470. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22471. get: function () {
  22472. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22473. },
  22474. enumerable: true,
  22475. configurable: true
  22476. });
  22477. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22478. get: function () {
  22479. return Camera._RIG_MODE_VR;
  22480. },
  22481. enumerable: true,
  22482. configurable: true
  22483. });
  22484. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22485. get: function () {
  22486. return Camera._RIG_MODE_WEBVR;
  22487. },
  22488. enumerable: true,
  22489. configurable: true
  22490. });
  22491. /**
  22492. * Store current camera state (fov, position, etc..)
  22493. */
  22494. Camera.prototype.storeState = function () {
  22495. this._stateStored = true;
  22496. this._storedFov = this.fov;
  22497. return this;
  22498. };
  22499. /**
  22500. * Restores the camera state values if it has been stored. You must call storeState() first
  22501. */
  22502. Camera.prototype._restoreStateValues = function () {
  22503. if (!this._stateStored) {
  22504. return false;
  22505. }
  22506. this.fov = this._storedFov;
  22507. return true;
  22508. };
  22509. /**
  22510. * Restored camera state. You must call storeState() first
  22511. */
  22512. Camera.prototype.restoreState = function () {
  22513. if (this._restoreStateValues()) {
  22514. this.onRestoreStateObservable.notifyObservers(this);
  22515. return true;
  22516. }
  22517. return false;
  22518. };
  22519. Camera.prototype.getClassName = function () {
  22520. return "Camera";
  22521. };
  22522. /**
  22523. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22524. */
  22525. Camera.prototype.toString = function (fullDetails) {
  22526. var ret = "Name: " + this.name;
  22527. ret += ", type: " + this.getClassName();
  22528. if (this.animations) {
  22529. for (var i = 0; i < this.animations.length; i++) {
  22530. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22531. }
  22532. }
  22533. if (fullDetails) {
  22534. }
  22535. return ret;
  22536. };
  22537. Object.defineProperty(Camera.prototype, "globalPosition", {
  22538. get: function () {
  22539. return this._globalPosition;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Camera.prototype.getActiveMeshes = function () {
  22545. return this._activeMeshes;
  22546. };
  22547. Camera.prototype.isActiveMesh = function (mesh) {
  22548. return (this._activeMeshes.indexOf(mesh) !== -1);
  22549. };
  22550. /**
  22551. * Is this camera ready to be used/rendered
  22552. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22553. * @return true if the camera is ready
  22554. */
  22555. Camera.prototype.isReady = function (completeCheck) {
  22556. if (completeCheck === void 0) { completeCheck = false; }
  22557. if (completeCheck) {
  22558. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22559. var pp = _a[_i];
  22560. if (pp && !pp.isReady()) {
  22561. return false;
  22562. }
  22563. }
  22564. }
  22565. return _super.prototype.isReady.call(this, completeCheck);
  22566. };
  22567. //Cache
  22568. Camera.prototype._initCache = function () {
  22569. _super.prototype._initCache.call(this);
  22570. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22571. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22572. this._cache.mode = undefined;
  22573. this._cache.minZ = undefined;
  22574. this._cache.maxZ = undefined;
  22575. this._cache.fov = undefined;
  22576. this._cache.fovMode = undefined;
  22577. this._cache.aspectRatio = undefined;
  22578. this._cache.orthoLeft = undefined;
  22579. this._cache.orthoRight = undefined;
  22580. this._cache.orthoBottom = undefined;
  22581. this._cache.orthoTop = undefined;
  22582. this._cache.renderWidth = undefined;
  22583. this._cache.renderHeight = undefined;
  22584. };
  22585. Camera.prototype._updateCache = function (ignoreParentClass) {
  22586. if (!ignoreParentClass) {
  22587. _super.prototype._updateCache.call(this);
  22588. }
  22589. this._cache.position.copyFrom(this.position);
  22590. this._cache.upVector.copyFrom(this.upVector);
  22591. };
  22592. // Synchronized
  22593. Camera.prototype._isSynchronized = function () {
  22594. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22595. };
  22596. Camera.prototype._isSynchronizedViewMatrix = function () {
  22597. if (!_super.prototype._isSynchronized.call(this))
  22598. return false;
  22599. return this._cache.position.equals(this.position)
  22600. && this._cache.upVector.equals(this.upVector)
  22601. && this.isSynchronizedWithParent();
  22602. };
  22603. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22604. var check = this._cache.mode === this.mode
  22605. && this._cache.minZ === this.minZ
  22606. && this._cache.maxZ === this.maxZ;
  22607. if (!check) {
  22608. return false;
  22609. }
  22610. var engine = this.getEngine();
  22611. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22612. check = this._cache.fov === this.fov
  22613. && this._cache.fovMode === this.fovMode
  22614. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22615. }
  22616. else {
  22617. check = this._cache.orthoLeft === this.orthoLeft
  22618. && this._cache.orthoRight === this.orthoRight
  22619. && this._cache.orthoBottom === this.orthoBottom
  22620. && this._cache.orthoTop === this.orthoTop
  22621. && this._cache.renderWidth === engine.getRenderWidth()
  22622. && this._cache.renderHeight === engine.getRenderHeight();
  22623. }
  22624. return check;
  22625. };
  22626. // Controls
  22627. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22628. };
  22629. Camera.prototype.detachControl = function (element) {
  22630. };
  22631. Camera.prototype.update = function () {
  22632. this._checkInputs();
  22633. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22634. this._updateRigCameras();
  22635. }
  22636. };
  22637. Camera.prototype._checkInputs = function () {
  22638. this.onAfterCheckInputsObservable.notifyObservers(this);
  22639. };
  22640. Object.defineProperty(Camera.prototype, "rigCameras", {
  22641. get: function () {
  22642. return this._rigCameras;
  22643. },
  22644. enumerable: true,
  22645. configurable: true
  22646. });
  22647. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22648. get: function () {
  22649. return this._rigPostProcess;
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. /**
  22655. * Internal, gets the first post proces.
  22656. * @returns the first post process to be run on this camera.
  22657. */
  22658. Camera.prototype._getFirstPostProcess = function () {
  22659. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22660. if (this._postProcesses[ppIndex] !== null) {
  22661. return this._postProcesses[ppIndex];
  22662. }
  22663. }
  22664. return null;
  22665. };
  22666. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22667. // invalidate framebuffer
  22668. var firstPostProcess = this._getFirstPostProcess();
  22669. if (firstPostProcess) {
  22670. firstPostProcess.markTextureDirty();
  22671. }
  22672. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22673. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22674. var cam = this._rigCameras[i];
  22675. var rigPostProcess = cam._rigPostProcess;
  22676. // for VR rig, there does not have to be a post process
  22677. if (rigPostProcess) {
  22678. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22679. if (isPass) {
  22680. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22681. cam.isIntermediate = this._postProcesses.length === 0;
  22682. }
  22683. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22684. rigPostProcess.markTextureDirty();
  22685. }
  22686. else {
  22687. cam._postProcesses = this._postProcesses.slice(0);
  22688. }
  22689. }
  22690. };
  22691. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22692. if (insertAt === void 0) { insertAt = null; }
  22693. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22694. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22695. return 0;
  22696. }
  22697. if (insertAt == null || insertAt < 0) {
  22698. this._postProcesses.push(postProcess);
  22699. }
  22700. else if (this._postProcesses[insertAt] === null) {
  22701. this._postProcesses[insertAt] = postProcess;
  22702. }
  22703. else {
  22704. this._postProcesses.splice(insertAt, 0, postProcess);
  22705. }
  22706. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22707. return this._postProcesses.indexOf(postProcess);
  22708. };
  22709. Camera.prototype.detachPostProcess = function (postProcess) {
  22710. var idx = this._postProcesses.indexOf(postProcess);
  22711. if (idx !== -1) {
  22712. this._postProcesses[idx] = null;
  22713. }
  22714. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22715. };
  22716. Camera.prototype.getWorldMatrix = function () {
  22717. if (this._isSynchronizedViewMatrix()) {
  22718. return this._worldMatrix;
  22719. }
  22720. // Getting the the view matrix will also compute the world matrix.
  22721. this.getViewMatrix();
  22722. return this._worldMatrix;
  22723. };
  22724. Camera.prototype._getViewMatrix = function () {
  22725. return BABYLON.Matrix.Identity();
  22726. };
  22727. Camera.prototype.getViewMatrix = function (force) {
  22728. if (!force && this._isSynchronizedViewMatrix()) {
  22729. return this._computedViewMatrix;
  22730. }
  22731. this.updateCache();
  22732. this._computedViewMatrix = this._getViewMatrix();
  22733. this._currentRenderId = this.getScene().getRenderId();
  22734. this._childRenderId = this._currentRenderId;
  22735. this._refreshFrustumPlanes = true;
  22736. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22737. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22738. }
  22739. this.onViewMatrixChangedObservable.notifyObservers(this);
  22740. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22741. return this._computedViewMatrix;
  22742. };
  22743. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22744. this._doNotComputeProjectionMatrix = true;
  22745. if (projection !== undefined) {
  22746. this._projectionMatrix = projection;
  22747. }
  22748. };
  22749. ;
  22750. Camera.prototype.unfreezeProjectionMatrix = function () {
  22751. this._doNotComputeProjectionMatrix = false;
  22752. };
  22753. ;
  22754. Camera.prototype.getProjectionMatrix = function (force) {
  22755. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22756. return this._projectionMatrix;
  22757. }
  22758. // Cache
  22759. this._cache.mode = this.mode;
  22760. this._cache.minZ = this.minZ;
  22761. this._cache.maxZ = this.maxZ;
  22762. // Matrix
  22763. this._refreshFrustumPlanes = true;
  22764. var engine = this.getEngine();
  22765. var scene = this.getScene();
  22766. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22767. this._cache.fov = this.fov;
  22768. this._cache.fovMode = this.fovMode;
  22769. this._cache.aspectRatio = engine.getAspectRatio(this);
  22770. if (this.minZ <= 0) {
  22771. this.minZ = 0.1;
  22772. }
  22773. if (scene.useRightHandedSystem) {
  22774. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22775. }
  22776. else {
  22777. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22778. }
  22779. }
  22780. else {
  22781. var halfWidth = engine.getRenderWidth() / 2.0;
  22782. var halfHeight = engine.getRenderHeight() / 2.0;
  22783. if (scene.useRightHandedSystem) {
  22784. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22785. }
  22786. else {
  22787. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22788. }
  22789. this._cache.orthoLeft = this.orthoLeft;
  22790. this._cache.orthoRight = this.orthoRight;
  22791. this._cache.orthoBottom = this.orthoBottom;
  22792. this._cache.orthoTop = this.orthoTop;
  22793. this._cache.renderWidth = engine.getRenderWidth();
  22794. this._cache.renderHeight = engine.getRenderHeight();
  22795. }
  22796. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22797. return this._projectionMatrix;
  22798. };
  22799. Camera.prototype.getTranformationMatrix = function () {
  22800. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22801. return this._transformMatrix;
  22802. };
  22803. Camera.prototype.updateFrustumPlanes = function () {
  22804. if (!this._refreshFrustumPlanes) {
  22805. return;
  22806. }
  22807. this.getTranformationMatrix();
  22808. if (!this._frustumPlanes) {
  22809. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22810. }
  22811. else {
  22812. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22813. }
  22814. this._refreshFrustumPlanes = false;
  22815. };
  22816. Camera.prototype.isInFrustum = function (target) {
  22817. this.updateFrustumPlanes();
  22818. return target.isInFrustum(this._frustumPlanes);
  22819. };
  22820. Camera.prototype.isCompletelyInFrustum = function (target) {
  22821. this.updateFrustumPlanes();
  22822. return target.isCompletelyInFrustum(this._frustumPlanes);
  22823. };
  22824. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22825. if (length === void 0) { length = 100; }
  22826. if (!transform) {
  22827. transform = this.getWorldMatrix();
  22828. }
  22829. if (!origin) {
  22830. origin = this.position;
  22831. }
  22832. var forward = new BABYLON.Vector3(0, 0, 1);
  22833. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22834. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22835. return new BABYLON.Ray(origin, direction, length);
  22836. };
  22837. /**
  22838. * Releases resources associated with this node.
  22839. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22840. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22841. */
  22842. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22843. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22844. // Observables
  22845. this.onViewMatrixChangedObservable.clear();
  22846. this.onProjectionMatrixChangedObservable.clear();
  22847. this.onAfterCheckInputsObservable.clear();
  22848. this.onRestoreStateObservable.clear();
  22849. // Inputs
  22850. if (this.inputs) {
  22851. this.inputs.clear();
  22852. }
  22853. // Animations
  22854. this.getScene().stopAnimation(this);
  22855. // Remove from scene
  22856. this.getScene().removeCamera(this);
  22857. while (this._rigCameras.length > 0) {
  22858. var camera = this._rigCameras.pop();
  22859. if (camera) {
  22860. camera.dispose();
  22861. }
  22862. }
  22863. // Postprocesses
  22864. if (this._rigPostProcess) {
  22865. this._rigPostProcess.dispose(this);
  22866. this._rigPostProcess = null;
  22867. this._postProcesses = [];
  22868. }
  22869. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22870. this._rigPostProcess = null;
  22871. this._postProcesses = [];
  22872. }
  22873. else {
  22874. var i = this._postProcesses.length;
  22875. while (--i >= 0) {
  22876. var postProcess = this._postProcesses[i];
  22877. if (postProcess) {
  22878. postProcess.dispose(this);
  22879. }
  22880. }
  22881. }
  22882. // Render targets
  22883. var i = this.customRenderTargets.length;
  22884. while (--i >= 0) {
  22885. this.customRenderTargets[i].dispose();
  22886. }
  22887. this.customRenderTargets = [];
  22888. // Active Meshes
  22889. this._activeMeshes.dispose();
  22890. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22891. };
  22892. Object.defineProperty(Camera.prototype, "leftCamera", {
  22893. // ---- Camera rigs section ----
  22894. get: function () {
  22895. if (this._rigCameras.length < 1) {
  22896. return null;
  22897. }
  22898. return this._rigCameras[0];
  22899. },
  22900. enumerable: true,
  22901. configurable: true
  22902. });
  22903. Object.defineProperty(Camera.prototype, "rightCamera", {
  22904. get: function () {
  22905. if (this._rigCameras.length < 2) {
  22906. return null;
  22907. }
  22908. return this._rigCameras[1];
  22909. },
  22910. enumerable: true,
  22911. configurable: true
  22912. });
  22913. Camera.prototype.getLeftTarget = function () {
  22914. if (this._rigCameras.length < 1) {
  22915. return null;
  22916. }
  22917. return this._rigCameras[0].getTarget();
  22918. };
  22919. Camera.prototype.getRightTarget = function () {
  22920. if (this._rigCameras.length < 2) {
  22921. return null;
  22922. }
  22923. return this._rigCameras[1].getTarget();
  22924. };
  22925. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22926. if (this.cameraRigMode === mode) {
  22927. return;
  22928. }
  22929. while (this._rigCameras.length > 0) {
  22930. var camera = this._rigCameras.pop();
  22931. if (camera) {
  22932. camera.dispose();
  22933. }
  22934. }
  22935. this.cameraRigMode = mode;
  22936. this._cameraRigParams = {};
  22937. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22938. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22939. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22940. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22941. // create the rig cameras, unless none
  22942. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22943. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22944. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22945. if (leftCamera && rightCamera) {
  22946. this._rigCameras.push(leftCamera);
  22947. this._rigCameras.push(rightCamera);
  22948. }
  22949. }
  22950. switch (this.cameraRigMode) {
  22951. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22952. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22953. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22954. break;
  22955. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22956. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22957. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22958. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22959. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22960. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22961. break;
  22962. case Camera.RIG_MODE_VR:
  22963. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22964. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22965. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22966. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22967. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22968. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22969. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22970. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22971. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22972. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22973. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22974. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22975. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22976. if (metrics.compensateDistortion) {
  22977. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22978. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22979. }
  22980. break;
  22981. case Camera.RIG_MODE_WEBVR:
  22982. if (rigParams.vrDisplay) {
  22983. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22984. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22985. //Left eye
  22986. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22987. this._rigCameras[0].setCameraRigParameter("left", true);
  22988. //leaving this for future reference
  22989. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22990. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22991. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22992. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22993. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22994. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22995. this._rigCameras[0].parent = this;
  22996. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22997. //Right eye
  22998. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22999. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23000. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23001. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23002. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23003. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23004. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23005. this._rigCameras[1].parent = this;
  23006. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23007. if (Camera.UseAlternateWebVRRendering) {
  23008. this._rigCameras[1]._skipRendering = true;
  23009. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23010. }
  23011. }
  23012. break;
  23013. }
  23014. this._cascadePostProcessesToRigCams();
  23015. this.update();
  23016. };
  23017. Camera.prototype._getVRProjectionMatrix = function () {
  23018. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23019. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23020. return this._projectionMatrix;
  23021. };
  23022. Camera.prototype._updateCameraRotationMatrix = function () {
  23023. //Here for WebVR
  23024. };
  23025. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23026. //Here for WebVR
  23027. };
  23028. /**
  23029. * This function MUST be overwritten by the different WebVR cameras available.
  23030. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23031. */
  23032. Camera.prototype._getWebVRProjectionMatrix = function () {
  23033. return BABYLON.Matrix.Identity();
  23034. };
  23035. /**
  23036. * This function MUST be overwritten by the different WebVR cameras available.
  23037. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23038. */
  23039. Camera.prototype._getWebVRViewMatrix = function () {
  23040. return BABYLON.Matrix.Identity();
  23041. };
  23042. Camera.prototype.setCameraRigParameter = function (name, value) {
  23043. if (!this._cameraRigParams) {
  23044. this._cameraRigParams = {};
  23045. }
  23046. this._cameraRigParams[name] = value;
  23047. //provisionnally:
  23048. if (name === "interaxialDistance") {
  23049. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23050. }
  23051. };
  23052. /**
  23053. * needs to be overridden by children so sub has required properties to be copied
  23054. */
  23055. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23056. return null;
  23057. };
  23058. /**
  23059. * May need to be overridden by children
  23060. */
  23061. Camera.prototype._updateRigCameras = function () {
  23062. for (var i = 0; i < this._rigCameras.length; i++) {
  23063. this._rigCameras[i].minZ = this.minZ;
  23064. this._rigCameras[i].maxZ = this.maxZ;
  23065. this._rigCameras[i].fov = this.fov;
  23066. }
  23067. // only update viewport when ANAGLYPH
  23068. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23069. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23070. }
  23071. };
  23072. Camera.prototype._setupInputs = function () {
  23073. };
  23074. Camera.prototype.serialize = function () {
  23075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23076. // Type
  23077. serializationObject.type = this.getClassName();
  23078. // Parent
  23079. if (this.parent) {
  23080. serializationObject.parentId = this.parent.id;
  23081. }
  23082. if (this.inputs) {
  23083. this.inputs.serialize(serializationObject);
  23084. }
  23085. // Animations
  23086. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23087. serializationObject.ranges = this.serializeAnimationRanges();
  23088. return serializationObject;
  23089. };
  23090. Camera.prototype.clone = function (name) {
  23091. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23092. };
  23093. Camera.prototype.getDirection = function (localAxis) {
  23094. var result = BABYLON.Vector3.Zero();
  23095. this.getDirectionToRef(localAxis, result);
  23096. return result;
  23097. };
  23098. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23099. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23100. };
  23101. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23102. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23103. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23104. switch (type) {
  23105. case "ArcRotateCamera":
  23106. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23107. case "DeviceOrientationCamera":
  23108. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23109. case "FollowCamera":
  23110. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23111. case "ArcFollowCamera":
  23112. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23113. case "GamepadCamera":
  23114. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23115. case "TouchCamera":
  23116. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23117. case "VirtualJoysticksCamera":
  23118. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23119. case "WebVRFreeCamera":
  23120. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23121. case "WebVRGamepadCamera":
  23122. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23123. case "VRDeviceOrientationFreeCamera":
  23124. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23125. case "VRDeviceOrientationGamepadCamera":
  23126. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23127. case "AnaglyphArcRotateCamera":
  23128. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23129. case "AnaglyphFreeCamera":
  23130. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23131. case "AnaglyphGamepadCamera":
  23132. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23133. case "AnaglyphUniversalCamera":
  23134. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23135. case "StereoscopicArcRotateCamera":
  23136. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23137. case "StereoscopicFreeCamera":
  23138. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23139. case "StereoscopicGamepadCamera":
  23140. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23141. case "StereoscopicUniversalCamera":
  23142. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23143. case "FreeCamera": // Forcing Universal here
  23144. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23145. default: // Universal Camera is the default value
  23146. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23147. }
  23148. };
  23149. Camera.prototype.computeWorldMatrix = function () {
  23150. return this.getWorldMatrix();
  23151. };
  23152. Camera.Parse = function (parsedCamera, scene) {
  23153. var type = parsedCamera.type;
  23154. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23155. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23156. // Parent
  23157. if (parsedCamera.parentId) {
  23158. camera._waitingParentId = parsedCamera.parentId;
  23159. }
  23160. //If camera has an input manager, let it parse inputs settings
  23161. if (camera.inputs) {
  23162. camera.inputs.parse(parsedCamera);
  23163. camera._setupInputs();
  23164. }
  23165. if (camera.setPosition) { // need to force position
  23166. camera.position.copyFromFloats(0, 0, 0);
  23167. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23168. }
  23169. // Target
  23170. if (parsedCamera.target) {
  23171. if (camera.setTarget) {
  23172. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23173. }
  23174. }
  23175. // Apply 3d rig, when found
  23176. if (parsedCamera.cameraRigMode) {
  23177. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23178. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23179. }
  23180. // Animations
  23181. if (parsedCamera.animations) {
  23182. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23183. var parsedAnimation = parsedCamera.animations[animationIndex];
  23184. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23185. }
  23186. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23187. }
  23188. if (parsedCamera.autoAnimate) {
  23189. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23190. }
  23191. return camera;
  23192. };
  23193. // Statics
  23194. Camera._PERSPECTIVE_CAMERA = 0;
  23195. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23196. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23197. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23198. Camera._RIG_MODE_NONE = 0;
  23199. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23200. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23201. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23202. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23203. Camera._RIG_MODE_VR = 20;
  23204. Camera._RIG_MODE_WEBVR = 21;
  23205. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23206. Camera.UseAlternateWebVRRendering = false;
  23207. __decorate([
  23208. BABYLON.serializeAsVector3()
  23209. ], Camera.prototype, "position", void 0);
  23210. __decorate([
  23211. BABYLON.serializeAsVector3()
  23212. ], Camera.prototype, "upVector", void 0);
  23213. __decorate([
  23214. BABYLON.serialize()
  23215. ], Camera.prototype, "orthoLeft", void 0);
  23216. __decorate([
  23217. BABYLON.serialize()
  23218. ], Camera.prototype, "orthoRight", void 0);
  23219. __decorate([
  23220. BABYLON.serialize()
  23221. ], Camera.prototype, "orthoBottom", void 0);
  23222. __decorate([
  23223. BABYLON.serialize()
  23224. ], Camera.prototype, "orthoTop", void 0);
  23225. __decorate([
  23226. BABYLON.serialize()
  23227. ], Camera.prototype, "fov", void 0);
  23228. __decorate([
  23229. BABYLON.serialize()
  23230. ], Camera.prototype, "minZ", void 0);
  23231. __decorate([
  23232. BABYLON.serialize()
  23233. ], Camera.prototype, "maxZ", void 0);
  23234. __decorate([
  23235. BABYLON.serialize()
  23236. ], Camera.prototype, "inertia", void 0);
  23237. __decorate([
  23238. BABYLON.serialize()
  23239. ], Camera.prototype, "mode", void 0);
  23240. __decorate([
  23241. BABYLON.serialize()
  23242. ], Camera.prototype, "layerMask", void 0);
  23243. __decorate([
  23244. BABYLON.serialize()
  23245. ], Camera.prototype, "fovMode", void 0);
  23246. __decorate([
  23247. BABYLON.serialize()
  23248. ], Camera.prototype, "cameraRigMode", void 0);
  23249. __decorate([
  23250. BABYLON.serialize()
  23251. ], Camera.prototype, "interaxialDistance", void 0);
  23252. __decorate([
  23253. BABYLON.serialize()
  23254. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23255. return Camera;
  23256. }(BABYLON.Node));
  23257. BABYLON.Camera = Camera;
  23258. })(BABYLON || (BABYLON = {}));
  23259. //# sourceMappingURL=babylon.camera.js.map
  23260. var BABYLON;
  23261. (function (BABYLON) {
  23262. var RenderingManager = /** @class */ (function () {
  23263. function RenderingManager(scene) {
  23264. this._renderingGroups = new Array();
  23265. this._autoClearDepthStencil = {};
  23266. this._customOpaqueSortCompareFn = {};
  23267. this._customAlphaTestSortCompareFn = {};
  23268. this._customTransparentSortCompareFn = {};
  23269. this._renderinGroupInfo = null;
  23270. this._scene = scene;
  23271. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23272. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23273. }
  23274. }
  23275. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23276. if (depth === void 0) { depth = true; }
  23277. if (stencil === void 0) { stencil = true; }
  23278. if (this._depthStencilBufferAlreadyCleaned) {
  23279. return;
  23280. }
  23281. this._scene.getEngine().clear(null, false, depth, stencil);
  23282. this._depthStencilBufferAlreadyCleaned = true;
  23283. };
  23284. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23285. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23286. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23287. var info = null;
  23288. if (observable) {
  23289. if (!this._renderinGroupInfo) {
  23290. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23291. }
  23292. info = this._renderinGroupInfo;
  23293. info.scene = this._scene;
  23294. info.camera = this._scene.activeCamera;
  23295. }
  23296. // Dispatch sprites
  23297. if (renderSprites) {
  23298. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23299. var manager = this._scene.spriteManagers[index];
  23300. this.dispatchSprites(manager);
  23301. }
  23302. }
  23303. // Render
  23304. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23305. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23306. var renderingGroup = this._renderingGroups[index];
  23307. if (!renderingGroup && !observable)
  23308. continue;
  23309. var renderingGroupMask = 0;
  23310. // Fire PRECLEAR stage
  23311. if (observable && info) {
  23312. renderingGroupMask = Math.pow(2, index);
  23313. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23314. info.renderingGroupId = index;
  23315. observable.notifyObservers(info, renderingGroupMask);
  23316. }
  23317. // Clear depth/stencil if needed
  23318. if (RenderingManager.AUTOCLEAR) {
  23319. var autoClear = this._autoClearDepthStencil[index];
  23320. if (autoClear && autoClear.autoClear) {
  23321. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23322. }
  23323. }
  23324. if (observable && info) {
  23325. // Fire PREOPAQUE stage
  23326. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23327. observable.notifyObservers(info, renderingGroupMask);
  23328. // Fire PRETRANSPARENT stage
  23329. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23330. observable.notifyObservers(info, renderingGroupMask);
  23331. }
  23332. if (renderingGroup)
  23333. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23334. // Fire POSTTRANSPARENT stage
  23335. if (observable && info) {
  23336. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23337. observable.notifyObservers(info, renderingGroupMask);
  23338. }
  23339. }
  23340. };
  23341. RenderingManager.prototype.reset = function () {
  23342. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23343. var renderingGroup = this._renderingGroups[index];
  23344. if (renderingGroup) {
  23345. renderingGroup.prepare();
  23346. }
  23347. }
  23348. };
  23349. RenderingManager.prototype.dispose = function () {
  23350. this.freeRenderingGroups();
  23351. this._renderingGroups.length = 0;
  23352. };
  23353. /**
  23354. * Clear the info related to rendering groups preventing retention points during dispose.
  23355. */
  23356. RenderingManager.prototype.freeRenderingGroups = function () {
  23357. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23358. var renderingGroup = this._renderingGroups[index];
  23359. if (renderingGroup) {
  23360. renderingGroup.dispose();
  23361. }
  23362. }
  23363. };
  23364. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23365. if (this._renderingGroups[renderingGroupId] === undefined) {
  23366. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23367. }
  23368. };
  23369. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23370. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23371. this._prepareRenderingGroup(renderingGroupId);
  23372. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23373. };
  23374. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23375. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23376. this._prepareRenderingGroup(renderingGroupId);
  23377. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23378. };
  23379. /**
  23380. * @param subMesh The submesh to dispatch
  23381. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23382. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23383. */
  23384. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23385. if (mesh === undefined) {
  23386. mesh = subMesh.getMesh();
  23387. }
  23388. var renderingGroupId = mesh.renderingGroupId || 0;
  23389. this._prepareRenderingGroup(renderingGroupId);
  23390. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23391. };
  23392. /**
  23393. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23394. * This allowed control for front to back rendering or reversly depending of the special needs.
  23395. *
  23396. * @param renderingGroupId The rendering group id corresponding to its index
  23397. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23398. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23399. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23400. */
  23401. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23402. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23403. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23404. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23405. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23406. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23407. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23408. if (this._renderingGroups[renderingGroupId]) {
  23409. var group = this._renderingGroups[renderingGroupId];
  23410. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23411. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23412. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23413. }
  23414. };
  23415. /**
  23416. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23417. *
  23418. * @param renderingGroupId The rendering group id corresponding to its index
  23419. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23420. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23421. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23422. */
  23423. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23424. if (depth === void 0) { depth = true; }
  23425. if (stencil === void 0) { stencil = true; }
  23426. this._autoClearDepthStencil[renderingGroupId] = {
  23427. autoClear: autoClearDepthStencil,
  23428. depth: depth,
  23429. stencil: stencil
  23430. };
  23431. };
  23432. /**
  23433. * The max id used for rendering groups (not included)
  23434. */
  23435. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23436. /**
  23437. * The min id used for rendering groups (included)
  23438. */
  23439. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23440. /**
  23441. * Used to globally prevent autoclearing scenes.
  23442. */
  23443. RenderingManager.AUTOCLEAR = true;
  23444. return RenderingManager;
  23445. }());
  23446. BABYLON.RenderingManager = RenderingManager;
  23447. })(BABYLON || (BABYLON = {}));
  23448. //# sourceMappingURL=babylon.renderingManager.js.map
  23449. var BABYLON;
  23450. (function (BABYLON) {
  23451. var RenderingGroup = /** @class */ (function () {
  23452. /**
  23453. * Creates a new rendering group.
  23454. * @param index The rendering group index
  23455. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23456. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23457. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23458. */
  23459. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23460. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23461. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23462. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23463. this.index = index;
  23464. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23465. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23466. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23467. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23468. this._particleSystems = new BABYLON.SmartArray(256);
  23469. this._spriteManagers = new BABYLON.SmartArray(256);
  23470. this._edgesRenderers = new BABYLON.SmartArray(16);
  23471. this._scene = scene;
  23472. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23473. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23474. this.transparentSortCompareFn = transparentSortCompareFn;
  23475. }
  23476. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23477. /**
  23478. * Set the opaque sort comparison function.
  23479. * If null the sub meshes will be render in the order they were created
  23480. */
  23481. set: function (value) {
  23482. this._opaqueSortCompareFn = value;
  23483. if (value) {
  23484. this._renderOpaque = this.renderOpaqueSorted;
  23485. }
  23486. else {
  23487. this._renderOpaque = RenderingGroup.renderUnsorted;
  23488. }
  23489. },
  23490. enumerable: true,
  23491. configurable: true
  23492. });
  23493. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23494. /**
  23495. * Set the alpha test sort comparison function.
  23496. * If null the sub meshes will be render in the order they were created
  23497. */
  23498. set: function (value) {
  23499. this._alphaTestSortCompareFn = value;
  23500. if (value) {
  23501. this._renderAlphaTest = this.renderAlphaTestSorted;
  23502. }
  23503. else {
  23504. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23505. }
  23506. },
  23507. enumerable: true,
  23508. configurable: true
  23509. });
  23510. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23511. /**
  23512. * Set the transparent sort comparison function.
  23513. * If null the sub meshes will be render in the order they were created
  23514. */
  23515. set: function (value) {
  23516. if (value) {
  23517. this._transparentSortCompareFn = value;
  23518. }
  23519. else {
  23520. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23521. }
  23522. this._renderTransparent = this.renderTransparentSorted;
  23523. },
  23524. enumerable: true,
  23525. configurable: true
  23526. });
  23527. /**
  23528. * Render all the sub meshes contained in the group.
  23529. * @param customRenderFunction Used to override the default render behaviour of the group.
  23530. * @returns true if rendered some submeshes.
  23531. */
  23532. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23533. if (customRenderFunction) {
  23534. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23535. return;
  23536. }
  23537. var engine = this._scene.getEngine();
  23538. // Depth only
  23539. if (this._depthOnlySubMeshes.length !== 0) {
  23540. engine.setColorWrite(false);
  23541. this._renderAlphaTest(this._depthOnlySubMeshes);
  23542. engine.setColorWrite(true);
  23543. }
  23544. // Opaque
  23545. if (this._opaqueSubMeshes.length !== 0) {
  23546. this._renderOpaque(this._opaqueSubMeshes);
  23547. }
  23548. // Alpha test
  23549. if (this._alphaTestSubMeshes.length !== 0) {
  23550. this._renderAlphaTest(this._alphaTestSubMeshes);
  23551. }
  23552. var stencilState = engine.getStencilBuffer();
  23553. engine.setStencilBuffer(false);
  23554. // Sprites
  23555. if (renderSprites) {
  23556. this._renderSprites();
  23557. }
  23558. // Particles
  23559. if (renderParticles) {
  23560. this._renderParticles(activeMeshes);
  23561. }
  23562. if (this.onBeforeTransparentRendering) {
  23563. this.onBeforeTransparentRendering();
  23564. }
  23565. // Transparent
  23566. if (this._transparentSubMeshes.length !== 0) {
  23567. this._renderTransparent(this._transparentSubMeshes);
  23568. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23569. }
  23570. // Set back stencil to false in case it changes before the edge renderer.
  23571. engine.setStencilBuffer(false);
  23572. // Edges
  23573. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23574. this._edgesRenderers.data[edgesRendererIndex].render();
  23575. }
  23576. // Restore Stencil state.
  23577. engine.setStencilBuffer(stencilState);
  23578. };
  23579. /**
  23580. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23581. * @param subMeshes The submeshes to render
  23582. */
  23583. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23584. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23585. };
  23586. /**
  23587. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23588. * @param subMeshes The submeshes to render
  23589. */
  23590. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23591. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23592. };
  23593. /**
  23594. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23595. * @param subMeshes The submeshes to render
  23596. */
  23597. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23598. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23599. };
  23600. /**
  23601. * Renders the submeshes in a specified order.
  23602. * @param subMeshes The submeshes to sort before render
  23603. * @param sortCompareFn The comparison function use to sort
  23604. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23605. * @param transparent Specifies to activate blending if true
  23606. */
  23607. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23608. var subIndex = 0;
  23609. var subMesh;
  23610. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23611. for (; subIndex < subMeshes.length; subIndex++) {
  23612. subMesh = subMeshes.data[subIndex];
  23613. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23614. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23615. }
  23616. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23617. if (sortCompareFn) {
  23618. sortedArray.sort(sortCompareFn);
  23619. }
  23620. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23621. subMesh = sortedArray[subIndex];
  23622. if (transparent) {
  23623. var material = subMesh.getMaterial();
  23624. if (material && material.needDepthPrePass) {
  23625. var engine = material.getScene().getEngine();
  23626. engine.setColorWrite(false);
  23627. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23628. subMesh.render(false);
  23629. engine.setColorWrite(true);
  23630. }
  23631. }
  23632. subMesh.render(transparent);
  23633. }
  23634. };
  23635. /**
  23636. * Renders the submeshes in the order they were dispatched (no sort applied).
  23637. * @param subMeshes The submeshes to render
  23638. */
  23639. RenderingGroup.renderUnsorted = function (subMeshes) {
  23640. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23641. var submesh = subMeshes.data[subIndex];
  23642. submesh.render(false);
  23643. }
  23644. };
  23645. /**
  23646. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23647. * are rendered back to front if in the same alpha index.
  23648. *
  23649. * @param a The first submesh
  23650. * @param b The second submesh
  23651. * @returns The result of the comparison
  23652. */
  23653. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23654. // Alpha index first
  23655. if (a._alphaIndex > b._alphaIndex) {
  23656. return 1;
  23657. }
  23658. if (a._alphaIndex < b._alphaIndex) {
  23659. return -1;
  23660. }
  23661. // Then distance to camera
  23662. return RenderingGroup.backToFrontSortCompare(a, b);
  23663. };
  23664. /**
  23665. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23666. * are rendered back to front.
  23667. *
  23668. * @param a The first submesh
  23669. * @param b The second submesh
  23670. * @returns The result of the comparison
  23671. */
  23672. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23673. // Then distance to camera
  23674. if (a._distanceToCamera < b._distanceToCamera) {
  23675. return 1;
  23676. }
  23677. if (a._distanceToCamera > b._distanceToCamera) {
  23678. return -1;
  23679. }
  23680. return 0;
  23681. };
  23682. /**
  23683. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23684. * are rendered front to back (prevent overdraw).
  23685. *
  23686. * @param a The first submesh
  23687. * @param b The second submesh
  23688. * @returns The result of the comparison
  23689. */
  23690. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23691. // Then distance to camera
  23692. if (a._distanceToCamera < b._distanceToCamera) {
  23693. return -1;
  23694. }
  23695. if (a._distanceToCamera > b._distanceToCamera) {
  23696. return 1;
  23697. }
  23698. return 0;
  23699. };
  23700. /**
  23701. * Resets the different lists of submeshes to prepare a new frame.
  23702. */
  23703. RenderingGroup.prototype.prepare = function () {
  23704. this._opaqueSubMeshes.reset();
  23705. this._transparentSubMeshes.reset();
  23706. this._alphaTestSubMeshes.reset();
  23707. this._depthOnlySubMeshes.reset();
  23708. this._particleSystems.reset();
  23709. this._spriteManagers.reset();
  23710. this._edgesRenderers.reset();
  23711. };
  23712. RenderingGroup.prototype.dispose = function () {
  23713. this._opaqueSubMeshes.dispose();
  23714. this._transparentSubMeshes.dispose();
  23715. this._alphaTestSubMeshes.dispose();
  23716. this._depthOnlySubMeshes.dispose();
  23717. this._particleSystems.dispose();
  23718. this._spriteManagers.dispose();
  23719. this._edgesRenderers.dispose();
  23720. };
  23721. /**
  23722. * Inserts the submesh in its correct queue depending on its material.
  23723. * @param subMesh The submesh to dispatch
  23724. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23725. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23726. */
  23727. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23728. // Get mesh and materials if not provided
  23729. if (mesh === undefined) {
  23730. mesh = subMesh.getMesh();
  23731. }
  23732. if (material === undefined) {
  23733. material = subMesh.getMaterial();
  23734. }
  23735. if (material === null || material === undefined) {
  23736. return;
  23737. }
  23738. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23739. this._transparentSubMeshes.push(subMesh);
  23740. }
  23741. else if (material.needAlphaTesting()) { // Alpha test
  23742. if (material.needDepthPrePass) {
  23743. this._depthOnlySubMeshes.push(subMesh);
  23744. }
  23745. this._alphaTestSubMeshes.push(subMesh);
  23746. }
  23747. else {
  23748. if (material.needDepthPrePass) {
  23749. this._depthOnlySubMeshes.push(subMesh);
  23750. }
  23751. this._opaqueSubMeshes.push(subMesh); // Opaque
  23752. }
  23753. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23754. this._edgesRenderers.push(mesh._edgesRenderer);
  23755. }
  23756. };
  23757. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23758. this._spriteManagers.push(spriteManager);
  23759. };
  23760. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23761. this._particleSystems.push(particleSystem);
  23762. };
  23763. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23764. if (this._particleSystems.length === 0) {
  23765. return;
  23766. }
  23767. // Particles
  23768. var activeCamera = this._scene.activeCamera;
  23769. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23770. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23771. var particleSystem = this._particleSystems.data[particleIndex];
  23772. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23773. continue;
  23774. }
  23775. var emitter = particleSystem.emitter;
  23776. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23777. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23778. }
  23779. }
  23780. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23781. };
  23782. RenderingGroup.prototype._renderSprites = function () {
  23783. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23784. return;
  23785. }
  23786. // Sprites
  23787. var activeCamera = this._scene.activeCamera;
  23788. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23789. for (var id = 0; id < this._spriteManagers.length; id++) {
  23790. var spriteManager = this._spriteManagers.data[id];
  23791. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23792. spriteManager.render();
  23793. }
  23794. }
  23795. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23796. };
  23797. return RenderingGroup;
  23798. }());
  23799. BABYLON.RenderingGroup = RenderingGroup;
  23800. })(BABYLON || (BABYLON = {}));
  23801. //# sourceMappingURL=babylon.renderingGroup.js.map
  23802. var BABYLON;
  23803. (function (BABYLON) {
  23804. /** @hidden */
  23805. var ClickInfo = /** @class */ (function () {
  23806. function ClickInfo() {
  23807. this._singleClick = false;
  23808. this._doubleClick = false;
  23809. this._hasSwiped = false;
  23810. this._ignore = false;
  23811. }
  23812. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23813. get: function () {
  23814. return this._singleClick;
  23815. },
  23816. set: function (b) {
  23817. this._singleClick = b;
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23823. get: function () {
  23824. return this._doubleClick;
  23825. },
  23826. set: function (b) {
  23827. this._doubleClick = b;
  23828. },
  23829. enumerable: true,
  23830. configurable: true
  23831. });
  23832. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23833. get: function () {
  23834. return this._hasSwiped;
  23835. },
  23836. set: function (b) {
  23837. this._hasSwiped = b;
  23838. },
  23839. enumerable: true,
  23840. configurable: true
  23841. });
  23842. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23843. get: function () {
  23844. return this._ignore;
  23845. },
  23846. set: function (b) {
  23847. this._ignore = b;
  23848. },
  23849. enumerable: true,
  23850. configurable: true
  23851. });
  23852. return ClickInfo;
  23853. }());
  23854. /**
  23855. * This class is used by the onRenderingGroupObservable
  23856. */
  23857. var RenderingGroupInfo = /** @class */ (function () {
  23858. function RenderingGroupInfo() {
  23859. }
  23860. /**
  23861. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23862. * This stage will be fired no matter what
  23863. */
  23864. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23865. /**
  23866. * Called before opaque object are rendered.
  23867. * This stage will be fired only if there's 3D Opaque content to render
  23868. */
  23869. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23870. /**
  23871. * Called after the opaque objects are rendered and before the transparent ones
  23872. * This stage will be fired only if there's 3D transparent content to render
  23873. */
  23874. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23875. /**
  23876. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23877. * This stage will be fired no matter what
  23878. */
  23879. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23880. return RenderingGroupInfo;
  23881. }());
  23882. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23883. /**
  23884. * Represents a scene to be rendered by the engine.
  23885. * @see http://doc.babylonjs.com/features/scene
  23886. */
  23887. var Scene = /** @class */ (function () {
  23888. /**
  23889. * Creates a new Scene
  23890. * @param engine defines the engine to use to render this scene
  23891. */
  23892. function Scene(engine) {
  23893. // Members
  23894. /**
  23895. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23896. */
  23897. this.autoClear = true;
  23898. /**
  23899. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23900. */
  23901. this.autoClearDepthAndStencil = true;
  23902. /**
  23903. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23904. */
  23905. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23906. /**
  23907. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23908. */
  23909. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23910. this._forceWireframe = false;
  23911. this._forcePointsCloud = false;
  23912. /**
  23913. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23914. */
  23915. this.forceShowBoundingBoxes = false;
  23916. /**
  23917. * Gets or sets a boolean indicating if animations are enabled
  23918. */
  23919. this.animationsEnabled = true;
  23920. this._animationPropertiesOverride = null;
  23921. /**
  23922. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23923. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23924. */
  23925. this.useConstantAnimationDeltaTime = false;
  23926. /**
  23927. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23928. * Please note that it requires to run a ray cast through the scene on every frame
  23929. */
  23930. this.constantlyUpdateMeshUnderPointer = false;
  23931. /**
  23932. * Defines the HTML cursor to use when hovering over interactive elements
  23933. */
  23934. this.hoverCursor = "pointer";
  23935. /**
  23936. * Defines the HTML default cursor to use (empty by default)
  23937. */
  23938. this.defaultCursor = "";
  23939. /**
  23940. * This is used to call preventDefault() on pointer down
  23941. * in order to block unwanted artifacts like system double clicks
  23942. */
  23943. this.preventDefaultOnPointerDown = true;
  23944. // Metadata
  23945. /**
  23946. * Gets or sets user defined metadata
  23947. */
  23948. this.metadata = null;
  23949. /**
  23950. * Use this array to add regular expressions used to disable offline support for specific urls
  23951. */
  23952. this.disableOfflineSupportExceptionRules = new Array();
  23953. /**
  23954. * An event triggered when the scene is disposed.
  23955. */
  23956. this.onDisposeObservable = new BABYLON.Observable();
  23957. this._onDisposeObserver = null;
  23958. /**
  23959. * An event triggered before rendering the scene (right after animations and physics)
  23960. */
  23961. this.onBeforeRenderObservable = new BABYLON.Observable();
  23962. this._onBeforeRenderObserver = null;
  23963. /**
  23964. * An event triggered after rendering the scene
  23965. */
  23966. this.onAfterRenderObservable = new BABYLON.Observable();
  23967. this._onAfterRenderObserver = null;
  23968. /**
  23969. * An event triggered before animating the scene
  23970. */
  23971. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23972. /**
  23973. * An event triggered after animations processing
  23974. */
  23975. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23976. /**
  23977. * An event triggered before draw calls are ready to be sent
  23978. */
  23979. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23980. /**
  23981. * An event triggered after draw calls have been sent
  23982. */
  23983. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered when physic simulation is about to be run
  23986. */
  23987. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered when physic simulation has been done
  23990. */
  23991. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23992. /**
  23993. * An event triggered when the scene is ready
  23994. */
  23995. this.onReadyObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered before rendering a camera
  23998. */
  23999. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24000. this._onBeforeCameraRenderObserver = null;
  24001. /**
  24002. * An event triggered after rendering a camera
  24003. */
  24004. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24005. this._onAfterCameraRenderObserver = null;
  24006. /**
  24007. * An event triggered when active meshes evaluation is about to start
  24008. */
  24009. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when active meshes evaluation is done
  24012. */
  24013. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when particles rendering is about to start
  24016. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24017. */
  24018. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when particles rendering is done
  24021. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24022. */
  24023. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24024. /**
  24025. * An event triggered when sprites rendering is about to start
  24026. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24027. */
  24028. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when sprites rendering is done
  24031. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24032. */
  24033. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24036. */
  24037. this.onDataLoadedObservable = new BABYLON.Observable();
  24038. /**
  24039. * An event triggered when a camera is created
  24040. */
  24041. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24042. /**
  24043. * An event triggered when a camera is removed
  24044. */
  24045. this.onCameraRemovedObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when a light is created
  24048. */
  24049. this.onNewLightAddedObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when a light is removed
  24052. */
  24053. this.onLightRemovedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when a geometry is created
  24056. */
  24057. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24058. /**
  24059. * An event triggered when a geometry is removed
  24060. */
  24061. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when a transform node is created
  24064. */
  24065. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered when a transform node is removed
  24068. */
  24069. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24070. /**
  24071. * An event triggered when a mesh is created
  24072. */
  24073. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when a mesh is removed
  24076. */
  24077. this.onMeshRemovedObservable = new BABYLON.Observable();
  24078. /**
  24079. * An event triggered when render targets are about to be rendered
  24080. * Can happen multiple times per frame.
  24081. */
  24082. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24083. /**
  24084. * An event triggered when render targets were rendered.
  24085. * Can happen multiple times per frame.
  24086. */
  24087. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24088. /**
  24089. * An event triggered before calculating deterministic simulation step
  24090. */
  24091. this.onBeforeStepObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered after calculating deterministic simulation step
  24094. */
  24095. this.onAfterStepObservable = new BABYLON.Observable();
  24096. /**
  24097. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24098. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24099. * 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)
  24100. */
  24101. this.onRenderingGroupObservable = new BABYLON.Observable();
  24102. // Animations
  24103. /**
  24104. * Gets a list of Animations associated with the scene
  24105. */
  24106. this.animations = [];
  24107. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24108. /**
  24109. * 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).
  24110. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24111. */
  24112. this.onPrePointerObservable = new BABYLON.Observable();
  24113. /**
  24114. * Observable event triggered each time an input event is received from the rendering canvas
  24115. */
  24116. this.onPointerObservable = new BABYLON.Observable();
  24117. this._meshPickProceed = false;
  24118. this._currentPickResult = null;
  24119. this._previousPickResult = null;
  24120. this._totalPointersPressed = 0;
  24121. this._doubleClickOccured = false;
  24122. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24123. this.cameraToUseForPointers = null;
  24124. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24125. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24126. this._startingPointerTime = 0;
  24127. this._previousStartingPointerTime = 0;
  24128. this._pointerCaptures = {};
  24129. // Deterministic lockstep
  24130. this._timeAccumulator = 0;
  24131. this._currentStepId = 0;
  24132. this._currentInternalStep = 0;
  24133. // Keyboard
  24134. /**
  24135. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24136. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24137. */
  24138. this.onPreKeyboardObservable = new BABYLON.Observable();
  24139. /**
  24140. * Observable event triggered each time an keyboard event is received from the hosting window
  24141. */
  24142. this.onKeyboardObservable = new BABYLON.Observable();
  24143. // Coordinates system
  24144. this._useRightHandedSystem = false;
  24145. // Fog
  24146. this._fogEnabled = true;
  24147. this._fogMode = Scene.FOGMODE_NONE;
  24148. /**
  24149. * Gets or sets the fog color to use
  24150. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24151. */
  24152. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24153. /**
  24154. * Gets or sets the fog density to use
  24155. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24156. */
  24157. this.fogDensity = 0.1;
  24158. /**
  24159. * Gets or sets the fog start distance to use
  24160. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24161. */
  24162. this.fogStart = 0;
  24163. /**
  24164. * Gets or sets the fog end distance to use
  24165. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24166. */
  24167. this.fogEnd = 1000.0;
  24168. // Lights
  24169. this._shadowsEnabled = true;
  24170. this._lightsEnabled = true;
  24171. /**
  24172. * All of the lights added to this scene
  24173. * @see http://doc.babylonjs.com/babylon101/lights
  24174. */
  24175. this.lights = new Array();
  24176. // Cameras
  24177. /** All of the cameras added to this scene.
  24178. * @see http://doc.babylonjs.com/babylon101/cameras
  24179. */
  24180. this.cameras = new Array();
  24181. /** All of the active cameras added to this scene. */
  24182. this.activeCameras = new Array();
  24183. // Meshes
  24184. /**
  24185. * All of the tranform nodes added to this scene
  24186. * @see http://doc.babylonjs.com/how_to/transformnode
  24187. */
  24188. this.transformNodes = new Array();
  24189. /**
  24190. * All of the (abstract) meshes added to this scene
  24191. */
  24192. this.meshes = new Array();
  24193. /**
  24194. * All of the animation groups added to this scene
  24195. * @see http://doc.babylonjs.com/how_to/group
  24196. */
  24197. this.animationGroups = new Array();
  24198. // Geometries
  24199. this._geometries = new Array();
  24200. /**
  24201. * All of the materials added to this scene
  24202. * @see http://doc.babylonjs.com/babylon101/materials
  24203. */
  24204. this.materials = new Array();
  24205. /**
  24206. * All of the multi-materials added to this scene
  24207. * @see http://doc.babylonjs.com/how_to/multi_materials
  24208. */
  24209. this.multiMaterials = new Array();
  24210. // Textures
  24211. this._texturesEnabled = true;
  24212. /**
  24213. * All of the textures added to this scene
  24214. */
  24215. this.textures = new Array();
  24216. // Particles
  24217. /**
  24218. * Gets or sets a boolean indicating if particles are enabled on this scene
  24219. */
  24220. this.particlesEnabled = true;
  24221. /**
  24222. * All of the particle systems added to this scene
  24223. * @see http://doc.babylonjs.com/babylon101/particles
  24224. */
  24225. this.particleSystems = new Array();
  24226. // Sprites
  24227. /**
  24228. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24229. */
  24230. this.spritesEnabled = true;
  24231. /**
  24232. * All of the sprite managers added to this scene
  24233. * @see http://doc.babylonjs.com/babylon101/sprites
  24234. */
  24235. this.spriteManagers = new Array();
  24236. /**
  24237. * The list of layers (background and foreground) of the scene
  24238. */
  24239. this.layers = new Array();
  24240. /**
  24241. * The list of effect layers (highlights/glow) added to the scene
  24242. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24243. * @see http://doc.babylonjs.com/how_to/glow_layer
  24244. */
  24245. this.effectLayers = new Array();
  24246. // Skeletons
  24247. this._skeletonsEnabled = true;
  24248. /**
  24249. * The list of skeletons added to the scene
  24250. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24251. */
  24252. this.skeletons = new Array();
  24253. // Morph targets
  24254. /**
  24255. * The list of morph target managers added to the scene
  24256. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24257. */
  24258. this.morphTargetManagers = new Array();
  24259. // Lens flares
  24260. /**
  24261. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24262. */
  24263. this.lensFlaresEnabled = true;
  24264. /**
  24265. * The list of lens flare system added to the scene
  24266. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24267. */
  24268. this.lensFlareSystems = new Array();
  24269. // Collisions
  24270. /**
  24271. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24272. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24273. */
  24274. this.collisionsEnabled = true;
  24275. /**
  24276. * Defines the gravity applied to this scene (used only for collisions)
  24277. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24278. */
  24279. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24280. // Postprocesses
  24281. /**
  24282. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24283. */
  24284. this.postProcessesEnabled = true;
  24285. /**
  24286. * The list of postprocesses added to the scene
  24287. */
  24288. this.postProcesses = new Array();
  24289. // Customs render targets
  24290. /**
  24291. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24292. */
  24293. this.renderTargetsEnabled = true;
  24294. /**
  24295. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24296. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24297. */
  24298. this.dumpNextRenderTargets = false;
  24299. /**
  24300. * The list of user defined render targets added to the scene
  24301. */
  24302. this.customRenderTargets = new Array();
  24303. /**
  24304. * Gets the list of meshes imported to the scene through SceneLoader
  24305. */
  24306. this.importedMeshesFiles = new Array();
  24307. // Probes
  24308. /**
  24309. * Gets or sets a boolean indicating if probes are enabled on this scene
  24310. */
  24311. this.probesEnabled = true;
  24312. /**
  24313. * The list of reflection probes added to the scene
  24314. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24315. */
  24316. this.reflectionProbes = new Array();
  24317. /** @hidden */
  24318. this._actionManagers = new Array();
  24319. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24320. // Procedural textures
  24321. /**
  24322. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24323. */
  24324. this.proceduralTexturesEnabled = true;
  24325. /**
  24326. * The list of procedural textures added to the scene
  24327. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24328. */
  24329. this.proceduralTextures = new Array();
  24330. /**
  24331. * The list of sound tracks added to the scene
  24332. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24333. */
  24334. this.soundTracks = new Array();
  24335. this._audioEnabled = true;
  24336. this._headphone = false;
  24337. // Performance counters
  24338. this._totalVertices = new BABYLON.PerfCounter();
  24339. /** @hidden */
  24340. this._activeIndices = new BABYLON.PerfCounter();
  24341. /** @hidden */
  24342. this._activeParticles = new BABYLON.PerfCounter();
  24343. /** @hidden */
  24344. this._activeBones = new BABYLON.PerfCounter();
  24345. this._animationTime = 0;
  24346. /**
  24347. * Gets or sets a general scale for animation speed
  24348. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24349. */
  24350. this.animationTimeScale = 1;
  24351. this._renderId = 0;
  24352. this._executeWhenReadyTimeoutId = -1;
  24353. this._intermediateRendering = false;
  24354. this._viewUpdateFlag = -1;
  24355. this._projectionUpdateFlag = -1;
  24356. this._alternateViewUpdateFlag = -1;
  24357. this._alternateProjectionUpdateFlag = -1;
  24358. /** @hidden */
  24359. this._toBeDisposed = new BABYLON.SmartArray(256);
  24360. this._activeRequests = new Array();
  24361. this._pendingData = new Array();
  24362. this._isDisposed = false;
  24363. /**
  24364. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24365. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24366. */
  24367. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24368. this._activeMeshes = new BABYLON.SmartArray(256);
  24369. this._processedMaterials = new BABYLON.SmartArray(256);
  24370. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24371. /** @hidden */
  24372. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24373. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24374. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24375. /** @hidden */
  24376. this._activeAnimatables = new Array();
  24377. this._transformMatrix = BABYLON.Matrix.Zero();
  24378. this._useAlternateCameraConfiguration = false;
  24379. this._alternateRendering = false;
  24380. /**
  24381. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24382. * This is useful if there are more lights that the maximum simulteanous authorized
  24383. */
  24384. this.requireLightSorting = false;
  24385. this._depthRenderer = {};
  24386. this._activeMeshesFrozen = false;
  24387. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24388. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24389. this._engine.scenes.push(this);
  24390. this._uid = null;
  24391. this._renderingManager = new BABYLON.RenderingManager(this);
  24392. if (BABYLON.PostProcessManager) {
  24393. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24394. }
  24395. if (BABYLON.OutlineRenderer) {
  24396. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24397. }
  24398. if (BABYLON.Tools.IsWindowObjectExist()) {
  24399. this.attachControl();
  24400. }
  24401. //simplification queue
  24402. if (BABYLON.SimplificationQueue) {
  24403. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24404. }
  24405. //collision coordinator initialization. For now legacy per default.
  24406. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24407. // Uniform Buffer
  24408. this._createUbo();
  24409. // Default Image processing definition
  24410. if (BABYLON.ImageProcessingConfiguration) {
  24411. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24412. }
  24413. }
  24414. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24415. /** The fog is deactivated */
  24416. get: function () {
  24417. return Scene._FOGMODE_NONE;
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24423. /** The fog density is following an exponential function */
  24424. get: function () {
  24425. return Scene._FOGMODE_EXP;
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24431. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24432. get: function () {
  24433. return Scene._FOGMODE_EXP2;
  24434. },
  24435. enumerable: true,
  24436. configurable: true
  24437. });
  24438. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24439. /** The fog density is following a linear function. */
  24440. get: function () {
  24441. return Scene._FOGMODE_LINEAR;
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24447. /**
  24448. * Texture used in all pbr material as the reflection texture.
  24449. * As in the majority of the scene they are the same (exception for multi room and so on),
  24450. * this is easier to reference from here than from all the materials.
  24451. */
  24452. get: function () {
  24453. return this._environmentTexture;
  24454. },
  24455. /**
  24456. * Texture used in all pbr material as the reflection texture.
  24457. * As in the majority of the scene they are the same (exception for multi room and so on),
  24458. * this is easier to set here than in all the materials.
  24459. */
  24460. set: function (value) {
  24461. if (this._environmentTexture === value) {
  24462. return;
  24463. }
  24464. this._environmentTexture = value;
  24465. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24471. /**
  24472. * Default image processing configuration used either in the rendering
  24473. * Forward main pass or through the imageProcessingPostProcess if present.
  24474. * As in the majority of the scene they are the same (exception for multi camera),
  24475. * this is easier to reference from here than from all the materials and post process.
  24476. *
  24477. * No setter as we it is a shared configuration, you can set the values instead.
  24478. */
  24479. get: function () {
  24480. return this._imageProcessingConfiguration;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24486. get: function () {
  24487. return this._forceWireframe;
  24488. },
  24489. /**
  24490. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24491. */
  24492. set: function (value) {
  24493. if (this._forceWireframe === value) {
  24494. return;
  24495. }
  24496. this._forceWireframe = value;
  24497. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24498. },
  24499. enumerable: true,
  24500. configurable: true
  24501. });
  24502. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24503. get: function () {
  24504. return this._forcePointsCloud;
  24505. },
  24506. /**
  24507. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24508. */
  24509. set: function (value) {
  24510. if (this._forcePointsCloud === value) {
  24511. return;
  24512. }
  24513. this._forcePointsCloud = value;
  24514. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24520. /**
  24521. * Gets or sets the animation properties override
  24522. */
  24523. get: function () {
  24524. return this._animationPropertiesOverride;
  24525. },
  24526. set: function (value) {
  24527. this._animationPropertiesOverride = value;
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "onDispose", {
  24533. /** Sets a function to be executed when this scene is disposed. */
  24534. set: function (callback) {
  24535. if (this._onDisposeObserver) {
  24536. this.onDisposeObservable.remove(this._onDisposeObserver);
  24537. }
  24538. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "beforeRender", {
  24544. /** Sets a function to be executed before rendering this scene */
  24545. set: function (callback) {
  24546. if (this._onBeforeRenderObserver) {
  24547. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24548. }
  24549. if (callback) {
  24550. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24551. }
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "afterRender", {
  24557. /** Sets a function to be executed after rendering this scene */
  24558. set: function (callback) {
  24559. if (this._onAfterRenderObserver) {
  24560. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24561. }
  24562. if (callback) {
  24563. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24564. }
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24570. /** Sets a function to be executed before rendering a camera*/
  24571. set: function (callback) {
  24572. if (this._onBeforeCameraRenderObserver) {
  24573. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24574. }
  24575. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24581. /** Sets a function to be executed after rendering a camera*/
  24582. set: function (callback) {
  24583. if (this._onAfterCameraRenderObserver) {
  24584. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24585. }
  24586. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24592. /**
  24593. * Gets the gamepad manager associated with the scene
  24594. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24595. */
  24596. get: function () {
  24597. if (!this._gamepadManager) {
  24598. this._gamepadManager = new BABYLON.GamepadManager(this);
  24599. }
  24600. return this._gamepadManager;
  24601. },
  24602. enumerable: true,
  24603. configurable: true
  24604. });
  24605. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24606. /**
  24607. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24608. */
  24609. get: function () {
  24610. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24616. get: function () {
  24617. return this._useRightHandedSystem;
  24618. },
  24619. /**
  24620. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24621. */
  24622. set: function (value) {
  24623. if (this._useRightHandedSystem === value) {
  24624. return;
  24625. }
  24626. this._useRightHandedSystem = value;
  24627. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24628. },
  24629. enumerable: true,
  24630. configurable: true
  24631. });
  24632. /**
  24633. * Sets the step Id used by deterministic lock step
  24634. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24635. * @param newStepId defines the step Id
  24636. */
  24637. Scene.prototype.setStepId = function (newStepId) {
  24638. this._currentStepId = newStepId;
  24639. };
  24640. ;
  24641. /**
  24642. * Gets the step Id used by deterministic lock step
  24643. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24644. * @returns the step Id
  24645. */
  24646. Scene.prototype.getStepId = function () {
  24647. return this._currentStepId;
  24648. };
  24649. ;
  24650. /**
  24651. * Gets the internal step used by deterministic lock step
  24652. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24653. * @returns the internal step
  24654. */
  24655. Scene.prototype.getInternalStep = function () {
  24656. return this._currentInternalStep;
  24657. };
  24658. ;
  24659. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24660. get: function () {
  24661. return this._fogEnabled;
  24662. },
  24663. /**
  24664. * Gets or sets a boolean indicating if fog is enabled on this scene
  24665. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24666. */
  24667. set: function (value) {
  24668. if (this._fogEnabled === value) {
  24669. return;
  24670. }
  24671. this._fogEnabled = value;
  24672. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(Scene.prototype, "fogMode", {
  24678. get: function () {
  24679. return this._fogMode;
  24680. },
  24681. /**
  24682. * Gets or sets the fog mode to use
  24683. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24684. */
  24685. set: function (value) {
  24686. if (this._fogMode === value) {
  24687. return;
  24688. }
  24689. this._fogMode = value;
  24690. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24696. get: function () {
  24697. return this._shadowsEnabled;
  24698. },
  24699. /**
  24700. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24701. */
  24702. set: function (value) {
  24703. if (this._shadowsEnabled === value) {
  24704. return;
  24705. }
  24706. this._shadowsEnabled = value;
  24707. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24713. get: function () {
  24714. return this._lightsEnabled;
  24715. },
  24716. /**
  24717. * Gets or sets a boolean indicating if lights are enabled on this scene
  24718. */
  24719. set: function (value) {
  24720. if (this._lightsEnabled === value) {
  24721. return;
  24722. }
  24723. this._lightsEnabled = value;
  24724. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24730. /** The default material used on meshes when no material is affected */
  24731. get: function () {
  24732. if (!this._defaultMaterial) {
  24733. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24734. }
  24735. return this._defaultMaterial;
  24736. },
  24737. /** The default material used on meshes when no material is affected */
  24738. set: function (value) {
  24739. this._defaultMaterial = value;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24745. get: function () {
  24746. return this._texturesEnabled;
  24747. },
  24748. /**
  24749. * Gets or sets a boolean indicating if textures are enabled on this scene
  24750. */
  24751. set: function (value) {
  24752. if (this._texturesEnabled === value) {
  24753. return;
  24754. }
  24755. this._texturesEnabled = value;
  24756. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24762. get: function () {
  24763. return this._skeletonsEnabled;
  24764. },
  24765. /**
  24766. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24767. */
  24768. set: function (value) {
  24769. if (this._skeletonsEnabled === value) {
  24770. return;
  24771. }
  24772. this._skeletonsEnabled = value;
  24773. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24779. /**
  24780. * Gets the postprocess render pipeline manager
  24781. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24782. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24783. */
  24784. get: function () {
  24785. if (!this._postProcessRenderPipelineManager) {
  24786. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24787. }
  24788. return this._postProcessRenderPipelineManager;
  24789. },
  24790. enumerable: true,
  24791. configurable: true
  24792. });
  24793. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24794. /**
  24795. * Gets the main soundtrack associated with the scene
  24796. */
  24797. get: function () {
  24798. if (!this._mainSoundTrack) {
  24799. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24800. }
  24801. return this._mainSoundTrack;
  24802. },
  24803. enumerable: true,
  24804. configurable: true
  24805. });
  24806. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24807. /** @hidden */
  24808. get: function () {
  24809. return this._alternateRendering;
  24810. },
  24811. enumerable: true,
  24812. configurable: true
  24813. });
  24814. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24815. /**
  24816. * Gets the list of frustum planes (built from the active camera)
  24817. */
  24818. get: function () {
  24819. return this._frustumPlanes;
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24825. /**
  24826. * Gets the current geometry buffer associated to the scene.
  24827. */
  24828. get: function () {
  24829. return this._geometryBufferRenderer;
  24830. },
  24831. /**
  24832. * Sets the current geometry buffer for the scene.
  24833. */
  24834. set: function (geometryBufferRenderer) {
  24835. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24836. this._geometryBufferRenderer = geometryBufferRenderer;
  24837. }
  24838. },
  24839. enumerable: true,
  24840. configurable: true
  24841. });
  24842. Object.defineProperty(Scene.prototype, "debugLayer", {
  24843. /**
  24844. * Gets the debug layer (aka Inspector) associated with the scene
  24845. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24846. */
  24847. get: function () {
  24848. if (!this._debugLayer) {
  24849. this._debugLayer = new BABYLON.DebugLayer(this);
  24850. }
  24851. return this._debugLayer;
  24852. },
  24853. enumerable: true,
  24854. configurable: true
  24855. });
  24856. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24857. /**
  24858. * Gets a boolean indicating if collisions are processed on a web worker
  24859. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24860. */
  24861. get: function () {
  24862. return this._workerCollisions;
  24863. },
  24864. set: function (enabled) {
  24865. if (!BABYLON.CollisionCoordinatorLegacy) {
  24866. return;
  24867. }
  24868. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24869. this._workerCollisions = enabled;
  24870. if (this.collisionCoordinator) {
  24871. this.collisionCoordinator.destroy();
  24872. }
  24873. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24874. this.collisionCoordinator.init(this);
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24880. /**
  24881. * Gets the octree used to boost mesh selection (picking)
  24882. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24883. */
  24884. get: function () {
  24885. return this._selectionOctree;
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24891. /**
  24892. * Gets the mesh that is currently under the pointer
  24893. */
  24894. get: function () {
  24895. return this._pointerOverMesh;
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. Object.defineProperty(Scene.prototype, "pointerX", {
  24901. /**
  24902. * Gets the current on-screen X position of the pointer
  24903. */
  24904. get: function () {
  24905. return this._pointerX;
  24906. },
  24907. enumerable: true,
  24908. configurable: true
  24909. });
  24910. Object.defineProperty(Scene.prototype, "pointerY", {
  24911. /**
  24912. * Gets the current on-screen Y position of the pointer
  24913. */
  24914. get: function () {
  24915. return this._pointerY;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. /**
  24921. * Gets the cached material (ie. the latest rendered one)
  24922. * @returns the cached material
  24923. */
  24924. Scene.prototype.getCachedMaterial = function () {
  24925. return this._cachedMaterial;
  24926. };
  24927. /**
  24928. * Gets the cached effect (ie. the latest rendered one)
  24929. * @returns the cached effect
  24930. */
  24931. Scene.prototype.getCachedEffect = function () {
  24932. return this._cachedEffect;
  24933. };
  24934. /**
  24935. * Gets the cached visibility state (ie. the latest rendered one)
  24936. * @returns the cached visibility state
  24937. */
  24938. Scene.prototype.getCachedVisibility = function () {
  24939. return this._cachedVisibility;
  24940. };
  24941. /**
  24942. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24943. * @param material defines the current material
  24944. * @param effect defines the current effect
  24945. * @param visibility defines the current visibility state
  24946. * @returns true if one parameter is not cached
  24947. */
  24948. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24949. if (visibility === void 0) { visibility = 1; }
  24950. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24951. };
  24952. /**
  24953. * Gets the bounding box renderer associated with the scene
  24954. * @returns a BoundingBoxRenderer
  24955. */
  24956. Scene.prototype.getBoundingBoxRenderer = function () {
  24957. if (!this._boundingBoxRenderer) {
  24958. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24959. }
  24960. return this._boundingBoxRenderer;
  24961. };
  24962. /**
  24963. * Gets the outline renderer associated with the scene
  24964. * @returns a OutlineRenderer
  24965. */
  24966. Scene.prototype.getOutlineRenderer = function () {
  24967. return this._outlineRenderer;
  24968. };
  24969. /**
  24970. * Gets the engine associated with the scene
  24971. * @returns an Engine
  24972. */
  24973. Scene.prototype.getEngine = function () {
  24974. return this._engine;
  24975. };
  24976. /**
  24977. * Gets the total number of vertices rendered per frame
  24978. * @returns the total number of vertices rendered per frame
  24979. */
  24980. Scene.prototype.getTotalVertices = function () {
  24981. return this._totalVertices.current;
  24982. };
  24983. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24984. /**
  24985. * Gets the performance counter for total vertices
  24986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24987. */
  24988. get: function () {
  24989. return this._totalVertices;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. /**
  24995. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24996. * @returns the total number of active indices rendered per frame
  24997. */
  24998. Scene.prototype.getActiveIndices = function () {
  24999. return this._activeIndices.current;
  25000. };
  25001. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25002. /**
  25003. * Gets the performance counter for active indices
  25004. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25005. */
  25006. get: function () {
  25007. return this._activeIndices;
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. /**
  25013. * Gets the total number of active particles rendered per frame
  25014. * @returns the total number of active particles rendered per frame
  25015. */
  25016. Scene.prototype.getActiveParticles = function () {
  25017. return this._activeParticles.current;
  25018. };
  25019. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25020. /**
  25021. * Gets the performance counter for active particles
  25022. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25023. */
  25024. get: function () {
  25025. return this._activeParticles;
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. /**
  25031. * Gets the total number of active bones rendered per frame
  25032. * @returns the total number of active bones rendered per frame
  25033. */
  25034. Scene.prototype.getActiveBones = function () {
  25035. return this._activeBones.current;
  25036. };
  25037. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25038. /**
  25039. * Gets the performance counter for active bones
  25040. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25041. */
  25042. get: function () {
  25043. return this._activeBones;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. /** @hidden */
  25049. Scene.prototype.getInterFramePerfCounter = function () {
  25050. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25051. return 0;
  25052. };
  25053. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25054. /** @hidden */
  25055. get: function () {
  25056. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25057. return null;
  25058. },
  25059. enumerable: true,
  25060. configurable: true
  25061. });
  25062. /** @hidden */
  25063. Scene.prototype.getLastFrameDuration = function () {
  25064. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25065. return 0;
  25066. };
  25067. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25068. /** @hidden */
  25069. get: function () {
  25070. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25071. return null;
  25072. },
  25073. enumerable: true,
  25074. configurable: true
  25075. });
  25076. /** @hidden */
  25077. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25078. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25079. return 0;
  25080. };
  25081. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25082. /** @hidden */
  25083. get: function () {
  25084. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25085. return null;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. /**
  25091. * Gets the array of active meshes
  25092. * @returns an array of AbstractMesh
  25093. */
  25094. Scene.prototype.getActiveMeshes = function () {
  25095. return this._activeMeshes;
  25096. };
  25097. /** @hidden */
  25098. Scene.prototype.getRenderTargetsDuration = function () {
  25099. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. /** @hidden */
  25103. Scene.prototype.getRenderDuration = function () {
  25104. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25105. return 0;
  25106. };
  25107. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25108. /** @hidden */
  25109. get: function () {
  25110. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25111. return null;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. /** @hidden */
  25117. Scene.prototype.getParticlesDuration = function () {
  25118. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25119. return 0;
  25120. };
  25121. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25122. /** @hidden */
  25123. get: function () {
  25124. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25125. return null;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. /** @hidden */
  25131. Scene.prototype.getSpritesDuration = function () {
  25132. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25133. return 0;
  25134. };
  25135. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25136. /** @hidden */
  25137. get: function () {
  25138. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25139. return null;
  25140. },
  25141. enumerable: true,
  25142. configurable: true
  25143. });
  25144. /**
  25145. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25146. * @returns a number
  25147. */
  25148. Scene.prototype.getAnimationRatio = function () {
  25149. return this._animationRatio;
  25150. };
  25151. /**
  25152. * Gets an unique Id for the current frame
  25153. * @returns a number
  25154. */
  25155. Scene.prototype.getRenderId = function () {
  25156. return this._renderId;
  25157. };
  25158. /** Call this function if you want to manually increment the render Id*/
  25159. Scene.prototype.incrementRenderId = function () {
  25160. this._renderId++;
  25161. };
  25162. Scene.prototype._updatePointerPosition = function (evt) {
  25163. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25164. if (!canvasRect) {
  25165. return;
  25166. }
  25167. this._pointerX = evt.clientX - canvasRect.left;
  25168. this._pointerY = evt.clientY - canvasRect.top;
  25169. this._unTranslatedPointerX = this._pointerX;
  25170. this._unTranslatedPointerY = this._pointerY;
  25171. };
  25172. Scene.prototype._createUbo = function () {
  25173. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25174. this._sceneUbo.addUniform("viewProjection", 16);
  25175. this._sceneUbo.addUniform("view", 16);
  25176. };
  25177. Scene.prototype._createAlternateUbo = function () {
  25178. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25179. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25180. this._alternateSceneUbo.addUniform("view", 16);
  25181. };
  25182. // Pointers handling
  25183. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25184. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25185. if (result) {
  25186. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25187. }
  25188. return result;
  25189. };
  25190. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25191. if (pointerInfo.pickInfo) {
  25192. if (!pointerInfo.pickInfo.ray) {
  25193. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25194. }
  25195. }
  25196. };
  25197. /**
  25198. * Use this method to simulate a pointer move on a mesh
  25199. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25200. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25201. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25202. * @returns the current scene
  25203. */
  25204. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25205. var evt = new PointerEvent("pointermove", pointerEventInit);
  25206. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25207. return this;
  25208. }
  25209. return this._processPointerMove(pickResult, evt);
  25210. };
  25211. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25212. var canvas = this._engine.getRenderingCanvas();
  25213. if (!canvas) {
  25214. return this;
  25215. }
  25216. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25217. this.setPointerOverSprite(null);
  25218. this.setPointerOverMesh(pickResult.pickedMesh);
  25219. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25220. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25221. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25222. }
  25223. else {
  25224. canvas.style.cursor = this.hoverCursor;
  25225. }
  25226. }
  25227. else {
  25228. canvas.style.cursor = this.defaultCursor;
  25229. }
  25230. }
  25231. else {
  25232. this.setPointerOverMesh(null);
  25233. // Sprites
  25234. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25235. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25236. this.setPointerOverSprite(pickResult.pickedSprite);
  25237. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25238. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25239. }
  25240. else {
  25241. canvas.style.cursor = this.hoverCursor;
  25242. }
  25243. }
  25244. else {
  25245. this.setPointerOverSprite(null);
  25246. // Restore pointer
  25247. canvas.style.cursor = this.defaultCursor;
  25248. }
  25249. }
  25250. if (pickResult) {
  25251. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25252. if (this.onPointerMove) {
  25253. this.onPointerMove(evt, pickResult, type);
  25254. }
  25255. if (this.onPointerObservable.hasObservers()) {
  25256. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25257. this._setRayOnPointerInfo(pi);
  25258. this.onPointerObservable.notifyObservers(pi, type);
  25259. }
  25260. }
  25261. return this;
  25262. };
  25263. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25264. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25265. if (pickResult) {
  25266. pi.ray = pickResult.ray;
  25267. }
  25268. this.onPrePointerObservable.notifyObservers(pi, type);
  25269. if (pi.skipOnPointerObservable) {
  25270. return true;
  25271. }
  25272. else {
  25273. return false;
  25274. }
  25275. };
  25276. /**
  25277. * Use this method to simulate a pointer down on a mesh
  25278. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25279. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25280. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25281. * @returns the current scene
  25282. */
  25283. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25284. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25285. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25286. return this;
  25287. }
  25288. return this._processPointerDown(pickResult, evt);
  25289. };
  25290. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25291. var _this = this;
  25292. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25293. this._pickedDownMesh = pickResult.pickedMesh;
  25294. var actionManager = pickResult.pickedMesh.actionManager;
  25295. if (actionManager) {
  25296. if (actionManager.hasPickTriggers) {
  25297. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25298. switch (evt.button) {
  25299. case 0:
  25300. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25301. break;
  25302. case 1:
  25303. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25304. break;
  25305. case 2:
  25306. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25307. break;
  25308. }
  25309. }
  25310. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25311. window.setTimeout(function () {
  25312. 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);
  25313. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25314. if (_this._totalPointersPressed !== 0 &&
  25315. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25316. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25317. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25318. _this._startingPointerTime = 0;
  25319. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25320. }
  25321. }
  25322. }, Scene.LongPressDelay);
  25323. }
  25324. }
  25325. }
  25326. if (pickResult) {
  25327. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25328. if (this.onPointerDown) {
  25329. this.onPointerDown(evt, pickResult, type);
  25330. }
  25331. if (this.onPointerObservable.hasObservers()) {
  25332. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25333. this._setRayOnPointerInfo(pi);
  25334. this.onPointerObservable.notifyObservers(pi, type);
  25335. }
  25336. }
  25337. return this;
  25338. };
  25339. /**
  25340. * Use this method to simulate a pointer up on a mesh
  25341. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25342. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25343. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25344. * @returns the current scene
  25345. */
  25346. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25347. var evt = new PointerEvent("pointerup", pointerEventInit);
  25348. var clickInfo = new ClickInfo();
  25349. clickInfo.singleClick = true;
  25350. clickInfo.ignore = true;
  25351. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25352. return this;
  25353. }
  25354. return this._processPointerUp(pickResult, evt, clickInfo);
  25355. };
  25356. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25357. if (pickResult && pickResult && pickResult.pickedMesh) {
  25358. this._pickedUpMesh = pickResult.pickedMesh;
  25359. if (this._pickedDownMesh === this._pickedUpMesh) {
  25360. if (this.onPointerPick) {
  25361. this.onPointerPick(evt, pickResult);
  25362. }
  25363. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25364. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25365. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25366. this._setRayOnPointerInfo(pi);
  25367. this.onPointerObservable.notifyObservers(pi, type_1);
  25368. }
  25369. }
  25370. if (pickResult.pickedMesh.actionManager) {
  25371. if (clickInfo.ignore) {
  25372. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25373. }
  25374. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25376. }
  25377. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25379. }
  25380. }
  25381. }
  25382. if (this._pickedDownMesh &&
  25383. this._pickedDownMesh.actionManager &&
  25384. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25385. this._pickedDownMesh !== this._pickedUpMesh) {
  25386. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25387. }
  25388. var type = BABYLON.PointerEventTypes.POINTERUP;
  25389. if (this.onPointerObservable.hasObservers()) {
  25390. if (!clickInfo.ignore) {
  25391. if (!clickInfo.hasSwiped) {
  25392. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25393. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25394. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25395. this._setRayOnPointerInfo(pi);
  25396. this.onPointerObservable.notifyObservers(pi, type_2);
  25397. }
  25398. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25399. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25400. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25401. this._setRayOnPointerInfo(pi);
  25402. this.onPointerObservable.notifyObservers(pi, type_3);
  25403. }
  25404. }
  25405. }
  25406. else {
  25407. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25408. this._setRayOnPointerInfo(pi);
  25409. this.onPointerObservable.notifyObservers(pi, type);
  25410. }
  25411. }
  25412. if (this.onPointerUp) {
  25413. this.onPointerUp(evt, pickResult, type);
  25414. }
  25415. return this;
  25416. };
  25417. /**
  25418. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25419. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25420. * @returns true if the pointer was captured
  25421. */
  25422. Scene.prototype.isPointerCaptured = function (pointerId) {
  25423. if (pointerId === void 0) { pointerId = 0; }
  25424. return this._pointerCaptures[pointerId];
  25425. };
  25426. /**
  25427. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25428. * @param attachUp defines if you want to attach events to pointerup
  25429. * @param attachDown defines if you want to attach events to pointerdown
  25430. * @param attachMove defines if you want to attach events to pointermove
  25431. */
  25432. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25433. var _this = this;
  25434. if (attachUp === void 0) { attachUp = true; }
  25435. if (attachDown === void 0) { attachDown = true; }
  25436. if (attachMove === void 0) { attachMove = true; }
  25437. this._initActionManager = function (act, clickInfo) {
  25438. if (!_this._meshPickProceed) {
  25439. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25440. _this._currentPickResult = pickResult;
  25441. if (pickResult) {
  25442. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25443. }
  25444. _this._meshPickProceed = true;
  25445. }
  25446. return act;
  25447. };
  25448. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25449. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25450. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25451. btn !== _this._previousButtonPressed) {
  25452. _this._doubleClickOccured = false;
  25453. clickInfo.singleClick = true;
  25454. clickInfo.ignore = false;
  25455. cb(clickInfo, _this._currentPickResult);
  25456. }
  25457. };
  25458. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25459. var clickInfo = new ClickInfo();
  25460. _this._currentPickResult = null;
  25461. var act = null;
  25462. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25463. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25464. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25465. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25466. act = _this._initActionManager(act, clickInfo);
  25467. if (act)
  25468. checkPicking = act.hasPickTriggers;
  25469. }
  25470. if (checkPicking) {
  25471. var btn = evt.button;
  25472. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25473. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25474. if (!clickInfo.hasSwiped) {
  25475. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25476. if (!checkSingleClickImmediately) {
  25477. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25478. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25479. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25480. act = _this._initActionManager(act, clickInfo);
  25481. if (act)
  25482. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25483. }
  25484. }
  25485. if (checkSingleClickImmediately) {
  25486. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25487. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25488. btn !== _this._previousButtonPressed) {
  25489. clickInfo.singleClick = true;
  25490. cb(clickInfo, _this._currentPickResult);
  25491. }
  25492. }
  25493. // at least one double click is required to be check and exclusive double click is enabled
  25494. else {
  25495. // wait that no double click has been raised during the double click delay
  25496. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25497. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25498. }
  25499. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25500. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25501. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25502. act = _this._initActionManager(act, clickInfo);
  25503. if (act)
  25504. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25505. }
  25506. if (checkDoubleClick) {
  25507. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25508. if (btn === _this._previousButtonPressed &&
  25509. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25510. !_this._doubleClickOccured) {
  25511. // pointer has not moved for 2 clicks, it's a double click
  25512. if (!clickInfo.hasSwiped &&
  25513. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25514. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25515. _this._previousStartingPointerTime = 0;
  25516. _this._doubleClickOccured = true;
  25517. clickInfo.doubleClick = true;
  25518. clickInfo.ignore = false;
  25519. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25520. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25521. }
  25522. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25523. cb(clickInfo, _this._currentPickResult);
  25524. }
  25525. // if the two successive clicks are too far, it's just two simple clicks
  25526. else {
  25527. _this._doubleClickOccured = false;
  25528. _this._previousStartingPointerTime = _this._startingPointerTime;
  25529. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25530. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25531. _this._previousButtonPressed = btn;
  25532. if (Scene.ExclusiveDoubleClickMode) {
  25533. if (_this._previousDelayedSimpleClickTimeout) {
  25534. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25535. }
  25536. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25537. cb(clickInfo, _this._previousPickResult);
  25538. }
  25539. else {
  25540. cb(clickInfo, _this._currentPickResult);
  25541. }
  25542. }
  25543. }
  25544. // just the first click of the double has been raised
  25545. else {
  25546. _this._doubleClickOccured = false;
  25547. _this._previousStartingPointerTime = _this._startingPointerTime;
  25548. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25549. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25550. _this._previousButtonPressed = btn;
  25551. }
  25552. }
  25553. }
  25554. }
  25555. clickInfo.ignore = true;
  25556. cb(clickInfo, _this._currentPickResult);
  25557. };
  25558. this._spritePredicate = function (sprite) {
  25559. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25560. };
  25561. this._onPointerMove = function (evt) {
  25562. _this._updatePointerPosition(evt);
  25563. // PreObservable support
  25564. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25565. return;
  25566. }
  25567. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25568. return;
  25569. }
  25570. if (!_this.pointerMovePredicate) {
  25571. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25572. }
  25573. // Meshes
  25574. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25575. _this._processPointerMove(pickResult, evt);
  25576. };
  25577. this._onPointerDown = function (evt) {
  25578. _this._totalPointersPressed++;
  25579. _this._pickedDownMesh = null;
  25580. _this._meshPickProceed = false;
  25581. _this._updatePointerPosition(evt);
  25582. if (_this.preventDefaultOnPointerDown && canvas) {
  25583. evt.preventDefault();
  25584. canvas.focus();
  25585. }
  25586. // PreObservable support
  25587. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25588. return;
  25589. }
  25590. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25591. return;
  25592. }
  25593. _this._pointerCaptures[evt.pointerId] = true;
  25594. _this._startingPointerPosition.x = _this._pointerX;
  25595. _this._startingPointerPosition.y = _this._pointerY;
  25596. _this._startingPointerTime = Date.now();
  25597. if (!_this.pointerDownPredicate) {
  25598. _this.pointerDownPredicate = function (mesh) {
  25599. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25600. };
  25601. }
  25602. // Meshes
  25603. _this._pickedDownMesh = null;
  25604. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25605. _this._processPointerDown(pickResult, evt);
  25606. // Sprites
  25607. _this._pickedDownSprite = null;
  25608. if (_this.spriteManagers.length > 0) {
  25609. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25610. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25611. if (pickResult.pickedSprite.actionManager) {
  25612. _this._pickedDownSprite = pickResult.pickedSprite;
  25613. switch (evt.button) {
  25614. case 0:
  25615. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25616. break;
  25617. case 1:
  25618. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25619. break;
  25620. case 2:
  25621. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25622. break;
  25623. }
  25624. if (pickResult.pickedSprite.actionManager) {
  25625. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25626. }
  25627. }
  25628. }
  25629. }
  25630. };
  25631. this._onPointerUp = function (evt) {
  25632. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25633. return; // So we need to test it the pointer down was pressed before.
  25634. }
  25635. _this._totalPointersPressed--;
  25636. _this._pickedUpMesh = null;
  25637. _this._meshPickProceed = false;
  25638. _this._updatePointerPosition(evt);
  25639. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25640. // PreObservable support
  25641. if (_this.onPrePointerObservable.hasObservers()) {
  25642. if (!clickInfo.ignore) {
  25643. if (!clickInfo.hasSwiped) {
  25644. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25645. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25646. return;
  25647. }
  25648. }
  25649. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25650. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25651. return;
  25652. }
  25653. }
  25654. }
  25655. }
  25656. else {
  25657. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25658. return;
  25659. }
  25660. }
  25661. }
  25662. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25663. return;
  25664. }
  25665. _this._pointerCaptures[evt.pointerId] = false;
  25666. if (!_this.pointerUpPredicate) {
  25667. _this.pointerUpPredicate = function (mesh) {
  25668. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25669. };
  25670. }
  25671. // Meshes
  25672. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25673. _this._initActionManager(null, clickInfo);
  25674. }
  25675. if (!pickResult) {
  25676. pickResult = _this._currentPickResult;
  25677. }
  25678. _this._processPointerUp(pickResult, evt, clickInfo);
  25679. // Sprites
  25680. if (!clickInfo.ignore) {
  25681. if (_this.spriteManagers.length > 0) {
  25682. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25683. if (spritePickResult) {
  25684. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25685. if (spritePickResult.pickedSprite.actionManager) {
  25686. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25687. if (spritePickResult.pickedSprite.actionManager) {
  25688. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25689. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25690. }
  25691. }
  25692. }
  25693. }
  25694. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25695. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25696. }
  25697. }
  25698. }
  25699. }
  25700. _this._previousPickResult = _this._currentPickResult;
  25701. });
  25702. };
  25703. this._onKeyDown = function (evt) {
  25704. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25705. if (_this.onPreKeyboardObservable.hasObservers()) {
  25706. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25707. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25708. if (pi.skipOnPointerObservable) {
  25709. return;
  25710. }
  25711. }
  25712. if (_this.onKeyboardObservable.hasObservers()) {
  25713. var pi = new BABYLON.KeyboardInfo(type, evt);
  25714. _this.onKeyboardObservable.notifyObservers(pi, type);
  25715. }
  25716. if (_this.actionManager) {
  25717. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25718. }
  25719. };
  25720. this._onKeyUp = function (evt) {
  25721. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25722. if (_this.onPreKeyboardObservable.hasObservers()) {
  25723. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25724. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25725. if (pi.skipOnPointerObservable) {
  25726. return;
  25727. }
  25728. }
  25729. if (_this.onKeyboardObservable.hasObservers()) {
  25730. var pi = new BABYLON.KeyboardInfo(type, evt);
  25731. _this.onKeyboardObservable.notifyObservers(pi, type);
  25732. }
  25733. if (_this.actionManager) {
  25734. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25735. }
  25736. };
  25737. var engine = this.getEngine();
  25738. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25739. if (!canvas) {
  25740. return;
  25741. }
  25742. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25743. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25744. });
  25745. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25746. if (!canvas) {
  25747. return;
  25748. }
  25749. canvas.removeEventListener("keydown", _this._onKeyDown);
  25750. canvas.removeEventListener("keyup", _this._onKeyUp);
  25751. });
  25752. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25753. var canvas = this._engine.getRenderingCanvas();
  25754. if (!canvas) {
  25755. return;
  25756. }
  25757. if (attachMove) {
  25758. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25759. // Wheel
  25760. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25761. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25762. }
  25763. if (attachDown) {
  25764. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25765. }
  25766. if (attachUp) {
  25767. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25768. }
  25769. canvas.tabIndex = 1;
  25770. };
  25771. /** Detaches all event handlers*/
  25772. Scene.prototype.detachControl = function () {
  25773. var engine = this.getEngine();
  25774. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25775. var canvas = engine.getRenderingCanvas();
  25776. if (!canvas) {
  25777. return;
  25778. }
  25779. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25780. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25781. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25782. if (this._onCanvasBlurObserver) {
  25783. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25784. }
  25785. if (this._onCanvasFocusObserver) {
  25786. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25787. }
  25788. // Wheel
  25789. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25790. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25791. // Keyboard
  25792. canvas.removeEventListener("keydown", this._onKeyDown);
  25793. canvas.removeEventListener("keyup", this._onKeyUp);
  25794. // Observables
  25795. this.onKeyboardObservable.clear();
  25796. this.onPreKeyboardObservable.clear();
  25797. this.onPointerObservable.clear();
  25798. this.onPrePointerObservable.clear();
  25799. };
  25800. /**
  25801. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25802. * Delay loaded resources are not taking in account
  25803. * @return true if all required resources are ready
  25804. */
  25805. Scene.prototype.isReady = function () {
  25806. if (this._isDisposed) {
  25807. return false;
  25808. }
  25809. if (this._pendingData.length > 0) {
  25810. return false;
  25811. }
  25812. var index;
  25813. var engine = this.getEngine();
  25814. // Geometries
  25815. for (index = 0; index < this._geometries.length; index++) {
  25816. var geometry = this._geometries[index];
  25817. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25818. return false;
  25819. }
  25820. }
  25821. // Meshes
  25822. for (index = 0; index < this.meshes.length; index++) {
  25823. var mesh = this.meshes[index];
  25824. if (!mesh.isEnabled()) {
  25825. continue;
  25826. }
  25827. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25828. continue;
  25829. }
  25830. if (!mesh.isReady(true)) {
  25831. return false;
  25832. }
  25833. // Effect layers
  25834. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25835. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25836. var layer = _a[_i];
  25837. if (!layer.hasMesh(mesh)) {
  25838. continue;
  25839. }
  25840. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25841. var subMesh = _c[_b];
  25842. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25843. return false;
  25844. }
  25845. }
  25846. }
  25847. }
  25848. // Post-processes
  25849. if (this.activeCameras && this.activeCameras.length > 0) {
  25850. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25851. var camera = _e[_d];
  25852. if (!camera.isReady(true)) {
  25853. return false;
  25854. }
  25855. }
  25856. }
  25857. else if (this.activeCamera) {
  25858. if (!this.activeCamera.isReady(true)) {
  25859. return false;
  25860. }
  25861. }
  25862. // Particles
  25863. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25864. var particleSystem = _g[_f];
  25865. if (!particleSystem.isReady()) {
  25866. return false;
  25867. }
  25868. }
  25869. return true;
  25870. };
  25871. /** Resets all cached information relative to material (including effect and visibility) */
  25872. Scene.prototype.resetCachedMaterial = function () {
  25873. this._cachedMaterial = null;
  25874. this._cachedEffect = null;
  25875. this._cachedVisibility = null;
  25876. };
  25877. /**
  25878. * Registers a function to be called before every frame render
  25879. * @param func defines the function to register
  25880. */
  25881. Scene.prototype.registerBeforeRender = function (func) {
  25882. this.onBeforeRenderObservable.add(func);
  25883. };
  25884. /**
  25885. * Unregisters a function called before every frame render
  25886. * @param func defines the function to unregister
  25887. */
  25888. Scene.prototype.unregisterBeforeRender = function (func) {
  25889. this.onBeforeRenderObservable.removeCallback(func);
  25890. };
  25891. /**
  25892. * Registers a function to be called after every frame render
  25893. * @param func defines the function to register
  25894. */
  25895. Scene.prototype.registerAfterRender = function (func) {
  25896. this.onAfterRenderObservable.add(func);
  25897. };
  25898. /**
  25899. * Unregisters a function called after every frame render
  25900. * @param func defines the function to unregister
  25901. */
  25902. Scene.prototype.unregisterAfterRender = function (func) {
  25903. this.onAfterRenderObservable.removeCallback(func);
  25904. };
  25905. Scene.prototype._executeOnceBeforeRender = function (func) {
  25906. var _this = this;
  25907. var execFunc = function () {
  25908. func();
  25909. setTimeout(function () {
  25910. _this.unregisterBeforeRender(execFunc);
  25911. });
  25912. };
  25913. this.registerBeforeRender(execFunc);
  25914. };
  25915. /**
  25916. * The provided function will run before render once and will be disposed afterwards.
  25917. * A timeout delay can be provided so that the function will be executed in N ms.
  25918. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25919. * @param func The function to be executed.
  25920. * @param timeout optional delay in ms
  25921. */
  25922. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25923. var _this = this;
  25924. if (timeout !== undefined) {
  25925. setTimeout(function () {
  25926. _this._executeOnceBeforeRender(func);
  25927. }, timeout);
  25928. }
  25929. else {
  25930. this._executeOnceBeforeRender(func);
  25931. }
  25932. };
  25933. /** @hidden */
  25934. Scene.prototype._addPendingData = function (data) {
  25935. this._pendingData.push(data);
  25936. };
  25937. /** @hidden */
  25938. Scene.prototype._removePendingData = function (data) {
  25939. var wasLoading = this.isLoading;
  25940. var index = this._pendingData.indexOf(data);
  25941. if (index !== -1) {
  25942. this._pendingData.splice(index, 1);
  25943. }
  25944. if (wasLoading && !this.isLoading) {
  25945. this.onDataLoadedObservable.notifyObservers(this);
  25946. }
  25947. };
  25948. /**
  25949. * Returns the number of items waiting to be loaded
  25950. * @returns the number of items waiting to be loaded
  25951. */
  25952. Scene.prototype.getWaitingItemsCount = function () {
  25953. return this._pendingData.length;
  25954. };
  25955. Object.defineProperty(Scene.prototype, "isLoading", {
  25956. /**
  25957. * Returns a boolean indicating if the scene is still loading data
  25958. */
  25959. get: function () {
  25960. return this._pendingData.length > 0;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. /**
  25966. * Registers a function to be executed when the scene is ready
  25967. * @param {Function} func - the function to be executed
  25968. */
  25969. Scene.prototype.executeWhenReady = function (func) {
  25970. var _this = this;
  25971. this.onReadyObservable.add(func);
  25972. if (this._executeWhenReadyTimeoutId !== -1) {
  25973. return;
  25974. }
  25975. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25976. _this._checkIsReady();
  25977. }, 150);
  25978. };
  25979. /**
  25980. * Returns a promise that resolves when the scene is ready
  25981. * @returns A promise that resolves when the scene is ready
  25982. */
  25983. Scene.prototype.whenReadyAsync = function () {
  25984. var _this = this;
  25985. return new Promise(function (resolve) {
  25986. _this.executeWhenReady(function () {
  25987. resolve();
  25988. });
  25989. });
  25990. };
  25991. /** @hidden */
  25992. Scene.prototype._checkIsReady = function () {
  25993. var _this = this;
  25994. if (this.isReady()) {
  25995. this.onReadyObservable.notifyObservers(this);
  25996. this.onReadyObservable.clear();
  25997. this._executeWhenReadyTimeoutId = -1;
  25998. return;
  25999. }
  26000. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26001. _this._checkIsReady();
  26002. }, 150);
  26003. };
  26004. // Animations
  26005. /**
  26006. * Will start the animation sequence of a given target
  26007. * @param target defines the target
  26008. * @param from defines from which frame should animation start
  26009. * @param to defines until which frame should animation run.
  26010. * @param weight defines the weight to apply to the animation (1.0 by default)
  26011. * @param loop defines if the animation loops
  26012. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26013. * @param onAnimationEnd defines the function to be executed when the animation ends
  26014. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26015. * @returns the animatable object created for this animation
  26016. */
  26017. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26018. if (weight === void 0) { weight = 1.0; }
  26019. if (speedRatio === void 0) { speedRatio = 1.0; }
  26020. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26021. returnedAnimatable.weight = weight;
  26022. return returnedAnimatable;
  26023. };
  26024. /**
  26025. * Will start the animation sequence of a given target
  26026. * @param target defines the target
  26027. * @param from defines from which frame should animation start
  26028. * @param to defines until which frame should animation run.
  26029. * @param loop defines if the animation loops
  26030. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26031. * @param onAnimationEnd defines the function to be executed when the animation ends
  26032. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26033. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26034. * @returns the animatable object created for this animation
  26035. */
  26036. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26037. if (speedRatio === void 0) { speedRatio = 1.0; }
  26038. if (stopCurrent === void 0) { stopCurrent = true; }
  26039. if (from > to && speedRatio > 0) {
  26040. speedRatio *= -1;
  26041. }
  26042. if (stopCurrent) {
  26043. this.stopAnimation(target);
  26044. }
  26045. if (!animatable) {
  26046. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26047. }
  26048. // Local animations
  26049. if (target.animations) {
  26050. animatable.appendAnimations(target, target.animations);
  26051. }
  26052. // Children animations
  26053. if (target.getAnimatables) {
  26054. var animatables = target.getAnimatables();
  26055. for (var index = 0; index < animatables.length; index++) {
  26056. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26057. }
  26058. }
  26059. animatable.reset();
  26060. return animatable;
  26061. };
  26062. /**
  26063. * Begin a new animation on a given node
  26064. * @param target defines the target where the animation will take place
  26065. * @param animations defines the list of animations to start
  26066. * @param from defines the initial value
  26067. * @param to defines the final value
  26068. * @param loop defines if you want animation to loop (off by default)
  26069. * @param speedRatio defines the speed ratio to apply to all animations
  26070. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26071. * @returns the list of created animatables
  26072. */
  26073. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26074. if (speedRatio === undefined) {
  26075. speedRatio = 1.0;
  26076. }
  26077. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26078. return animatable;
  26079. };
  26080. /**
  26081. * Begin a new animation on a given node and its hierarchy
  26082. * @param target defines the root node where the animation will take place
  26083. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  26084. * @param animations defines the list of animations to start
  26085. * @param from defines the initial value
  26086. * @param to defines the final value
  26087. * @param loop defines if you want animation to loop (off by default)
  26088. * @param speedRatio defines the speed ratio to apply to all animations
  26089. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26090. * @returns the list of animatables created for all nodes
  26091. */
  26092. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26093. var children = target.getDescendants(directDescendantsOnly);
  26094. var result = [];
  26095. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26096. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26097. var child = children_1[_i];
  26098. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26099. }
  26100. return result;
  26101. };
  26102. /**
  26103. * Gets the animatable associated with a specific target
  26104. * @param target defines the target of the animatable
  26105. * @returns the required animatable if found
  26106. */
  26107. Scene.prototype.getAnimatableByTarget = function (target) {
  26108. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26109. if (this._activeAnimatables[index].target === target) {
  26110. return this._activeAnimatables[index];
  26111. }
  26112. }
  26113. return null;
  26114. };
  26115. /**
  26116. * Gets all animatables associated with a given target
  26117. * @param target defines the target to look animatables for
  26118. * @returns an array of Animatables
  26119. */
  26120. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26121. var result = [];
  26122. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26123. if (this._activeAnimatables[index].target === target) {
  26124. result.push(this._activeAnimatables[index]);
  26125. }
  26126. }
  26127. return result;
  26128. };
  26129. Object.defineProperty(Scene.prototype, "animatables", {
  26130. /**
  26131. * Gets all animatable attached to the scene
  26132. */
  26133. get: function () {
  26134. return this._activeAnimatables;
  26135. },
  26136. enumerable: true,
  26137. configurable: true
  26138. });
  26139. /**
  26140. * Will stop the animation of the given target
  26141. * @param target - the target
  26142. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26143. */
  26144. Scene.prototype.stopAnimation = function (target, animationName) {
  26145. var animatables = this.getAllAnimatablesByTarget(target);
  26146. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26147. var animatable = animatables_1[_i];
  26148. animatable.stop(animationName);
  26149. }
  26150. };
  26151. /**
  26152. * Stops and removes all animations that have been applied to the scene
  26153. */
  26154. Scene.prototype.stopAllAnimations = function () {
  26155. if (this._activeAnimatables) {
  26156. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26157. this._activeAnimatables[i].stop();
  26158. }
  26159. this._activeAnimatables = [];
  26160. }
  26161. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26162. var group = _a[_i];
  26163. group.stop();
  26164. }
  26165. };
  26166. Scene.prototype._animate = function () {
  26167. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26168. return;
  26169. }
  26170. // Getting time
  26171. var now = BABYLON.Tools.Now;
  26172. if (!this._animationTimeLast) {
  26173. if (this._pendingData.length > 0) {
  26174. return;
  26175. }
  26176. this._animationTimeLast = now;
  26177. }
  26178. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26179. this._animationTime += deltaTime;
  26180. this._animationTimeLast = now;
  26181. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26182. this._activeAnimatables[index]._animate(this._animationTime);
  26183. }
  26184. // Late animation bindings
  26185. this._processLateAnimationBindings();
  26186. };
  26187. /** @hidden */
  26188. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26189. var target = runtimeAnimation.target;
  26190. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26191. if (!target._lateAnimationHolders) {
  26192. target._lateAnimationHolders = {};
  26193. }
  26194. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26195. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26196. totalWeight: 0,
  26197. animations: [],
  26198. originalValue: originalValue
  26199. };
  26200. }
  26201. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26202. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26203. };
  26204. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26205. var normalizer = 1.0;
  26206. var finalPosition = BABYLON.Tmp.Vector3[0];
  26207. var finalScaling = BABYLON.Tmp.Vector3[1];
  26208. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26209. var startIndex = 0;
  26210. var originalAnimation = holder.animations[0];
  26211. var originalValue = holder.originalValue;
  26212. var scale = 1;
  26213. if (holder.totalWeight < 1.0) {
  26214. // We need to mix the original value in
  26215. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26216. scale = 1.0 - holder.totalWeight;
  26217. }
  26218. else {
  26219. startIndex = 1;
  26220. // We need to normalize the weights
  26221. normalizer = holder.totalWeight;
  26222. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26223. scale = originalAnimation.weight / normalizer;
  26224. if (scale == 1) {
  26225. return originalAnimation.currentValue;
  26226. }
  26227. }
  26228. finalScaling.scaleInPlace(scale);
  26229. finalPosition.scaleInPlace(scale);
  26230. finalQuaternion.scaleInPlace(scale);
  26231. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26232. var runtimeAnimation = holder.animations[animIndex];
  26233. var scale = runtimeAnimation.weight / normalizer;
  26234. var currentPosition = BABYLON.Tmp.Vector3[2];
  26235. var currentScaling = BABYLON.Tmp.Vector3[3];
  26236. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26237. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26238. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26239. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26240. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26241. }
  26242. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26243. return originalAnimation._workValue;
  26244. };
  26245. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26246. var originalAnimation = holder.animations[0];
  26247. var originalValue = holder.originalValue;
  26248. if (holder.animations.length === 1) {
  26249. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26250. }
  26251. var normalizer = 1.0;
  26252. var quaternions;
  26253. var weights;
  26254. if (holder.totalWeight < 1.0) {
  26255. var scale = 1.0 - holder.totalWeight;
  26256. quaternions = [];
  26257. weights = [];
  26258. quaternions.push(originalValue);
  26259. weights.push(scale);
  26260. }
  26261. else {
  26262. if (holder.animations.length === 2) { // Slerp as soon as we can
  26263. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26264. }
  26265. quaternions = [];
  26266. weights = [];
  26267. normalizer = holder.totalWeight;
  26268. }
  26269. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26270. var runtimeAnimation = holder.animations[animIndex];
  26271. quaternions.push(runtimeAnimation.currentValue);
  26272. weights.push(runtimeAnimation.weight / normalizer);
  26273. }
  26274. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26275. var cumulativeAmount = 0;
  26276. var cumulativeQuaternion = null;
  26277. for (var index = 0; index < quaternions.length;) {
  26278. if (!cumulativeQuaternion) {
  26279. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26280. cumulativeAmount = weights[index] + weights[index + 1];
  26281. index += 2;
  26282. continue;
  26283. }
  26284. cumulativeAmount += weights[index];
  26285. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26286. index++;
  26287. }
  26288. return cumulativeQuaternion;
  26289. };
  26290. Scene.prototype._processLateAnimationBindings = function () {
  26291. if (!this._registeredForLateAnimationBindings.length) {
  26292. return;
  26293. }
  26294. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26295. var target = this._registeredForLateAnimationBindings.data[index];
  26296. for (var path in target._lateAnimationHolders) {
  26297. var holder = target._lateAnimationHolders[path];
  26298. var originalAnimation = holder.animations[0];
  26299. var originalValue = holder.originalValue;
  26300. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26301. var finalValue = void 0;
  26302. if (matrixDecomposeMode) {
  26303. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26304. }
  26305. else {
  26306. var quaternionMode = originalValue.w !== undefined;
  26307. if (quaternionMode) {
  26308. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26309. }
  26310. else {
  26311. var startIndex = 0;
  26312. var normalizer = 1.0;
  26313. if (holder.totalWeight < 1.0) {
  26314. // We need to mix the original value in
  26315. if (originalValue.scale) {
  26316. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26317. }
  26318. else {
  26319. finalValue = originalValue * (1.0 - holder.totalWeight);
  26320. }
  26321. }
  26322. else {
  26323. // We need to normalize the weights
  26324. normalizer = holder.totalWeight;
  26325. var scale_1 = originalAnimation.weight / normalizer;
  26326. if (scale_1 !== 1) {
  26327. if (originalAnimation.currentValue.scale) {
  26328. finalValue = originalAnimation.currentValue.scale(scale_1);
  26329. }
  26330. else {
  26331. finalValue = originalAnimation.currentValue * scale_1;
  26332. }
  26333. }
  26334. else {
  26335. finalValue = originalAnimation.currentValue;
  26336. }
  26337. startIndex = 1;
  26338. }
  26339. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26340. var runtimeAnimation = holder.animations[animIndex];
  26341. var scale = runtimeAnimation.weight / normalizer;
  26342. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26343. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26344. }
  26345. else {
  26346. finalValue += runtimeAnimation.currentValue * scale;
  26347. }
  26348. }
  26349. }
  26350. }
  26351. target[path] = finalValue;
  26352. }
  26353. target._lateAnimationHolders = {};
  26354. }
  26355. this._registeredForLateAnimationBindings.reset();
  26356. };
  26357. // Matrix
  26358. /** @hidden */
  26359. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26360. this._useAlternateCameraConfiguration = active;
  26361. };
  26362. /**
  26363. * Gets the current view matrix
  26364. * @returns a Matrix
  26365. */
  26366. Scene.prototype.getViewMatrix = function () {
  26367. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26368. };
  26369. /**
  26370. * Gets the current projection matrix
  26371. * @returns a Matrix
  26372. */
  26373. Scene.prototype.getProjectionMatrix = function () {
  26374. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26375. };
  26376. /**
  26377. * Gets the current transform matrix
  26378. * @returns a Matrix made of View * Projection
  26379. */
  26380. Scene.prototype.getTransformMatrix = function () {
  26381. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26382. };
  26383. /**
  26384. * Sets the current transform matrix
  26385. * @param view defines the View matrix to use
  26386. * @param projection defines the Projection matrix to use
  26387. */
  26388. Scene.prototype.setTransformMatrix = function (view, projection) {
  26389. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26390. return;
  26391. }
  26392. this._viewUpdateFlag = view.updateFlag;
  26393. this._projectionUpdateFlag = projection.updateFlag;
  26394. this._viewMatrix = view;
  26395. this._projectionMatrix = projection;
  26396. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26397. // Update frustum
  26398. if (!this._frustumPlanes) {
  26399. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26400. }
  26401. else {
  26402. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26403. }
  26404. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26405. var otherCamera = this.activeCamera._alternateCamera;
  26406. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26407. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26408. }
  26409. if (this._sceneUbo.useUbo) {
  26410. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26411. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26412. this._sceneUbo.update();
  26413. }
  26414. };
  26415. /** @hidden */
  26416. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26417. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26418. return;
  26419. }
  26420. this._alternateViewUpdateFlag = view.updateFlag;
  26421. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26422. this._alternateViewMatrix = view;
  26423. this._alternateProjectionMatrix = projection;
  26424. if (!this._alternateTransformMatrix) {
  26425. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26426. }
  26427. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26428. if (!this._alternateSceneUbo) {
  26429. this._createAlternateUbo();
  26430. }
  26431. if (this._alternateSceneUbo.useUbo) {
  26432. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26433. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26434. this._alternateSceneUbo.update();
  26435. }
  26436. };
  26437. /**
  26438. * Gets the uniform buffer used to store scene data
  26439. * @returns a UniformBuffer
  26440. */
  26441. Scene.prototype.getSceneUniformBuffer = function () {
  26442. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26443. };
  26444. /**
  26445. * Gets an unique (relatively to the current scene) Id
  26446. * @returns an unique number for the scene
  26447. */
  26448. Scene.prototype.getUniqueId = function () {
  26449. var result = Scene._uniqueIdCounter;
  26450. Scene._uniqueIdCounter++;
  26451. return result;
  26452. };
  26453. /**
  26454. * Add a mesh to the list of scene's meshes
  26455. * @param newMesh defines the mesh to add
  26456. * @param recursive if all child meshes should also be added to the scene
  26457. */
  26458. Scene.prototype.addMesh = function (newMesh, recursive) {
  26459. var _this = this;
  26460. if (recursive === void 0) { recursive = false; }
  26461. this.meshes.push(newMesh);
  26462. //notify the collision coordinator
  26463. if (this.collisionCoordinator) {
  26464. this.collisionCoordinator.onMeshAdded(newMesh);
  26465. }
  26466. newMesh._resyncLightSources();
  26467. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26468. if (recursive) {
  26469. newMesh.getChildMeshes().forEach(function (m) {
  26470. _this.addMesh(m);
  26471. });
  26472. }
  26473. };
  26474. /**
  26475. * Remove a mesh for the list of scene's meshes
  26476. * @param toRemove defines the mesh to remove
  26477. * @param recursive if all child meshes should also be removed from the scene
  26478. * @returns the index where the mesh was in the mesh list
  26479. */
  26480. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26481. var _this = this;
  26482. if (recursive === void 0) { recursive = false; }
  26483. var index = this.meshes.indexOf(toRemove);
  26484. if (index !== -1) {
  26485. // Remove from the scene if mesh found
  26486. this.meshes.splice(index, 1);
  26487. }
  26488. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26489. if (recursive) {
  26490. toRemove.getChildMeshes().forEach(function (m) {
  26491. _this.removeMesh(m);
  26492. });
  26493. }
  26494. return index;
  26495. };
  26496. /**
  26497. * Add a transform node to the list of scene's transform nodes
  26498. * @param newTransformNode defines the transform node to add
  26499. */
  26500. Scene.prototype.addTransformNode = function (newTransformNode) {
  26501. this.transformNodes.push(newTransformNode);
  26502. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26503. };
  26504. /**
  26505. * Remove a transform node for the list of scene's transform nodes
  26506. * @param toRemove defines the transform node to remove
  26507. * @returns the index where the transform node was in the transform node list
  26508. */
  26509. Scene.prototype.removeTransformNode = function (toRemove) {
  26510. var index = this.transformNodes.indexOf(toRemove);
  26511. if (index !== -1) {
  26512. // Remove from the scene if found
  26513. this.transformNodes.splice(index, 1);
  26514. }
  26515. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26516. return index;
  26517. };
  26518. /**
  26519. * Remove a skeleton for the list of scene's skeletons
  26520. * @param toRemove defines the skeleton to remove
  26521. * @returns the index where the skeleton was in the skeleton list
  26522. */
  26523. Scene.prototype.removeSkeleton = function (toRemove) {
  26524. var index = this.skeletons.indexOf(toRemove);
  26525. if (index !== -1) {
  26526. // Remove from the scene if found
  26527. this.skeletons.splice(index, 1);
  26528. }
  26529. return index;
  26530. };
  26531. /**
  26532. * Remove a morph target for the list of scene's morph targets
  26533. * @param toRemove defines the morph target to remove
  26534. * @returns the index where the morph target was in the morph target list
  26535. */
  26536. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26537. var index = this.morphTargetManagers.indexOf(toRemove);
  26538. if (index !== -1) {
  26539. // Remove from the scene if found
  26540. this.morphTargetManagers.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Remove a light for the list of scene's lights
  26546. * @param toRemove defines the light to remove
  26547. * @returns the index where the light was in the light list
  26548. */
  26549. Scene.prototype.removeLight = function (toRemove) {
  26550. var index = this.lights.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. // Remove from meshes
  26553. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26554. var mesh = _a[_i];
  26555. mesh._removeLightSource(toRemove);
  26556. }
  26557. // Remove from the scene if mesh found
  26558. this.lights.splice(index, 1);
  26559. this.sortLightsByPriority();
  26560. }
  26561. this.onLightRemovedObservable.notifyObservers(toRemove);
  26562. return index;
  26563. };
  26564. /**
  26565. * Remove a camera for the list of scene's cameras
  26566. * @param toRemove defines the camera to remove
  26567. * @returns the index where the camera was in the camera list
  26568. */
  26569. Scene.prototype.removeCamera = function (toRemove) {
  26570. var index = this.cameras.indexOf(toRemove);
  26571. if (index !== -1) {
  26572. // Remove from the scene if mesh found
  26573. this.cameras.splice(index, 1);
  26574. }
  26575. // Remove from activeCameras
  26576. var index2 = this.activeCameras.indexOf(toRemove);
  26577. if (index2 !== -1) {
  26578. // Remove from the scene if mesh found
  26579. this.activeCameras.splice(index2, 1);
  26580. }
  26581. // Reset the activeCamera
  26582. if (this.activeCamera === toRemove) {
  26583. if (this.cameras.length > 0) {
  26584. this.activeCamera = this.cameras[0];
  26585. }
  26586. else {
  26587. this.activeCamera = null;
  26588. }
  26589. }
  26590. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26591. return index;
  26592. };
  26593. /**
  26594. * Remove a particle system for the list of scene's particle systems
  26595. * @param toRemove defines the particle system to remove
  26596. * @returns the index where the particle system was in the particle system list
  26597. */
  26598. Scene.prototype.removeParticleSystem = function (toRemove) {
  26599. var index = this.particleSystems.indexOf(toRemove);
  26600. if (index !== -1) {
  26601. this.particleSystems.splice(index, 1);
  26602. }
  26603. return index;
  26604. };
  26605. /**
  26606. * Remove a animation for the list of scene's animations
  26607. * @param toRemove defines the animation to remove
  26608. * @returns the index where the animation was in the animation list
  26609. */
  26610. Scene.prototype.removeAnimation = function (toRemove) {
  26611. var index = this.animations.indexOf(toRemove);
  26612. if (index !== -1) {
  26613. this.animations.splice(index, 1);
  26614. }
  26615. return index;
  26616. };
  26617. /**
  26618. * Removes the given animation group from this scene.
  26619. * @param toRemove The animation group to remove
  26620. * @returns The index of the removed animation group
  26621. */
  26622. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26623. var index = this.animationGroups.indexOf(toRemove);
  26624. if (index !== -1) {
  26625. this.animationGroups.splice(index, 1);
  26626. }
  26627. return index;
  26628. };
  26629. /**
  26630. * Removes the given multi-material from this scene.
  26631. * @param toRemove The multi-material to remove
  26632. * @returns The index of the removed multi-material
  26633. */
  26634. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26635. var index = this.multiMaterials.indexOf(toRemove);
  26636. if (index !== -1) {
  26637. this.multiMaterials.splice(index, 1);
  26638. }
  26639. return index;
  26640. };
  26641. /**
  26642. * Removes the given material from this scene.
  26643. * @param toRemove The material to remove
  26644. * @returns The index of the removed material
  26645. */
  26646. Scene.prototype.removeMaterial = function (toRemove) {
  26647. var index = this.materials.indexOf(toRemove);
  26648. if (index !== -1) {
  26649. this.materials.splice(index, 1);
  26650. }
  26651. return index;
  26652. };
  26653. /**
  26654. * Removes the given lens flare system from this scene.
  26655. * @param toRemove The lens flare system to remove
  26656. * @returns The index of the removed lens flare system
  26657. */
  26658. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26659. var index = this.lensFlareSystems.indexOf(toRemove);
  26660. if (index !== -1) {
  26661. this.lensFlareSystems.splice(index, 1);
  26662. }
  26663. return index;
  26664. };
  26665. /**
  26666. * Removes the given action manager from this scene.
  26667. * @param toRemove The action manager to remove
  26668. * @returns The index of the removed action manager
  26669. */
  26670. Scene.prototype.removeActionManager = function (toRemove) {
  26671. var index = this._actionManagers.indexOf(toRemove);
  26672. if (index !== -1) {
  26673. this._actionManagers.splice(index, 1);
  26674. }
  26675. return index;
  26676. };
  26677. /**
  26678. * Removes the given effect layer from this scene.
  26679. * @param toRemove defines the effect layer to remove
  26680. * @returns the index of the removed effect layer
  26681. */
  26682. Scene.prototype.removeEffectLayer = function (toRemove) {
  26683. var index = this.effectLayers.indexOf(toRemove);
  26684. if (index !== -1) {
  26685. this.effectLayers.splice(index, 1);
  26686. }
  26687. return index;
  26688. };
  26689. /**
  26690. * Removes the given texture from this scene.
  26691. * @param toRemove The texture to remove
  26692. * @returns The index of the removed texture
  26693. */
  26694. Scene.prototype.removeTexture = function (toRemove) {
  26695. var index = this.textures.indexOf(toRemove);
  26696. if (index !== -1) {
  26697. this.textures.splice(index, 1);
  26698. }
  26699. return index;
  26700. };
  26701. /**
  26702. * Adds the given light to this scene
  26703. * @param newLight The light to add
  26704. */
  26705. Scene.prototype.addLight = function (newLight) {
  26706. this.lights.push(newLight);
  26707. this.sortLightsByPriority();
  26708. // Add light to all meshes (To support if the light is removed and then readded)
  26709. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26710. var mesh = _a[_i];
  26711. if (mesh._lightSources.indexOf(newLight) === -1) {
  26712. mesh._lightSources.push(newLight);
  26713. mesh._resyncLightSources();
  26714. }
  26715. }
  26716. this.onNewLightAddedObservable.notifyObservers(newLight);
  26717. };
  26718. /**
  26719. * Sorts the list list based on light priorities
  26720. */
  26721. Scene.prototype.sortLightsByPriority = function () {
  26722. if (this.requireLightSorting) {
  26723. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26724. }
  26725. };
  26726. /**
  26727. * Adds the given camera to this scene
  26728. * @param newCamera The camera to add
  26729. */
  26730. Scene.prototype.addCamera = function (newCamera) {
  26731. this.cameras.push(newCamera);
  26732. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26733. };
  26734. /**
  26735. * Adds the given skeleton to this scene
  26736. * @param newSkeleton The skeleton to add
  26737. */
  26738. Scene.prototype.addSkeleton = function (newSkeleton) {
  26739. this.skeletons.push(newSkeleton);
  26740. };
  26741. /**
  26742. * Adds the given particle system to this scene
  26743. * @param newParticleSystem The particle system to add
  26744. */
  26745. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26746. this.particleSystems.push(newParticleSystem);
  26747. };
  26748. /**
  26749. * Adds the given animation to this scene
  26750. * @param newAnimation The animation to add
  26751. */
  26752. Scene.prototype.addAnimation = function (newAnimation) {
  26753. this.animations.push(newAnimation);
  26754. };
  26755. /**
  26756. * Adds the given animation group to this scene.
  26757. * @param newAnimationGroup The animation group to add
  26758. */
  26759. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26760. this.animationGroups.push(newAnimationGroup);
  26761. };
  26762. /**
  26763. * Adds the given multi-material to this scene
  26764. * @param newMultiMaterial The multi-material to add
  26765. */
  26766. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26767. this.multiMaterials.push(newMultiMaterial);
  26768. };
  26769. /**
  26770. * Adds the given material to this scene
  26771. * @param newMaterial The material to add
  26772. */
  26773. Scene.prototype.addMaterial = function (newMaterial) {
  26774. this.materials.push(newMaterial);
  26775. };
  26776. /**
  26777. * Adds the given morph target to this scene
  26778. * @param newMorphTargetManager The morph target to add
  26779. */
  26780. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26781. this.morphTargetManagers.push(newMorphTargetManager);
  26782. };
  26783. /**
  26784. * Adds the given geometry to this scene
  26785. * @param newGeometry The geometry to add
  26786. */
  26787. Scene.prototype.addGeometry = function (newGeometry) {
  26788. this._geometries.push(newGeometry);
  26789. };
  26790. /**
  26791. * Adds the given lens flare system to this scene
  26792. * @param newLensFlareSystem The lens flare system to add
  26793. */
  26794. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26795. this.lensFlareSystems.push(newLensFlareSystem);
  26796. };
  26797. /**
  26798. * Adds the given effect layer to this scene
  26799. * @param newEffectLayer defines the effect layer to add
  26800. */
  26801. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26802. this.effectLayers.push(newEffectLayer);
  26803. };
  26804. /**
  26805. * Adds the given action manager to this scene
  26806. * @param newActionManager The action manager to add
  26807. */
  26808. Scene.prototype.addActionManager = function (newActionManager) {
  26809. this._actionManagers.push(newActionManager);
  26810. };
  26811. /**
  26812. * Adds the given texture to this scene.
  26813. * @param newTexture The texture to add
  26814. */
  26815. Scene.prototype.addTexture = function (newTexture) {
  26816. this.textures.push(newTexture);
  26817. };
  26818. /**
  26819. * Switch active camera
  26820. * @param newCamera defines the new active camera
  26821. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26822. */
  26823. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26824. if (attachControl === void 0) { attachControl = true; }
  26825. var canvas = this._engine.getRenderingCanvas();
  26826. if (!canvas) {
  26827. return;
  26828. }
  26829. if (this.activeCamera) {
  26830. this.activeCamera.detachControl(canvas);
  26831. }
  26832. this.activeCamera = newCamera;
  26833. if (attachControl) {
  26834. newCamera.attachControl(canvas);
  26835. }
  26836. };
  26837. /**
  26838. * sets the active camera of the scene using its ID
  26839. * @param id defines the camera's ID
  26840. * @return the new active camera or null if none found.
  26841. */
  26842. Scene.prototype.setActiveCameraByID = function (id) {
  26843. var camera = this.getCameraByID(id);
  26844. if (camera) {
  26845. this.activeCamera = camera;
  26846. return camera;
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * sets the active camera of the scene using its name
  26852. * @param name defines the camera's name
  26853. * @returns the new active camera or null if none found.
  26854. */
  26855. Scene.prototype.setActiveCameraByName = function (name) {
  26856. var camera = this.getCameraByName(name);
  26857. if (camera) {
  26858. this.activeCamera = camera;
  26859. return camera;
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * get an animation group using its name
  26865. * @param name defines the material's name
  26866. * @return the animation group or null if none found.
  26867. */
  26868. Scene.prototype.getAnimationGroupByName = function (name) {
  26869. for (var index = 0; index < this.animationGroups.length; index++) {
  26870. if (this.animationGroups[index].name === name) {
  26871. return this.animationGroups[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * get a material using its id
  26878. * @param id defines the material's ID
  26879. * @return the material or null if none found.
  26880. */
  26881. Scene.prototype.getMaterialByID = function (id) {
  26882. for (var index = 0; index < this.materials.length; index++) {
  26883. if (this.materials[index].id === id) {
  26884. return this.materials[index];
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a material using its name
  26891. * @param name defines the material's name
  26892. * @return the material or null if none found.
  26893. */
  26894. Scene.prototype.getMaterialByName = function (name) {
  26895. for (var index = 0; index < this.materials.length; index++) {
  26896. if (this.materials[index].name === name) {
  26897. return this.materials[index];
  26898. }
  26899. }
  26900. return null;
  26901. };
  26902. /**
  26903. * Gets a lens flare system using its name
  26904. * @param name defines the name to look for
  26905. * @returns the lens flare system or null if not found
  26906. */
  26907. Scene.prototype.getLensFlareSystemByName = function (name) {
  26908. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26909. if (this.lensFlareSystems[index].name === name) {
  26910. return this.lensFlareSystems[index];
  26911. }
  26912. }
  26913. return null;
  26914. };
  26915. /**
  26916. * Gets a lens flare system using its id
  26917. * @param id defines the id to look for
  26918. * @returns the lens flare system or null if not found
  26919. */
  26920. Scene.prototype.getLensFlareSystemByID = function (id) {
  26921. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26922. if (this.lensFlareSystems[index].id === id) {
  26923. return this.lensFlareSystems[index];
  26924. }
  26925. }
  26926. return null;
  26927. };
  26928. /**
  26929. * Gets a camera using its id
  26930. * @param id defines the id to look for
  26931. * @returns the camera or null if not found
  26932. */
  26933. Scene.prototype.getCameraByID = function (id) {
  26934. for (var index = 0; index < this.cameras.length; index++) {
  26935. if (this.cameras[index].id === id) {
  26936. return this.cameras[index];
  26937. }
  26938. }
  26939. return null;
  26940. };
  26941. /**
  26942. * Gets a camera using its unique id
  26943. * @param uniqueId defines the unique id to look for
  26944. * @returns the camera or null if not found
  26945. */
  26946. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26947. for (var index = 0; index < this.cameras.length; index++) {
  26948. if (this.cameras[index].uniqueId === uniqueId) {
  26949. return this.cameras[index];
  26950. }
  26951. }
  26952. return null;
  26953. };
  26954. /**
  26955. * Gets a camera using its name
  26956. * @param name defines the camera's name
  26957. * @return the camera or null if none found.
  26958. */
  26959. Scene.prototype.getCameraByName = function (name) {
  26960. for (var index = 0; index < this.cameras.length; index++) {
  26961. if (this.cameras[index].name === name) {
  26962. return this.cameras[index];
  26963. }
  26964. }
  26965. return null;
  26966. };
  26967. /**
  26968. * Gets a bone using its id
  26969. * @param id defines the bone's id
  26970. * @return the bone or null if not found
  26971. */
  26972. Scene.prototype.getBoneByID = function (id) {
  26973. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26974. var skeleton = this.skeletons[skeletonIndex];
  26975. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26976. if (skeleton.bones[boneIndex].id === id) {
  26977. return skeleton.bones[boneIndex];
  26978. }
  26979. }
  26980. }
  26981. return null;
  26982. };
  26983. /**
  26984. * Gets a bone using its id
  26985. * @param name defines the bone's name
  26986. * @return the bone or null if not found
  26987. */
  26988. Scene.prototype.getBoneByName = function (name) {
  26989. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26990. var skeleton = this.skeletons[skeletonIndex];
  26991. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26992. if (skeleton.bones[boneIndex].name === name) {
  26993. return skeleton.bones[boneIndex];
  26994. }
  26995. }
  26996. }
  26997. return null;
  26998. };
  26999. /**
  27000. * Gets a light node using its name
  27001. * @param name defines the the light's name
  27002. * @return the light or null if none found.
  27003. */
  27004. Scene.prototype.getLightByName = function (name) {
  27005. for (var index = 0; index < this.lights.length; index++) {
  27006. if (this.lights[index].name === name) {
  27007. return this.lights[index];
  27008. }
  27009. }
  27010. return null;
  27011. };
  27012. /**
  27013. * Gets a light node using its id
  27014. * @param id defines the light's id
  27015. * @return the light or null if none found.
  27016. */
  27017. Scene.prototype.getLightByID = function (id) {
  27018. for (var index = 0; index < this.lights.length; index++) {
  27019. if (this.lights[index].id === id) {
  27020. return this.lights[index];
  27021. }
  27022. }
  27023. return null;
  27024. };
  27025. /**
  27026. * Gets a light node using its scene-generated unique ID
  27027. * @param uniqueId defines the light's unique id
  27028. * @return the light or null if none found.
  27029. */
  27030. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27031. for (var index = 0; index < this.lights.length; index++) {
  27032. if (this.lights[index].uniqueId === uniqueId) {
  27033. return this.lights[index];
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. /**
  27039. * Gets a particle system by id
  27040. * @param id defines the particle system id
  27041. * @return the corresponding system or null if none found
  27042. */
  27043. Scene.prototype.getParticleSystemByID = function (id) {
  27044. for (var index = 0; index < this.particleSystems.length; index++) {
  27045. if (this.particleSystems[index].id === id) {
  27046. return this.particleSystems[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a geometry using its ID
  27053. * @param id defines the geometry's id
  27054. * @return the geometry or null if none found.
  27055. */
  27056. Scene.prototype.getGeometryByID = function (id) {
  27057. for (var index = 0; index < this._geometries.length; index++) {
  27058. if (this._geometries[index].id === id) {
  27059. return this._geometries[index];
  27060. }
  27061. }
  27062. return null;
  27063. };
  27064. /**
  27065. * Add a new geometry to this scene
  27066. * @param geometry defines the geometry to be added to the scene.
  27067. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27068. * @return a boolean defining if the geometry was added or not
  27069. */
  27070. Scene.prototype.pushGeometry = function (geometry, force) {
  27071. if (!force && this.getGeometryByID(geometry.id)) {
  27072. return false;
  27073. }
  27074. this._geometries.push(geometry);
  27075. //notify the collision coordinator
  27076. if (this.collisionCoordinator) {
  27077. this.collisionCoordinator.onGeometryAdded(geometry);
  27078. }
  27079. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27080. return true;
  27081. };
  27082. /**
  27083. * Removes an existing geometry
  27084. * @param geometry defines the geometry to be removed from the scene
  27085. * @return a boolean defining if the geometry was removed or not
  27086. */
  27087. Scene.prototype.removeGeometry = function (geometry) {
  27088. var index = this._geometries.indexOf(geometry);
  27089. if (index > -1) {
  27090. this._geometries.splice(index, 1);
  27091. //notify the collision coordinator
  27092. if (this.collisionCoordinator) {
  27093. this.collisionCoordinator.onGeometryDeleted(geometry);
  27094. }
  27095. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27096. return true;
  27097. }
  27098. return false;
  27099. };
  27100. /**
  27101. * Gets the list of geometries attached to the scene
  27102. * @returns an array of Geometry
  27103. */
  27104. Scene.prototype.getGeometries = function () {
  27105. return this._geometries;
  27106. };
  27107. /**
  27108. * Gets the first added mesh found of a given ID
  27109. * @param id defines the id to search for
  27110. * @return the mesh found or null if not found at all
  27111. */
  27112. Scene.prototype.getMeshByID = function (id) {
  27113. for (var index = 0; index < this.meshes.length; index++) {
  27114. if (this.meshes[index].id === id) {
  27115. return this.meshes[index];
  27116. }
  27117. }
  27118. return null;
  27119. };
  27120. /**
  27121. * Gets a list of meshes using their id
  27122. * @param id defines the id to search for
  27123. * @returns a list of meshes
  27124. */
  27125. Scene.prototype.getMeshesByID = function (id) {
  27126. return this.meshes.filter(function (m) {
  27127. return m.id === id;
  27128. });
  27129. };
  27130. /**
  27131. * Gets the first added transform node found of a given ID
  27132. * @param id defines the id to search for
  27133. * @return the found transform node or null if not found at all.
  27134. */
  27135. Scene.prototype.getTransformNodeByID = function (id) {
  27136. for (var index = 0; index < this.transformNodes.length; index++) {
  27137. if (this.transformNodes[index].id === id) {
  27138. return this.transformNodes[index];
  27139. }
  27140. }
  27141. return null;
  27142. };
  27143. /**
  27144. * Gets a list of transform nodes using their id
  27145. * @param id defines the id to search for
  27146. * @returns a list of transform nodes
  27147. */
  27148. Scene.prototype.getTransformNodesByID = function (id) {
  27149. return this.transformNodes.filter(function (m) {
  27150. return m.id === id;
  27151. });
  27152. };
  27153. /**
  27154. * Gets a mesh with its auto-generated unique id
  27155. * @param uniqueId defines the unique id to search for
  27156. * @return the found mesh or null if not found at all.
  27157. */
  27158. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27159. for (var index = 0; index < this.meshes.length; index++) {
  27160. if (this.meshes[index].uniqueId === uniqueId) {
  27161. return this.meshes[index];
  27162. }
  27163. }
  27164. return null;
  27165. };
  27166. /**
  27167. * Gets a the last added mesh using a given id
  27168. * @param id defines the id to search for
  27169. * @return the found mesh or null if not found at all.
  27170. */
  27171. Scene.prototype.getLastMeshByID = function (id) {
  27172. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27173. if (this.meshes[index].id === id) {
  27174. return this.meshes[index];
  27175. }
  27176. }
  27177. return null;
  27178. };
  27179. /**
  27180. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27181. * @param id defines the id to search for
  27182. * @return the found node or null if not found at all
  27183. */
  27184. Scene.prototype.getLastEntryByID = function (id) {
  27185. var index;
  27186. for (index = this.meshes.length - 1; index >= 0; index--) {
  27187. if (this.meshes[index].id === id) {
  27188. return this.meshes[index];
  27189. }
  27190. }
  27191. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27192. if (this.transformNodes[index].id === id) {
  27193. return this.transformNodes[index];
  27194. }
  27195. }
  27196. for (index = this.cameras.length - 1; index >= 0; index--) {
  27197. if (this.cameras[index].id === id) {
  27198. return this.cameras[index];
  27199. }
  27200. }
  27201. for (index = this.lights.length - 1; index >= 0; index--) {
  27202. if (this.lights[index].id === id) {
  27203. return this.lights[index];
  27204. }
  27205. }
  27206. return null;
  27207. };
  27208. /**
  27209. * Gets a node (Mesh, Camera, Light) using a given id
  27210. * @param id defines the id to search for
  27211. * @return the found node or null if not found at all
  27212. */
  27213. Scene.prototype.getNodeByID = function (id) {
  27214. var mesh = this.getMeshByID(id);
  27215. if (mesh) {
  27216. return mesh;
  27217. }
  27218. var light = this.getLightByID(id);
  27219. if (light) {
  27220. return light;
  27221. }
  27222. var camera = this.getCameraByID(id);
  27223. if (camera) {
  27224. return camera;
  27225. }
  27226. var bone = this.getBoneByID(id);
  27227. return bone;
  27228. };
  27229. /**
  27230. * Gets a node (Mesh, Camera, Light) using a given name
  27231. * @param name defines the name to search for
  27232. * @return the found node or null if not found at all.
  27233. */
  27234. Scene.prototype.getNodeByName = function (name) {
  27235. var mesh = this.getMeshByName(name);
  27236. if (mesh) {
  27237. return mesh;
  27238. }
  27239. var light = this.getLightByName(name);
  27240. if (light) {
  27241. return light;
  27242. }
  27243. var camera = this.getCameraByName(name);
  27244. if (camera) {
  27245. return camera;
  27246. }
  27247. var bone = this.getBoneByName(name);
  27248. return bone;
  27249. };
  27250. /**
  27251. * Gets a mesh using a given name
  27252. * @param name defines the name to search for
  27253. * @return the found mesh or null if not found at all.
  27254. */
  27255. Scene.prototype.getMeshByName = function (name) {
  27256. for (var index = 0; index < this.meshes.length; index++) {
  27257. if (this.meshes[index].name === name) {
  27258. return this.meshes[index];
  27259. }
  27260. }
  27261. return null;
  27262. };
  27263. /**
  27264. * Gets a transform node using a given name
  27265. * @param name defines the name to search for
  27266. * @return the found transform node or null if not found at all.
  27267. */
  27268. Scene.prototype.getTransformNodeByName = function (name) {
  27269. for (var index = 0; index < this.transformNodes.length; index++) {
  27270. if (this.transformNodes[index].name === name) {
  27271. return this.transformNodes[index];
  27272. }
  27273. }
  27274. return null;
  27275. };
  27276. /**
  27277. * Gets a sound using a given name
  27278. * @param name defines the name to search for
  27279. * @return the found sound or null if not found at all.
  27280. */
  27281. Scene.prototype.getSoundByName = function (name) {
  27282. var index;
  27283. if (BABYLON.AudioEngine) {
  27284. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27285. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27286. return this.mainSoundTrack.soundCollection[index];
  27287. }
  27288. }
  27289. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27290. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27291. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27292. return this.soundTracks[sdIndex].soundCollection[index];
  27293. }
  27294. }
  27295. }
  27296. }
  27297. return null;
  27298. };
  27299. /**
  27300. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27301. * @param id defines the id to search for
  27302. * @return the found skeleton or null if not found at all.
  27303. */
  27304. Scene.prototype.getLastSkeletonByID = function (id) {
  27305. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27306. if (this.skeletons[index].id === id) {
  27307. return this.skeletons[index];
  27308. }
  27309. }
  27310. return null;
  27311. };
  27312. /**
  27313. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27314. * @param id defines the id to search for
  27315. * @return the found skeleton or null if not found at all.
  27316. */
  27317. Scene.prototype.getSkeletonById = function (id) {
  27318. for (var index = 0; index < this.skeletons.length; index++) {
  27319. if (this.skeletons[index].id === id) {
  27320. return this.skeletons[index];
  27321. }
  27322. }
  27323. return null;
  27324. };
  27325. /**
  27326. * Gets a skeleton using a given name
  27327. * @param name defines the name to search for
  27328. * @return the found skeleton or null if not found at all.
  27329. */
  27330. Scene.prototype.getSkeletonByName = function (name) {
  27331. for (var index = 0; index < this.skeletons.length; index++) {
  27332. if (this.skeletons[index].name === name) {
  27333. return this.skeletons[index];
  27334. }
  27335. }
  27336. return null;
  27337. };
  27338. /**
  27339. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27340. * @param id defines the id to search for
  27341. * @return the found morph target manager or null if not found at all.
  27342. */
  27343. Scene.prototype.getMorphTargetManagerById = function (id) {
  27344. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27345. if (this.morphTargetManagers[index].uniqueId === id) {
  27346. return this.morphTargetManagers[index];
  27347. }
  27348. }
  27349. return null;
  27350. };
  27351. /**
  27352. * Gets a boolean indicating if the given mesh is active
  27353. * @param mesh defines the mesh to look for
  27354. * @returns true if the mesh is in the active list
  27355. */
  27356. Scene.prototype.isActiveMesh = function (mesh) {
  27357. return (this._activeMeshes.indexOf(mesh) !== -1);
  27358. };
  27359. /**
  27360. * Return a the first highlight layer of the scene with a given name.
  27361. * @param name The name of the highlight layer to look for.
  27362. * @return The highlight layer if found otherwise null.
  27363. */
  27364. Scene.prototype.getHighlightLayerByName = function (name) {
  27365. for (var index = 0; index < this.effectLayers.length; index++) {
  27366. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27367. return this.effectLayers[index];
  27368. }
  27369. }
  27370. return null;
  27371. };
  27372. /**
  27373. * Return a the first highlight layer of the scene with a given name.
  27374. * @param name The name of the highlight layer to look for.
  27375. * @return The highlight layer if found otherwise null.
  27376. */
  27377. Scene.prototype.getGlowLayerByName = function (name) {
  27378. for (var index = 0; index < this.effectLayers.length; index++) {
  27379. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27380. return this.effectLayers[index];
  27381. }
  27382. }
  27383. return null;
  27384. };
  27385. Object.defineProperty(Scene.prototype, "uid", {
  27386. /**
  27387. * Return a unique id as a string which can serve as an identifier for the scene
  27388. */
  27389. get: function () {
  27390. if (!this._uid) {
  27391. this._uid = BABYLON.Tools.RandomId();
  27392. }
  27393. return this._uid;
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. /**
  27399. * Add an externaly attached data from its key.
  27400. * This method call will fail and return false, if such key already exists.
  27401. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27402. * @param key the unique key that identifies the data
  27403. * @param data the data object to associate to the key for this Engine instance
  27404. * @return true if no such key were already present and the data was added successfully, false otherwise
  27405. */
  27406. Scene.prototype.addExternalData = function (key, data) {
  27407. if (!this._externalData) {
  27408. this._externalData = new BABYLON.StringDictionary();
  27409. }
  27410. return this._externalData.add(key, data);
  27411. };
  27412. /**
  27413. * Get an externaly attached data from its key
  27414. * @param key the unique key that identifies the data
  27415. * @return the associated data, if present (can be null), or undefined if not present
  27416. */
  27417. Scene.prototype.getExternalData = function (key) {
  27418. if (!this._externalData) {
  27419. return null;
  27420. }
  27421. return this._externalData.get(key);
  27422. };
  27423. /**
  27424. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27425. * @param key the unique key that identifies the data
  27426. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27427. * @return the associated data, can be null if the factory returned null.
  27428. */
  27429. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27430. if (!this._externalData) {
  27431. this._externalData = new BABYLON.StringDictionary();
  27432. }
  27433. return this._externalData.getOrAddWithFactory(key, factory);
  27434. };
  27435. /**
  27436. * Remove an externaly attached data from the Engine instance
  27437. * @param key the unique key that identifies the data
  27438. * @return true if the data was successfully removed, false if it doesn't exist
  27439. */
  27440. Scene.prototype.removeExternalData = function (key) {
  27441. return this._externalData.remove(key);
  27442. };
  27443. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27444. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27445. if (mesh.showSubMeshesBoundingBox) {
  27446. var boundingInfo = subMesh.getBoundingInfo();
  27447. if (boundingInfo !== null && boundingInfo !== undefined) {
  27448. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27449. }
  27450. }
  27451. var material = subMesh.getMaterial();
  27452. if (material !== null && material !== undefined) {
  27453. // Render targets
  27454. if (material.getRenderTargetTextures !== undefined) {
  27455. if (this._processedMaterials.indexOf(material) === -1) {
  27456. this._processedMaterials.push(material);
  27457. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27458. }
  27459. }
  27460. // Dispatch
  27461. this._activeIndices.addCount(subMesh.indexCount, false);
  27462. this._renderingManager.dispatch(subMesh, mesh, material);
  27463. }
  27464. }
  27465. };
  27466. /**
  27467. * Clear the processed materials smart array preventing retention point in material dispose.
  27468. */
  27469. Scene.prototype.freeProcessedMaterials = function () {
  27470. this._processedMaterials.dispose();
  27471. };
  27472. /**
  27473. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27474. */
  27475. Scene.prototype.freeActiveMeshes = function () {
  27476. this._activeMeshes.dispose();
  27477. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27478. this.activeCamera._activeMeshes.dispose();
  27479. }
  27480. if (this.activeCameras) {
  27481. for (var i = 0; i < this.activeCameras.length; i++) {
  27482. var activeCamera = this.activeCameras[i];
  27483. if (activeCamera && activeCamera._activeMeshes) {
  27484. activeCamera._activeMeshes.dispose();
  27485. }
  27486. }
  27487. }
  27488. };
  27489. /**
  27490. * Clear the info related to rendering groups preventing retention points during dispose.
  27491. */
  27492. Scene.prototype.freeRenderingGroups = function () {
  27493. if (this._renderingManager) {
  27494. this._renderingManager.freeRenderingGroups();
  27495. }
  27496. if (this.textures) {
  27497. for (var i = 0; i < this.textures.length; i++) {
  27498. var texture = this.textures[i];
  27499. if (texture && texture.renderList) {
  27500. texture.freeRenderingGroups();
  27501. }
  27502. }
  27503. }
  27504. };
  27505. /** @hidden */
  27506. Scene.prototype._isInIntermediateRendering = function () {
  27507. return this._intermediateRendering;
  27508. };
  27509. /**
  27510. * Defines the current active mesh candidate provider
  27511. * @param provider defines the provider to use
  27512. */
  27513. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27514. this._activeMeshCandidateProvider = provider;
  27515. };
  27516. /**
  27517. * Gets the current active mesh candidate provider
  27518. * @returns the current active mesh candidate provider
  27519. */
  27520. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27521. return this._activeMeshCandidateProvider;
  27522. };
  27523. /**
  27524. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27525. * @returns the current scene
  27526. */
  27527. Scene.prototype.freezeActiveMeshes = function () {
  27528. if (!this.activeCamera) {
  27529. return this;
  27530. }
  27531. if (!this._frustumPlanes) {
  27532. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27533. }
  27534. this._evaluateActiveMeshes();
  27535. this._activeMeshesFrozen = true;
  27536. return this;
  27537. };
  27538. /**
  27539. * Use this function to restart evaluating active meshes on every frame
  27540. * @returns the current scene
  27541. */
  27542. Scene.prototype.unfreezeActiveMeshes = function () {
  27543. this._activeMeshesFrozen = false;
  27544. return this;
  27545. };
  27546. Scene.prototype._evaluateActiveMeshes = function () {
  27547. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27548. return;
  27549. }
  27550. if (!this.activeCamera) {
  27551. return;
  27552. }
  27553. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27554. this.activeCamera._activeMeshes.reset();
  27555. this._activeMeshes.reset();
  27556. this._renderingManager.reset();
  27557. this._processedMaterials.reset();
  27558. this._activeParticleSystems.reset();
  27559. this._activeSkeletons.reset();
  27560. this._softwareSkinnedMeshes.reset();
  27561. if (this._boundingBoxRenderer) {
  27562. this._boundingBoxRenderer.reset();
  27563. }
  27564. // Meshes
  27565. var meshes;
  27566. var len;
  27567. var checkIsEnabled = true;
  27568. // Determine mesh candidates
  27569. if (this._activeMeshCandidateProvider !== undefined) {
  27570. // Use _activeMeshCandidateProvider
  27571. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27572. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27573. if (meshes !== undefined) {
  27574. len = meshes.length;
  27575. }
  27576. else {
  27577. len = 0;
  27578. }
  27579. }
  27580. else if (this._selectionOctree !== undefined) {
  27581. // Octree
  27582. var selection = this._selectionOctree.select(this._frustumPlanes);
  27583. meshes = selection.data;
  27584. len = selection.length;
  27585. }
  27586. else {
  27587. // Full scene traversal
  27588. len = this.meshes.length;
  27589. meshes = this.meshes;
  27590. }
  27591. // Check each mesh
  27592. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27593. mesh = meshes[meshIndex];
  27594. if (mesh.isBlocked) {
  27595. continue;
  27596. }
  27597. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27598. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27599. continue;
  27600. }
  27601. mesh.computeWorldMatrix();
  27602. // Intersections
  27603. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27604. this._meshesForIntersections.pushNoDuplicate(mesh);
  27605. }
  27606. // Switch to current LOD
  27607. meshLOD = mesh.getLOD(this.activeCamera);
  27608. if (meshLOD === undefined || meshLOD === null) {
  27609. continue;
  27610. }
  27611. mesh._preActivate();
  27612. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27613. this._activeMeshes.push(mesh);
  27614. this.activeCamera._activeMeshes.push(mesh);
  27615. mesh._activate(this._renderId);
  27616. if (meshLOD !== mesh) {
  27617. meshLOD._activate(this._renderId);
  27618. }
  27619. this._activeMesh(mesh, meshLOD);
  27620. }
  27621. }
  27622. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27623. // Particle systems
  27624. if (this.particlesEnabled) {
  27625. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27626. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27627. var particleSystem = this.particleSystems[particleIndex];
  27628. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27629. continue;
  27630. }
  27631. var emitter = particleSystem.emitter;
  27632. if (!emitter.position || emitter.isEnabled()) {
  27633. this._activeParticleSystems.push(particleSystem);
  27634. particleSystem.animate();
  27635. this._renderingManager.dispatchParticles(particleSystem);
  27636. }
  27637. }
  27638. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27639. }
  27640. };
  27641. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27642. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27643. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27644. mesh.skeleton.prepare();
  27645. }
  27646. if (!mesh.computeBonesUsingShaders) {
  27647. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27648. }
  27649. }
  27650. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27651. var boundingInfo = sourceMesh.getBoundingInfo();
  27652. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27653. }
  27654. if (mesh !== undefined && mesh !== null
  27655. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27656. // Submeshes Octrees
  27657. var len;
  27658. var subMeshes;
  27659. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27660. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27661. len = intersections.length;
  27662. subMeshes = intersections.data;
  27663. }
  27664. else {
  27665. subMeshes = mesh.subMeshes;
  27666. len = subMeshes.length;
  27667. }
  27668. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27669. subMesh = subMeshes[subIndex];
  27670. this._evaluateSubMesh(subMesh, mesh);
  27671. }
  27672. }
  27673. };
  27674. /**
  27675. * Update the transform matrix to update from the current active camera
  27676. * @param force defines a boolean used to force the update even if cache is up to date
  27677. */
  27678. Scene.prototype.updateTransformMatrix = function (force) {
  27679. if (!this.activeCamera) {
  27680. return;
  27681. }
  27682. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27683. };
  27684. /**
  27685. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27686. * @param alternateCamera defines the camera to use
  27687. */
  27688. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27689. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27690. };
  27691. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27692. if (camera && camera._skipRendering) {
  27693. return;
  27694. }
  27695. var engine = this._engine;
  27696. this.activeCamera = camera;
  27697. if (!this.activeCamera)
  27698. throw new Error("Active camera not set");
  27699. // Viewport
  27700. engine.setViewport(this.activeCamera.viewport);
  27701. // Camera
  27702. this.resetCachedMaterial();
  27703. this._renderId++;
  27704. this.updateTransformMatrix();
  27705. if (camera._alternateCamera) {
  27706. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27707. this._alternateRendering = true;
  27708. }
  27709. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27710. // Meshes
  27711. this._evaluateActiveMeshes();
  27712. // Software skinning
  27713. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27714. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27715. mesh.applySkeleton(mesh.skeleton);
  27716. }
  27717. // Render targets
  27718. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27719. var needsRestoreFrameBuffer = false;
  27720. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27721. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27722. }
  27723. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27724. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27725. }
  27726. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27727. this._intermediateRendering = true;
  27728. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27729. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27730. var renderTarget = this._renderTargets.data[renderIndex];
  27731. if (renderTarget._shouldRender()) {
  27732. this._renderId++;
  27733. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27734. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27735. }
  27736. }
  27737. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27738. this._intermediateRendering = false;
  27739. this._renderId++;
  27740. needsRestoreFrameBuffer = true; // Restore back buffer
  27741. }
  27742. // Render EffectLayer Texture
  27743. var stencilState = this._engine.getStencilBuffer();
  27744. var renderEffects = false;
  27745. var needStencil = false;
  27746. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27747. this._intermediateRendering = true;
  27748. for (var i = 0; i < this.effectLayers.length; i++) {
  27749. var effectLayer = this.effectLayers[i];
  27750. if (effectLayer.shouldRender() &&
  27751. (!effectLayer.camera ||
  27752. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27753. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27754. renderEffects = true;
  27755. needStencil = needStencil || effectLayer.needStencil();
  27756. var renderTarget = effectLayer._mainTexture;
  27757. if (renderTarget._shouldRender()) {
  27758. this._renderId++;
  27759. renderTarget.render(false, false);
  27760. needsRestoreFrameBuffer = true;
  27761. }
  27762. }
  27763. }
  27764. this._intermediateRendering = false;
  27765. this._renderId++;
  27766. }
  27767. if (needsRestoreFrameBuffer) {
  27768. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27769. }
  27770. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27771. // Prepare Frame
  27772. if (this.postProcessManager) {
  27773. this.postProcessManager._prepareFrame();
  27774. }
  27775. // Backgrounds
  27776. var layerIndex;
  27777. var layer;
  27778. if (this.layers.length) {
  27779. engine.setDepthBuffer(false);
  27780. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27781. layer = this.layers[layerIndex];
  27782. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27783. layer.render();
  27784. }
  27785. }
  27786. engine.setDepthBuffer(true);
  27787. }
  27788. // Activate effect Layer stencil
  27789. if (needStencil) {
  27790. this._engine.setStencilBuffer(true);
  27791. }
  27792. // Render
  27793. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27794. this._renderingManager.render(null, null, true, true);
  27795. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27796. // Restore effect Layer stencil
  27797. if (needStencil) {
  27798. this._engine.setStencilBuffer(stencilState);
  27799. }
  27800. // Bounding boxes
  27801. if (this._boundingBoxRenderer) {
  27802. this._boundingBoxRenderer.render();
  27803. }
  27804. // Lens flares
  27805. if (this.lensFlaresEnabled) {
  27806. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27807. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27808. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27809. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27810. lensFlareSystem.render();
  27811. }
  27812. }
  27813. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27814. }
  27815. // Effect Layer
  27816. if (renderEffects) {
  27817. engine.setDepthBuffer(false);
  27818. for (var i = 0; i < this.effectLayers.length; i++) {
  27819. if (this.effectLayers[i].shouldRender()) {
  27820. this.effectLayers[i].render();
  27821. }
  27822. }
  27823. engine.setDepthBuffer(true);
  27824. }
  27825. // Foregrounds
  27826. if (this.layers.length) {
  27827. engine.setDepthBuffer(false);
  27828. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27829. layer = this.layers[layerIndex];
  27830. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27831. layer.render();
  27832. }
  27833. }
  27834. engine.setDepthBuffer(true);
  27835. }
  27836. // Finalize frame
  27837. if (this.postProcessManager) {
  27838. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27839. }
  27840. // Reset some special arrays
  27841. this._renderTargets.reset();
  27842. this._alternateRendering = false;
  27843. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27844. };
  27845. Scene.prototype._processSubCameras = function (camera) {
  27846. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27847. this._renderForCamera(camera);
  27848. return;
  27849. }
  27850. // rig cameras
  27851. for (var index = 0; index < camera._rigCameras.length; index++) {
  27852. this._renderForCamera(camera._rigCameras[index], camera);
  27853. }
  27854. this.activeCamera = camera;
  27855. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27856. };
  27857. Scene.prototype._checkIntersections = function () {
  27858. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27859. var sourceMesh = this._meshesForIntersections.data[index];
  27860. if (!sourceMesh.actionManager) {
  27861. continue;
  27862. }
  27863. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27864. var action = sourceMesh.actionManager.actions[actionIndex];
  27865. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27866. var parameters = action.getTriggerParameter();
  27867. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27868. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27869. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27870. if (areIntersecting && currentIntersectionInProgress === -1) {
  27871. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27872. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27873. sourceMesh._intersectionsInProgress.push(otherMesh);
  27874. }
  27875. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27876. sourceMesh._intersectionsInProgress.push(otherMesh);
  27877. }
  27878. }
  27879. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27880. //They intersected, and now they don't.
  27881. //is this trigger an exit trigger? execute an event.
  27882. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27883. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27884. }
  27885. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27886. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27887. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27888. return otherMesh === parameterMesh;
  27889. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27890. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27891. }
  27892. }
  27893. }
  27894. }
  27895. }
  27896. };
  27897. /**
  27898. * Render the scene
  27899. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27900. */
  27901. Scene.prototype.render = function (updateCameras) {
  27902. if (updateCameras === void 0) { updateCameras = true; }
  27903. if (this.isDisposed) {
  27904. return;
  27905. }
  27906. this._activeParticles.fetchNewFrame();
  27907. this._totalVertices.fetchNewFrame();
  27908. this._activeIndices.fetchNewFrame();
  27909. this._activeBones.fetchNewFrame();
  27910. this._meshesForIntersections.reset();
  27911. this.resetCachedMaterial();
  27912. this.onBeforeAnimationsObservable.notifyObservers(this);
  27913. // Actions
  27914. if (this.actionManager) {
  27915. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27916. }
  27917. //Simplification Queue
  27918. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27919. this.simplificationQueue.executeNext();
  27920. }
  27921. if (this._engine.isDeterministicLockStep()) {
  27922. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27923. var defaultFPS = (60.0 / 1000.0);
  27924. var defaultFrameTime = 1000 / 60; // frame time in MS
  27925. if (this._physicsEngine) {
  27926. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27927. }
  27928. var stepsTaken = 0;
  27929. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27930. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27931. internalSteps = Math.min(internalSteps, maxSubSteps);
  27932. do {
  27933. this.onBeforeStepObservable.notifyObservers(this);
  27934. // Animations
  27935. this._animationRatio = defaultFrameTime * defaultFPS;
  27936. this._animate();
  27937. this.onAfterAnimationsObservable.notifyObservers(this);
  27938. // Physics
  27939. if (this._physicsEngine) {
  27940. this.onBeforePhysicsObservable.notifyObservers(this);
  27941. this._physicsEngine._step(defaultFrameTime / 1000);
  27942. this.onAfterPhysicsObservable.notifyObservers(this);
  27943. }
  27944. this.onAfterStepObservable.notifyObservers(this);
  27945. this._currentStepId++;
  27946. stepsTaken++;
  27947. deltaTime -= defaultFrameTime;
  27948. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27949. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27950. }
  27951. else {
  27952. // Animations
  27953. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27954. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27955. this._animate();
  27956. this.onAfterAnimationsObservable.notifyObservers(this);
  27957. // Physics
  27958. if (this._physicsEngine) {
  27959. this.onBeforePhysicsObservable.notifyObservers(this);
  27960. this._physicsEngine._step(deltaTime / 1000.0);
  27961. this.onAfterPhysicsObservable.notifyObservers(this);
  27962. }
  27963. }
  27964. // update gamepad manager
  27965. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27966. this._gamepadManager._checkGamepadsStatus();
  27967. }
  27968. // Update Cameras
  27969. if (updateCameras) {
  27970. if (this.activeCameras.length > 0) {
  27971. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27972. var camera = this.activeCameras[cameraIndex];
  27973. camera.update();
  27974. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27975. // rig cameras
  27976. for (var index = 0; index < camera._rigCameras.length; index++) {
  27977. camera._rigCameras[index].update();
  27978. }
  27979. }
  27980. }
  27981. }
  27982. else if (this.activeCamera) {
  27983. this.activeCamera.update();
  27984. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27985. // rig cameras
  27986. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27987. this.activeCamera._rigCameras[index].update();
  27988. }
  27989. }
  27990. }
  27991. }
  27992. // Before render
  27993. this.onBeforeRenderObservable.notifyObservers(this);
  27994. // Customs render targets
  27995. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27996. var engine = this.getEngine();
  27997. var currentActiveCamera = this.activeCamera;
  27998. if (this.renderTargetsEnabled) {
  27999. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28000. this._intermediateRendering = true;
  28001. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28002. var renderTarget = this.customRenderTargets[customIndex];
  28003. if (renderTarget._shouldRender()) {
  28004. this._renderId++;
  28005. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28006. if (!this.activeCamera)
  28007. throw new Error("Active camera not set");
  28008. // Viewport
  28009. engine.setViewport(this.activeCamera.viewport);
  28010. // Camera
  28011. this.updateTransformMatrix();
  28012. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28013. }
  28014. }
  28015. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28016. this._intermediateRendering = false;
  28017. this._renderId++;
  28018. }
  28019. // Restore back buffer
  28020. if (this.customRenderTargets.length > 0) {
  28021. engine.restoreDefaultFramebuffer();
  28022. }
  28023. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28024. this.activeCamera = currentActiveCamera;
  28025. // Procedural textures
  28026. if (this.proceduralTexturesEnabled) {
  28027. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28028. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28029. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28030. if (proceduralTexture._shouldRender()) {
  28031. proceduralTexture.render();
  28032. }
  28033. }
  28034. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28035. }
  28036. // Clear
  28037. if (this.autoClearDepthAndStencil || this.autoClear) {
  28038. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28039. }
  28040. // Shadows
  28041. if (this.shadowsEnabled) {
  28042. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28043. var light = this.lights[lightIndex];
  28044. var shadowGenerator = light.getShadowGenerator();
  28045. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28046. var shadowMap = (shadowGenerator.getShadowMap());
  28047. if (this.textures.indexOf(shadowMap) !== -1) {
  28048. this._renderTargets.push(shadowMap);
  28049. }
  28050. }
  28051. }
  28052. }
  28053. // Depth renderer
  28054. for (var key in this._depthRenderer) {
  28055. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28056. }
  28057. // Geometry renderer
  28058. if (this._geometryBufferRenderer) {
  28059. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28060. }
  28061. // RenderPipeline
  28062. if (this._postProcessRenderPipelineManager) {
  28063. this._postProcessRenderPipelineManager.update();
  28064. }
  28065. // Multi-cameras?
  28066. if (this.activeCameras.length > 0) {
  28067. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28068. if (cameraIndex > 0) {
  28069. this._engine.clear(null, false, true, true);
  28070. }
  28071. this._processSubCameras(this.activeCameras[cameraIndex]);
  28072. }
  28073. }
  28074. else {
  28075. if (!this.activeCamera) {
  28076. throw new Error("No camera defined");
  28077. }
  28078. this._processSubCameras(this.activeCamera);
  28079. }
  28080. // Intersection checks
  28081. this._checkIntersections();
  28082. // Update the audio listener attached to the camera
  28083. if (BABYLON.AudioEngine) {
  28084. this._updateAudioParameters();
  28085. }
  28086. // After render
  28087. if (this.afterRender) {
  28088. this.afterRender();
  28089. }
  28090. this.onAfterRenderObservable.notifyObservers(this);
  28091. // Cleaning
  28092. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28093. var data = this._toBeDisposed.data[index];
  28094. if (data) {
  28095. data.dispose();
  28096. }
  28097. this._toBeDisposed[index] = null;
  28098. }
  28099. this._toBeDisposed.reset();
  28100. if (this.dumpNextRenderTargets) {
  28101. this.dumpNextRenderTargets = false;
  28102. }
  28103. this._activeBones.addCount(0, true);
  28104. this._activeIndices.addCount(0, true);
  28105. this._activeParticles.addCount(0, true);
  28106. };
  28107. Scene.prototype._updateAudioParameters = function () {
  28108. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28109. return;
  28110. }
  28111. var listeningCamera;
  28112. var audioEngine = BABYLON.Engine.audioEngine;
  28113. if (this.activeCameras.length > 0) {
  28114. listeningCamera = this.activeCameras[0];
  28115. }
  28116. else {
  28117. listeningCamera = this.activeCamera;
  28118. }
  28119. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28120. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28121. // for VR cameras
  28122. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28123. listeningCamera = listeningCamera.rigCameras[0];
  28124. }
  28125. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28126. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28127. cameraDirection.normalize();
  28128. // To avoid some errors on GearVR
  28129. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28130. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28131. }
  28132. var i;
  28133. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28134. var sound = this.mainSoundTrack.soundCollection[i];
  28135. if (sound.useCustomAttenuation) {
  28136. sound.updateDistanceFromListener();
  28137. }
  28138. }
  28139. for (i = 0; i < this.soundTracks.length; i++) {
  28140. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28141. sound = this.soundTracks[i].soundCollection[j];
  28142. if (sound.useCustomAttenuation) {
  28143. sound.updateDistanceFromListener();
  28144. }
  28145. }
  28146. }
  28147. }
  28148. };
  28149. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28150. // Audio
  28151. /**
  28152. * Gets or sets if audio support is enabled
  28153. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28154. */
  28155. get: function () {
  28156. return this._audioEnabled;
  28157. },
  28158. set: function (value) {
  28159. this._audioEnabled = value;
  28160. if (BABYLON.AudioEngine) {
  28161. if (this._audioEnabled) {
  28162. this._enableAudio();
  28163. }
  28164. else {
  28165. this._disableAudio();
  28166. }
  28167. }
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. Scene.prototype._disableAudio = function () {
  28173. var i;
  28174. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28175. this.mainSoundTrack.soundCollection[i].pause();
  28176. }
  28177. for (i = 0; i < this.soundTracks.length; i++) {
  28178. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28179. this.soundTracks[i].soundCollection[j].pause();
  28180. }
  28181. }
  28182. };
  28183. Scene.prototype._enableAudio = function () {
  28184. var i;
  28185. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28186. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28187. this.mainSoundTrack.soundCollection[i].play();
  28188. }
  28189. }
  28190. for (i = 0; i < this.soundTracks.length; i++) {
  28191. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28192. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28193. this.soundTracks[i].soundCollection[j].play();
  28194. }
  28195. }
  28196. }
  28197. };
  28198. Object.defineProperty(Scene.prototype, "headphone", {
  28199. /**
  28200. * Gets or sets if audio will be output to headphones
  28201. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28202. */
  28203. get: function () {
  28204. return this._headphone;
  28205. },
  28206. set: function (value) {
  28207. this._headphone = value;
  28208. if (BABYLON.AudioEngine) {
  28209. if (this._headphone) {
  28210. this._switchAudioModeForHeadphones();
  28211. }
  28212. else {
  28213. this._switchAudioModeForNormalSpeakers();
  28214. }
  28215. }
  28216. },
  28217. enumerable: true,
  28218. configurable: true
  28219. });
  28220. Scene.prototype._switchAudioModeForHeadphones = function () {
  28221. this.mainSoundTrack.switchPanningModelToHRTF();
  28222. for (var i = 0; i < this.soundTracks.length; i++) {
  28223. this.soundTracks[i].switchPanningModelToHRTF();
  28224. }
  28225. };
  28226. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28227. this.mainSoundTrack.switchPanningModelToEqualPower();
  28228. for (var i = 0; i < this.soundTracks.length; i++) {
  28229. this.soundTracks[i].switchPanningModelToEqualPower();
  28230. }
  28231. };
  28232. /**
  28233. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28234. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28235. * @returns the created depth renderer
  28236. */
  28237. Scene.prototype.enableDepthRenderer = function (camera) {
  28238. camera = camera || this.activeCamera;
  28239. if (!camera) {
  28240. throw "No camera available to enable depth renderer";
  28241. }
  28242. if (!this._depthRenderer[camera.id]) {
  28243. var textureType = 0;
  28244. if (this._engine.getCaps().textureHalfFloatRender) {
  28245. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28246. }
  28247. else if (this._engine.getCaps().textureFloatRender) {
  28248. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28249. }
  28250. else {
  28251. throw "Depth renderer does not support int texture type";
  28252. }
  28253. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28254. }
  28255. return this._depthRenderer[camera.id];
  28256. };
  28257. /**
  28258. * Disables a depth renderer for a given camera
  28259. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28260. */
  28261. Scene.prototype.disableDepthRenderer = function (camera) {
  28262. camera = camera || this.activeCamera;
  28263. if (!camera || !this._depthRenderer[camera.id]) {
  28264. return;
  28265. }
  28266. this._depthRenderer[camera.id].dispose();
  28267. delete this._depthRenderer[camera.id];
  28268. };
  28269. /**
  28270. * Enables a GeometryBufferRender and associates it with the scene
  28271. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28272. * @returns the GeometryBufferRenderer
  28273. */
  28274. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28275. if (ratio === void 0) { ratio = 1; }
  28276. if (this._geometryBufferRenderer) {
  28277. return this._geometryBufferRenderer;
  28278. }
  28279. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28280. if (!this._geometryBufferRenderer.isSupported) {
  28281. this._geometryBufferRenderer = null;
  28282. }
  28283. return this._geometryBufferRenderer;
  28284. };
  28285. /**
  28286. * Disables the GeometryBufferRender associated with the scene
  28287. */
  28288. Scene.prototype.disableGeometryBufferRenderer = function () {
  28289. if (!this._geometryBufferRenderer) {
  28290. return;
  28291. }
  28292. this._geometryBufferRenderer.dispose();
  28293. this._geometryBufferRenderer = null;
  28294. };
  28295. /**
  28296. * Freeze all materials
  28297. * A frozen material will not be updatable but should be faster to render
  28298. */
  28299. Scene.prototype.freezeMaterials = function () {
  28300. for (var i = 0; i < this.materials.length; i++) {
  28301. this.materials[i].freeze();
  28302. }
  28303. };
  28304. /**
  28305. * Unfreeze all materials
  28306. * A frozen material will not be updatable but should be faster to render
  28307. */
  28308. Scene.prototype.unfreezeMaterials = function () {
  28309. for (var i = 0; i < this.materials.length; i++) {
  28310. this.materials[i].unfreeze();
  28311. }
  28312. };
  28313. /**
  28314. * Releases all held ressources
  28315. */
  28316. Scene.prototype.dispose = function () {
  28317. this.beforeRender = null;
  28318. this.afterRender = null;
  28319. this.skeletons = [];
  28320. this.morphTargetManagers = [];
  28321. this.importedMeshesFiles = new Array();
  28322. this.stopAllAnimations();
  28323. this.resetCachedMaterial();
  28324. for (var key in this._depthRenderer) {
  28325. this._depthRenderer[key].dispose();
  28326. }
  28327. if (this._gamepadManager) {
  28328. this._gamepadManager.dispose();
  28329. this._gamepadManager = null;
  28330. }
  28331. // Smart arrays
  28332. if (this.activeCamera) {
  28333. this.activeCamera._activeMeshes.dispose();
  28334. this.activeCamera = null;
  28335. }
  28336. this._activeMeshes.dispose();
  28337. this._renderingManager.dispose();
  28338. this._processedMaterials.dispose();
  28339. this._activeParticleSystems.dispose();
  28340. this._activeSkeletons.dispose();
  28341. this._softwareSkinnedMeshes.dispose();
  28342. this._renderTargets.dispose();
  28343. this._registeredForLateAnimationBindings.dispose();
  28344. if (this._boundingBoxRenderer) {
  28345. this._boundingBoxRenderer.dispose();
  28346. }
  28347. this._meshesForIntersections.dispose();
  28348. this._toBeDisposed.dispose();
  28349. // Abort active requests
  28350. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28351. var request = _a[_i];
  28352. request.abort();
  28353. }
  28354. // Debug layer
  28355. if (this._debugLayer) {
  28356. this._debugLayer.hide();
  28357. }
  28358. // Events
  28359. this.onDisposeObservable.notifyObservers(this);
  28360. this.onDisposeObservable.clear();
  28361. this.onBeforeRenderObservable.clear();
  28362. this.onAfterRenderObservable.clear();
  28363. this.onBeforeRenderTargetsRenderObservable.clear();
  28364. this.onAfterRenderTargetsRenderObservable.clear();
  28365. this.onAfterStepObservable.clear();
  28366. this.onBeforeStepObservable.clear();
  28367. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28368. this.onAfterActiveMeshesEvaluationObservable.clear();
  28369. this.onBeforeParticlesRenderingObservable.clear();
  28370. this.onAfterParticlesRenderingObservable.clear();
  28371. this.onBeforeSpritesRenderingObservable.clear();
  28372. this.onAfterSpritesRenderingObservable.clear();
  28373. this.onBeforeDrawPhaseObservable.clear();
  28374. this.onAfterDrawPhaseObservable.clear();
  28375. this.onBeforePhysicsObservable.clear();
  28376. this.onAfterPhysicsObservable.clear();
  28377. this.onBeforeAnimationsObservable.clear();
  28378. this.onAfterAnimationsObservable.clear();
  28379. this.onDataLoadedObservable.clear();
  28380. this.detachControl();
  28381. // Release sounds & sounds tracks
  28382. if (BABYLON.AudioEngine) {
  28383. this.disposeSounds();
  28384. }
  28385. // VR Helper
  28386. if (this.VRHelper) {
  28387. this.VRHelper.dispose();
  28388. }
  28389. // Detach cameras
  28390. var canvas = this._engine.getRenderingCanvas();
  28391. if (canvas) {
  28392. var index;
  28393. for (index = 0; index < this.cameras.length; index++) {
  28394. this.cameras[index].detachControl(canvas);
  28395. }
  28396. }
  28397. // Release animation groups
  28398. while (this.animationGroups.length) {
  28399. this.animationGroups[0].dispose();
  28400. }
  28401. // Release lights
  28402. while (this.lights.length) {
  28403. this.lights[0].dispose();
  28404. }
  28405. // Release meshes
  28406. while (this.meshes.length) {
  28407. this.meshes[0].dispose(true);
  28408. }
  28409. while (this.transformNodes.length) {
  28410. this.removeTransformNode(this.transformNodes[0]);
  28411. }
  28412. // Release cameras
  28413. while (this.cameras.length) {
  28414. this.cameras[0].dispose();
  28415. }
  28416. // Release materials
  28417. if (this.defaultMaterial) {
  28418. this.defaultMaterial.dispose();
  28419. }
  28420. while (this.multiMaterials.length) {
  28421. this.multiMaterials[0].dispose();
  28422. }
  28423. while (this.materials.length) {
  28424. this.materials[0].dispose();
  28425. }
  28426. // Release particles
  28427. while (this.particleSystems.length) {
  28428. this.particleSystems[0].dispose();
  28429. }
  28430. // Release sprites
  28431. while (this.spriteManagers.length) {
  28432. this.spriteManagers[0].dispose();
  28433. }
  28434. // Release postProcesses
  28435. while (this.postProcesses.length) {
  28436. this.postProcesses[0].dispose();
  28437. }
  28438. // Release layers
  28439. while (this.layers.length) {
  28440. this.layers[0].dispose();
  28441. }
  28442. while (this.effectLayers.length) {
  28443. this.effectLayers[0].dispose();
  28444. }
  28445. // Release textures
  28446. while (this.textures.length) {
  28447. this.textures[0].dispose();
  28448. }
  28449. // Release UBO
  28450. this._sceneUbo.dispose();
  28451. if (this._alternateSceneUbo) {
  28452. this._alternateSceneUbo.dispose();
  28453. }
  28454. // Post-processes
  28455. this.postProcessManager.dispose();
  28456. if (this._postProcessRenderPipelineManager) {
  28457. this._postProcessRenderPipelineManager.dispose();
  28458. }
  28459. // Physics
  28460. if (this._physicsEngine) {
  28461. this.disablePhysicsEngine();
  28462. }
  28463. // Remove from engine
  28464. index = this._engine.scenes.indexOf(this);
  28465. if (index > -1) {
  28466. this._engine.scenes.splice(index, 1);
  28467. }
  28468. this._engine.wipeCaches(true);
  28469. this._isDisposed = true;
  28470. };
  28471. Object.defineProperty(Scene.prototype, "isDisposed", {
  28472. /**
  28473. * Gets if the scene is already disposed
  28474. */
  28475. get: function () {
  28476. return this._isDisposed;
  28477. },
  28478. enumerable: true,
  28479. configurable: true
  28480. });
  28481. /**
  28482. * Releases sounds & soundtracks
  28483. */
  28484. Scene.prototype.disposeSounds = function () {
  28485. if (!this._mainSoundTrack) {
  28486. return;
  28487. }
  28488. this.mainSoundTrack.dispose();
  28489. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28490. this.soundTracks[scIndex].dispose();
  28491. }
  28492. };
  28493. /**
  28494. * Call this function to reduce memory footprint of the scene.
  28495. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28496. */
  28497. Scene.prototype.clearCachedVertexData = function () {
  28498. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28499. var mesh = this.meshes[meshIndex];
  28500. var geometry = mesh.geometry;
  28501. if (geometry) {
  28502. geometry._indices = [];
  28503. for (var vbName in geometry._vertexBuffers) {
  28504. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28505. continue;
  28506. }
  28507. geometry._vertexBuffers[vbName]._buffer._data = null;
  28508. }
  28509. }
  28510. }
  28511. };
  28512. /**
  28513. * This function will remove the local cached buffer data from texture.
  28514. * It will save memory but will prevent the texture from being rebuilt
  28515. */
  28516. Scene.prototype.cleanCachedTextureBuffer = function () {
  28517. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28518. var baseTexture = _a[_i];
  28519. var buffer = baseTexture._buffer;
  28520. if (buffer) {
  28521. baseTexture._buffer = null;
  28522. }
  28523. }
  28524. };
  28525. // Octrees
  28526. /**
  28527. * Get the world extend vectors with an optional filter
  28528. *
  28529. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28530. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28531. */
  28532. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28533. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28534. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28535. filterPredicate = filterPredicate || (function () { return true; });
  28536. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28537. mesh.computeWorldMatrix(true);
  28538. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28539. return;
  28540. }
  28541. var boundingInfo = mesh.getBoundingInfo();
  28542. var minBox = boundingInfo.boundingBox.minimumWorld;
  28543. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28544. BABYLON.Tools.CheckExtends(minBox, min, max);
  28545. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28546. });
  28547. return {
  28548. min: min,
  28549. max: max
  28550. };
  28551. };
  28552. /**
  28553. * Creates or updates the octree used to boost selection (picking)
  28554. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28555. * @param maxCapacity defines the maximum capacity per leaf
  28556. * @param maxDepth defines the maximum depth of the octree
  28557. * @returns an octree of AbstractMesh
  28558. */
  28559. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28560. if (maxCapacity === void 0) { maxCapacity = 64; }
  28561. if (maxDepth === void 0) { maxDepth = 2; }
  28562. if (!this._selectionOctree) {
  28563. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28564. }
  28565. var worldExtends = this.getWorldExtends();
  28566. // Update octree
  28567. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28568. return this._selectionOctree;
  28569. };
  28570. // Picking
  28571. /**
  28572. * Creates a ray that can be used to pick in the scene
  28573. * @param x defines the x coordinate of the origin (on-screen)
  28574. * @param y defines the y coordinate of the origin (on-screen)
  28575. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28576. * @param camera defines the camera to use for the picking
  28577. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28578. * @returns a Ray
  28579. */
  28580. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28581. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28582. var result = BABYLON.Ray.Zero();
  28583. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28584. return result;
  28585. };
  28586. /**
  28587. * Creates a ray that can be used to pick in the scene
  28588. * @param x defines the x coordinate of the origin (on-screen)
  28589. * @param y defines the y coordinate of the origin (on-screen)
  28590. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28591. * @param result defines the ray where to store the picking ray
  28592. * @param camera defines the camera to use for the picking
  28593. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28594. * @returns the current scene
  28595. */
  28596. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28597. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28598. var engine = this._engine;
  28599. if (!camera) {
  28600. if (!this.activeCamera)
  28601. throw new Error("Active camera not set");
  28602. camera = this.activeCamera;
  28603. }
  28604. var cameraViewport = camera.viewport;
  28605. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28606. // Moving coordinates to local viewport world
  28607. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28608. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28609. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28610. return this;
  28611. };
  28612. /**
  28613. * Creates a ray that can be used to pick in the scene
  28614. * @param x defines the x coordinate of the origin (on-screen)
  28615. * @param y defines the y coordinate of the origin (on-screen)
  28616. * @param camera defines the camera to use for the picking
  28617. * @returns a Ray
  28618. */
  28619. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28620. var result = BABYLON.Ray.Zero();
  28621. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28622. return result;
  28623. };
  28624. /**
  28625. * Creates a ray that can be used to pick in the scene
  28626. * @param x defines the x coordinate of the origin (on-screen)
  28627. * @param y defines the y coordinate of the origin (on-screen)
  28628. * @param result defines the ray where to store the picking ray
  28629. * @param camera defines the camera to use for the picking
  28630. * @returns the current scene
  28631. */
  28632. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28633. if (!BABYLON.PickingInfo) {
  28634. return this;
  28635. }
  28636. var engine = this._engine;
  28637. if (!camera) {
  28638. if (!this.activeCamera)
  28639. throw new Error("Active camera not set");
  28640. camera = this.activeCamera;
  28641. }
  28642. var cameraViewport = camera.viewport;
  28643. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28644. var identity = BABYLON.Matrix.Identity();
  28645. // Moving coordinates to local viewport world
  28646. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28647. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28648. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28649. return this;
  28650. };
  28651. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28652. if (!BABYLON.PickingInfo) {
  28653. return null;
  28654. }
  28655. var pickingInfo = null;
  28656. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28657. var mesh = this.meshes[meshIndex];
  28658. if (predicate) {
  28659. if (!predicate(mesh)) {
  28660. continue;
  28661. }
  28662. }
  28663. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28664. continue;
  28665. }
  28666. var world = mesh.getWorldMatrix();
  28667. var ray = rayFunction(world);
  28668. var result = mesh.intersects(ray, fastCheck);
  28669. if (!result || !result.hit)
  28670. continue;
  28671. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28672. continue;
  28673. pickingInfo = result;
  28674. if (fastCheck) {
  28675. break;
  28676. }
  28677. }
  28678. return pickingInfo || new BABYLON.PickingInfo();
  28679. };
  28680. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28681. if (!BABYLON.PickingInfo) {
  28682. return null;
  28683. }
  28684. var pickingInfos = new Array();
  28685. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28686. var mesh = this.meshes[meshIndex];
  28687. if (predicate) {
  28688. if (!predicate(mesh)) {
  28689. continue;
  28690. }
  28691. }
  28692. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28693. continue;
  28694. }
  28695. var world = mesh.getWorldMatrix();
  28696. var ray = rayFunction(world);
  28697. var result = mesh.intersects(ray, false);
  28698. if (!result || !result.hit)
  28699. continue;
  28700. pickingInfos.push(result);
  28701. }
  28702. return pickingInfos;
  28703. };
  28704. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28705. if (!BABYLON.PickingInfo) {
  28706. return null;
  28707. }
  28708. var pickingInfo = null;
  28709. if (!camera) {
  28710. if (!this.activeCamera) {
  28711. return null;
  28712. }
  28713. camera = this.activeCamera;
  28714. }
  28715. if (this.spriteManagers.length > 0) {
  28716. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28717. var spriteManager = this.spriteManagers[spriteIndex];
  28718. if (!spriteManager.isPickable) {
  28719. continue;
  28720. }
  28721. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28722. if (!result || !result.hit)
  28723. continue;
  28724. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28725. continue;
  28726. pickingInfo = result;
  28727. if (fastCheck) {
  28728. break;
  28729. }
  28730. }
  28731. }
  28732. return pickingInfo || new BABYLON.PickingInfo();
  28733. };
  28734. /** Launch a ray to try to pick a mesh in the scene
  28735. * @param x position on screen
  28736. * @param y position on screen
  28737. * @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
  28738. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28739. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28740. * @returns a PickingInfo
  28741. */
  28742. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28743. var _this = this;
  28744. if (!BABYLON.PickingInfo) {
  28745. return null;
  28746. }
  28747. var result = this._internalPick(function (world) {
  28748. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28749. return _this._tempPickingRay;
  28750. }, predicate, fastCheck);
  28751. if (result) {
  28752. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28753. }
  28754. return result;
  28755. };
  28756. /** Launch a ray to try to pick a sprite in the scene
  28757. * @param x position on screen
  28758. * @param y position on screen
  28759. * @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
  28760. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28761. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28762. * @returns a PickingInfo
  28763. */
  28764. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28765. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28766. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28767. };
  28768. /** Use the given ray to pick a mesh in the scene
  28769. * @param ray The ray to use to pick meshes
  28770. * @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
  28771. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28772. * @returns a PickingInfo
  28773. */
  28774. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28775. var _this = this;
  28776. var result = this._internalPick(function (world) {
  28777. if (!_this._pickWithRayInverseMatrix) {
  28778. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28779. }
  28780. world.invertToRef(_this._pickWithRayInverseMatrix);
  28781. if (!_this._cachedRayForTransform) {
  28782. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28783. }
  28784. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28785. return _this._cachedRayForTransform;
  28786. }, predicate, fastCheck);
  28787. if (result) {
  28788. result.ray = ray;
  28789. }
  28790. return result;
  28791. };
  28792. /**
  28793. * Launch a ray to try to pick a mesh in the scene
  28794. * @param x X position on screen
  28795. * @param y Y position on screen
  28796. * @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
  28797. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28798. * @returns an array of PickingInfo
  28799. */
  28800. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28801. var _this = this;
  28802. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28803. };
  28804. /**
  28805. * Launch a ray to try to pick a mesh in the scene
  28806. * @param ray Ray to use
  28807. * @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
  28808. * @returns an array of PickingInfo
  28809. */
  28810. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28811. var _this = this;
  28812. return this._internalMultiPick(function (world) {
  28813. if (!_this._pickWithRayInverseMatrix) {
  28814. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28815. }
  28816. world.invertToRef(_this._pickWithRayInverseMatrix);
  28817. if (!_this._cachedRayForTransform) {
  28818. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28819. }
  28820. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28821. return _this._cachedRayForTransform;
  28822. }, predicate);
  28823. };
  28824. /**
  28825. * Force the value of meshUnderPointer
  28826. * @param mesh defines the mesh to use
  28827. */
  28828. Scene.prototype.setPointerOverMesh = function (mesh) {
  28829. if (this._pointerOverMesh === mesh) {
  28830. return;
  28831. }
  28832. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28833. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28834. }
  28835. this._pointerOverMesh = mesh;
  28836. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28837. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28838. }
  28839. };
  28840. /**
  28841. * Gets the mesh under the pointer
  28842. * @returns a Mesh or null if no mesh is under the pointer
  28843. */
  28844. Scene.prototype.getPointerOverMesh = function () {
  28845. return this._pointerOverMesh;
  28846. };
  28847. /**
  28848. * Force the sprite under the pointer
  28849. * @param sprite defines the sprite to use
  28850. */
  28851. Scene.prototype.setPointerOverSprite = function (sprite) {
  28852. if (this._pointerOverSprite === sprite) {
  28853. return;
  28854. }
  28855. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28856. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28857. }
  28858. this._pointerOverSprite = sprite;
  28859. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28860. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28861. }
  28862. };
  28863. /**
  28864. * Gets the sprite under the pointer
  28865. * @returns a Sprite or null if no sprite is under the pointer
  28866. */
  28867. Scene.prototype.getPointerOverSprite = function () {
  28868. return this._pointerOverSprite;
  28869. };
  28870. // Physics
  28871. /**
  28872. * Gets the current physics engine
  28873. * @returns a PhysicsEngine or null if none attached
  28874. */
  28875. Scene.prototype.getPhysicsEngine = function () {
  28876. return this._physicsEngine;
  28877. };
  28878. /**
  28879. * Enables physics to the current scene
  28880. * @param gravity defines the scene's gravity for the physics engine
  28881. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28882. * @return a boolean indicating if the physics engine was initialized
  28883. */
  28884. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28885. if (gravity === void 0) { gravity = null; }
  28886. if (this._physicsEngine) {
  28887. return true;
  28888. }
  28889. try {
  28890. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28891. return true;
  28892. }
  28893. catch (e) {
  28894. BABYLON.Tools.Error(e.message);
  28895. return false;
  28896. }
  28897. };
  28898. /**
  28899. * Disables and disposes the physics engine associated with the scene
  28900. */
  28901. Scene.prototype.disablePhysicsEngine = function () {
  28902. if (!this._physicsEngine) {
  28903. return;
  28904. }
  28905. this._physicsEngine.dispose();
  28906. this._physicsEngine = null;
  28907. };
  28908. /**
  28909. * Gets a boolean indicating if there is an active physics engine
  28910. * @returns a boolean indicating if there is an active physics engine
  28911. */
  28912. Scene.prototype.isPhysicsEnabled = function () {
  28913. return this._physicsEngine !== undefined;
  28914. };
  28915. /**
  28916. * Deletes a physics compound impostor
  28917. * @param compound defines the compound to delete
  28918. */
  28919. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28920. var mesh = compound.parts[0].mesh;
  28921. if (mesh.physicsImpostor) {
  28922. mesh.physicsImpostor.dispose( /*true*/);
  28923. mesh.physicsImpostor = null;
  28924. }
  28925. };
  28926. // Misc.
  28927. /** @hidden */
  28928. Scene.prototype._rebuildGeometries = function () {
  28929. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28930. var geometry = _a[_i];
  28931. geometry._rebuild();
  28932. }
  28933. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28934. var mesh = _c[_b];
  28935. mesh._rebuild();
  28936. }
  28937. if (this.postProcessManager) {
  28938. this.postProcessManager._rebuild();
  28939. }
  28940. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28941. var layer = _e[_d];
  28942. layer._rebuild();
  28943. }
  28944. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28945. var effectLayer = _g[_f];
  28946. effectLayer._rebuild();
  28947. }
  28948. if (this._boundingBoxRenderer) {
  28949. this._boundingBoxRenderer._rebuild();
  28950. }
  28951. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28952. var system = _j[_h];
  28953. system.rebuild();
  28954. }
  28955. if (this._postProcessRenderPipelineManager) {
  28956. this._postProcessRenderPipelineManager._rebuild();
  28957. }
  28958. };
  28959. /** @hidden */
  28960. Scene.prototype._rebuildTextures = function () {
  28961. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28962. var texture = _a[_i];
  28963. texture._rebuild();
  28964. }
  28965. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28966. };
  28967. /**
  28968. * Creates a default light for the scene.
  28969. * @param replace Whether to replace the existing lights in the scene.
  28970. */
  28971. Scene.prototype.createDefaultLight = function (replace) {
  28972. if (replace === void 0) { replace = false; }
  28973. // Dispose existing light in replace mode.
  28974. if (replace) {
  28975. if (this.lights) {
  28976. for (var i = 0; i < this.lights.length; i++) {
  28977. this.lights[i].dispose();
  28978. }
  28979. }
  28980. }
  28981. // Light
  28982. if (this.lights.length === 0) {
  28983. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28984. }
  28985. };
  28986. /**
  28987. * Creates a default camera for the scene.
  28988. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28989. * @param replace Whether to replace the existing active camera in the scene.
  28990. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28991. */
  28992. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28993. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28994. if (replace === void 0) { replace = false; }
  28995. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28996. // Dispose existing camera in replace mode.
  28997. if (replace) {
  28998. if (this.activeCamera) {
  28999. this.activeCamera.dispose();
  29000. this.activeCamera = null;
  29001. }
  29002. }
  29003. // Camera
  29004. if (!this.activeCamera) {
  29005. var worldExtends = this.getWorldExtends();
  29006. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29007. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29008. var camera;
  29009. var radius = worldSize.length() * 1.5;
  29010. // empty scene scenario!
  29011. if (!isFinite(radius)) {
  29012. radius = 1;
  29013. worldCenter.copyFromFloats(0, 0, 0);
  29014. }
  29015. if (createArcRotateCamera) {
  29016. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29017. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29018. arcRotateCamera.wheelPrecision = 100 / radius;
  29019. camera = arcRotateCamera;
  29020. }
  29021. else {
  29022. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29023. freeCamera.setTarget(worldCenter);
  29024. camera = freeCamera;
  29025. }
  29026. camera.minZ = radius * 0.01;
  29027. camera.maxZ = radius * 1000;
  29028. camera.speed = radius * 0.2;
  29029. this.activeCamera = camera;
  29030. var canvas = this.getEngine().getRenderingCanvas();
  29031. if (attachCameraControls && canvas) {
  29032. camera.attachControl(canvas);
  29033. }
  29034. }
  29035. };
  29036. /**
  29037. * Creates a default camera and a default light
  29038. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29039. * @param replace defines if the camera and/or light will replace the existing ones
  29040. * @param attachCameraControls defines if attachControl will be called on the new camera
  29041. */
  29042. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29043. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29044. if (replace === void 0) { replace = false; }
  29045. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29046. this.createDefaultLight(replace);
  29047. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29048. };
  29049. /**
  29050. * Creates a new sky box
  29051. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29052. * @param environmentTexture defines the texture to use as environment texture
  29053. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29054. * @param scale defines the overall scale of the skybox
  29055. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29056. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29057. * @returns a new mesh holding the sky box
  29058. */
  29059. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29060. if (pbr === void 0) { pbr = false; }
  29061. if (scale === void 0) { scale = 1000; }
  29062. if (blur === void 0) { blur = 0; }
  29063. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29064. if (!environmentTexture) {
  29065. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29066. return null;
  29067. }
  29068. if (setGlobalEnvTexture) {
  29069. if (environmentTexture) {
  29070. this.environmentTexture = environmentTexture;
  29071. }
  29072. }
  29073. // Skybox
  29074. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29075. if (pbr) {
  29076. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29077. hdrSkyboxMaterial.backFaceCulling = false;
  29078. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29079. if (hdrSkyboxMaterial.reflectionTexture) {
  29080. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29081. }
  29082. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29083. hdrSkyboxMaterial.disableLighting = true;
  29084. hdrSkyboxMaterial.twoSidedLighting = true;
  29085. hdrSkybox.infiniteDistance = true;
  29086. hdrSkybox.material = hdrSkyboxMaterial;
  29087. }
  29088. else {
  29089. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29090. skyboxMaterial.backFaceCulling = false;
  29091. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29092. if (skyboxMaterial.reflectionTexture) {
  29093. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29094. }
  29095. skyboxMaterial.disableLighting = true;
  29096. hdrSkybox.infiniteDistance = true;
  29097. hdrSkybox.material = skyboxMaterial;
  29098. }
  29099. return hdrSkybox;
  29100. };
  29101. /**
  29102. * Creates a new environment
  29103. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29104. * @param options defines the options you can use to configure the environment
  29105. * @returns the new EnvironmentHelper
  29106. */
  29107. Scene.prototype.createDefaultEnvironment = function (options) {
  29108. if (BABYLON.EnvironmentHelper) {
  29109. return new BABYLON.EnvironmentHelper(options, this);
  29110. }
  29111. return null;
  29112. };
  29113. /**
  29114. * Creates a new VREXperienceHelper
  29115. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29116. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29117. * @returns a new VREXperienceHelper
  29118. */
  29119. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29120. if (webVROptions === void 0) { webVROptions = {}; }
  29121. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29122. };
  29123. // Tags
  29124. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29125. if (tagsQuery === undefined) {
  29126. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29127. return list;
  29128. }
  29129. var listByTags = [];
  29130. forEach = forEach || (function (item) { return; });
  29131. for (var i in list) {
  29132. var item = list[i];
  29133. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29134. listByTags.push(item);
  29135. forEach(item);
  29136. }
  29137. }
  29138. return listByTags;
  29139. };
  29140. /**
  29141. * Get a list of meshes by tags
  29142. * @param tagsQuery defines the tags query to use
  29143. * @param forEach defines a predicate used to filter results
  29144. * @returns an array of Mesh
  29145. */
  29146. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29147. return this._getByTags(this.meshes, tagsQuery, forEach);
  29148. };
  29149. /**
  29150. * Get a list of cameras by tags
  29151. * @param tagsQuery defines the tags query to use
  29152. * @param forEach defines a predicate used to filter results
  29153. * @returns an array of Camera
  29154. */
  29155. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29156. return this._getByTags(this.cameras, tagsQuery, forEach);
  29157. };
  29158. /**
  29159. * Get a list of lights by tags
  29160. * @param tagsQuery defines the tags query to use
  29161. * @param forEach defines a predicate used to filter results
  29162. * @returns an array of Light
  29163. */
  29164. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29165. return this._getByTags(this.lights, tagsQuery, forEach);
  29166. };
  29167. /**
  29168. * Get a list of materials by tags
  29169. * @param tagsQuery defines the tags query to use
  29170. * @param forEach defines a predicate used to filter results
  29171. * @returns an array of Material
  29172. */
  29173. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29174. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29175. };
  29176. /**
  29177. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29178. * This allowed control for front to back rendering or reversly depending of the special needs.
  29179. *
  29180. * @param renderingGroupId The rendering group id corresponding to its index
  29181. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29182. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29183. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29184. */
  29185. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29186. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29187. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29188. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29189. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29190. };
  29191. /**
  29192. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29193. *
  29194. * @param renderingGroupId The rendering group id corresponding to its index
  29195. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29196. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29197. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29198. */
  29199. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29200. if (depth === void 0) { depth = true; }
  29201. if (stencil === void 0) { stencil = true; }
  29202. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29203. };
  29204. /**
  29205. * Will flag all materials as dirty to trigger new shader compilation
  29206. * @param flag defines the flag used to specify which material part must be marked as dirty
  29207. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29208. */
  29209. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29210. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29211. var material = _a[_i];
  29212. if (predicate && !predicate(material)) {
  29213. continue;
  29214. }
  29215. material.markAsDirty(flag);
  29216. }
  29217. };
  29218. /** @hidden */
  29219. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29220. var _this = this;
  29221. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29222. this._activeRequests.push(request);
  29223. request.onCompleteObservable.add(function (request) {
  29224. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29225. });
  29226. return request;
  29227. };
  29228. /** @hidden */
  29229. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29230. var _this = this;
  29231. return new Promise(function (resolve, reject) {
  29232. _this._loadFile(url, function (data) {
  29233. resolve(data);
  29234. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29235. reject(exception);
  29236. });
  29237. });
  29238. };
  29239. // Statics
  29240. Scene._FOGMODE_NONE = 0;
  29241. Scene._FOGMODE_EXP = 1;
  29242. Scene._FOGMODE_EXP2 = 2;
  29243. Scene._FOGMODE_LINEAR = 3;
  29244. Scene._uniqueIdCounter = 0;
  29245. /**
  29246. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29247. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29248. */
  29249. Scene.MinDeltaTime = 1.0;
  29250. /**
  29251. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29252. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29253. */
  29254. Scene.MaxDeltaTime = 1000.0;
  29255. /** The distance in pixel that you have to move to prevent some events */
  29256. Scene.DragMovementThreshold = 10; // in pixels
  29257. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29258. Scene.LongPressDelay = 500; // in milliseconds
  29259. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29260. Scene.DoubleClickDelay = 300; // in milliseconds
  29261. /** If you need to check double click without raising a single click at first click, enable this flag */
  29262. Scene.ExclusiveDoubleClickMode = false;
  29263. return Scene;
  29264. }());
  29265. BABYLON.Scene = Scene;
  29266. })(BABYLON || (BABYLON = {}));
  29267. //# sourceMappingURL=babylon.scene.js.map
  29268. var BABYLON;
  29269. (function (BABYLON) {
  29270. /**
  29271. * Set of assets to keep when moving a scene into an asset container.
  29272. */
  29273. var KeepAssets = /** @class */ (function () {
  29274. function KeepAssets() {
  29275. /**
  29276. * Cameras to keep.
  29277. */
  29278. this.cameras = new Array();
  29279. /**
  29280. * Lights to keep.
  29281. */
  29282. this.lights = new Array();
  29283. /**
  29284. * Meshes to keep.
  29285. */
  29286. this.meshes = new Array();
  29287. /**
  29288. * Skeletons to keep.
  29289. */
  29290. this.skeletons = new Array();
  29291. /**
  29292. * ParticleSystems to keep.
  29293. */
  29294. this.particleSystems = new Array();
  29295. /**
  29296. * Animations to keep.
  29297. */
  29298. this.animations = new Array();
  29299. /**
  29300. * AnimationGroups to keep.
  29301. */
  29302. this.animationGroups = new Array();
  29303. /**
  29304. * MultiMaterials to keep.
  29305. */
  29306. this.multiMaterials = new Array();
  29307. /**
  29308. * Materials to keep.
  29309. */
  29310. this.materials = new Array();
  29311. /**
  29312. * MorphTargetManagers to keep.
  29313. */
  29314. this.morphTargetManagers = new Array();
  29315. /**
  29316. * Geometries to keep.
  29317. */
  29318. this.geometries = new Array();
  29319. /**
  29320. * TransformNodes to keep.
  29321. */
  29322. this.transformNodes = new Array();
  29323. /**
  29324. * LensFlareSystems to keep.
  29325. */
  29326. this.lensFlareSystems = new Array();
  29327. /**
  29328. * ShadowGenerators to keep.
  29329. */
  29330. this.shadowGenerators = new Array();
  29331. /**
  29332. * ActionManagers to keep.
  29333. */
  29334. this.actionManagers = new Array();
  29335. /**
  29336. * Sounds to keep.
  29337. */
  29338. this.sounds = new Array();
  29339. /**
  29340. * Textures to keep.
  29341. */
  29342. this.textures = new Array();
  29343. /**
  29344. * Effect layers to keep.
  29345. */
  29346. this.effectLayers = new Array();
  29347. }
  29348. return KeepAssets;
  29349. }());
  29350. BABYLON.KeepAssets = KeepAssets;
  29351. /**
  29352. * Container with a set of assets that can be added or removed from a scene.
  29353. */
  29354. var AssetContainer = /** @class */ (function () {
  29355. /**
  29356. * Instantiates an AssetContainer.
  29357. * @param scene The scene the AssetContainer belongs to.
  29358. */
  29359. function AssetContainer(scene) {
  29360. // Objects
  29361. /**
  29362. * Cameras populated in the container.
  29363. */
  29364. this.cameras = new Array();
  29365. /**
  29366. * Lights populated in the container.
  29367. */
  29368. this.lights = new Array();
  29369. /**
  29370. * Meshes populated in the container.
  29371. */
  29372. this.meshes = new Array();
  29373. /**
  29374. * Skeletons populated in the container.
  29375. */
  29376. this.skeletons = new Array();
  29377. /**
  29378. * ParticleSystems populated in the container.
  29379. */
  29380. this.particleSystems = new Array();
  29381. /**
  29382. * Animations populated in the container.
  29383. */
  29384. this.animations = new Array();
  29385. /**
  29386. * AnimationGroups populated in the container.
  29387. */
  29388. this.animationGroups = new Array();
  29389. /**
  29390. * MultiMaterials populated in the container.
  29391. */
  29392. this.multiMaterials = new Array();
  29393. /**
  29394. * Materials populated in the container.
  29395. */
  29396. this.materials = new Array();
  29397. /**
  29398. * MorphTargetManagers populated in the container.
  29399. */
  29400. this.morphTargetManagers = new Array();
  29401. /**
  29402. * Geometries populated in the container.
  29403. */
  29404. this.geometries = new Array();
  29405. /**
  29406. * TransformNodes populated in the container.
  29407. */
  29408. this.transformNodes = new Array();
  29409. /**
  29410. * LensFlareSystems populated in the container.
  29411. */
  29412. this.lensFlareSystems = new Array();
  29413. /**
  29414. * ShadowGenerators populated in the container.
  29415. */
  29416. this.shadowGenerators = new Array();
  29417. /**
  29418. * ActionManagers populated in the container.
  29419. */
  29420. this.actionManagers = new Array();
  29421. /**
  29422. * Sounds populated in the container.
  29423. */
  29424. this.sounds = new Array();
  29425. /**
  29426. * Textures populated in the container.
  29427. */
  29428. this.textures = new Array();
  29429. /**
  29430. * Effect layers populated in the container.
  29431. */
  29432. this.effectLayers = new Array();
  29433. this.scene = scene;
  29434. }
  29435. /**
  29436. * Adds all the assets from the container to the scene.
  29437. */
  29438. AssetContainer.prototype.addAllToScene = function () {
  29439. var _this = this;
  29440. this.cameras.forEach(function (o) {
  29441. _this.scene.addCamera(o);
  29442. });
  29443. this.lights.forEach(function (o) {
  29444. _this.scene.addLight(o);
  29445. });
  29446. this.meshes.forEach(function (o) {
  29447. _this.scene.addMesh(o);
  29448. });
  29449. this.skeletons.forEach(function (o) {
  29450. _this.scene.addSkeleton(o);
  29451. });
  29452. this.particleSystems.forEach(function (o) {
  29453. _this.scene.addParticleSystem(o);
  29454. });
  29455. this.animations.forEach(function (o) {
  29456. _this.scene.addAnimation(o);
  29457. });
  29458. this.animationGroups.forEach(function (o) {
  29459. _this.scene.addAnimationGroup(o);
  29460. });
  29461. this.multiMaterials.forEach(function (o) {
  29462. _this.scene.addMultiMaterial(o);
  29463. });
  29464. this.materials.forEach(function (o) {
  29465. _this.scene.addMaterial(o);
  29466. });
  29467. this.morphTargetManagers.forEach(function (o) {
  29468. _this.scene.addMorphTargetManager(o);
  29469. });
  29470. this.geometries.forEach(function (o) {
  29471. _this.scene.addGeometry(o);
  29472. });
  29473. this.transformNodes.forEach(function (o) {
  29474. _this.scene.addTransformNode(o);
  29475. });
  29476. this.lensFlareSystems.forEach(function (o) {
  29477. _this.scene.addLensFlareSystem(o);
  29478. });
  29479. this.actionManagers.forEach(function (o) {
  29480. _this.scene.addActionManager(o);
  29481. });
  29482. this.sounds.forEach(function (o) {
  29483. o.play();
  29484. o.autoplay = true;
  29485. _this.scene.mainSoundTrack.AddSound(o);
  29486. });
  29487. this.textures.forEach(function (o) {
  29488. _this.scene.addTexture(o);
  29489. });
  29490. this.effectLayers.forEach(function (o) {
  29491. _this.scene.addEffectLayer(o);
  29492. });
  29493. };
  29494. /**
  29495. * Removes all the assets in the container from the scene
  29496. */
  29497. AssetContainer.prototype.removeAllFromScene = function () {
  29498. var _this = this;
  29499. this.cameras.forEach(function (o) {
  29500. _this.scene.removeCamera(o);
  29501. });
  29502. this.lights.forEach(function (o) {
  29503. _this.scene.removeLight(o);
  29504. });
  29505. this.meshes.forEach(function (o) {
  29506. _this.scene.removeMesh(o);
  29507. });
  29508. this.skeletons.forEach(function (o) {
  29509. _this.scene.removeSkeleton(o);
  29510. });
  29511. this.particleSystems.forEach(function (o) {
  29512. _this.scene.removeParticleSystem(o);
  29513. });
  29514. this.animations.forEach(function (o) {
  29515. _this.scene.removeAnimation(o);
  29516. });
  29517. this.animationGroups.forEach(function (o) {
  29518. _this.scene.removeAnimationGroup(o);
  29519. });
  29520. this.multiMaterials.forEach(function (o) {
  29521. _this.scene.removeMultiMaterial(o);
  29522. });
  29523. this.materials.forEach(function (o) {
  29524. _this.scene.removeMaterial(o);
  29525. });
  29526. this.morphTargetManagers.forEach(function (o) {
  29527. _this.scene.removeMorphTargetManager(o);
  29528. });
  29529. this.geometries.forEach(function (o) {
  29530. _this.scene.removeGeometry(o);
  29531. });
  29532. this.transformNodes.forEach(function (o) {
  29533. _this.scene.removeTransformNode(o);
  29534. });
  29535. this.lensFlareSystems.forEach(function (o) {
  29536. _this.scene.removeLensFlareSystem(o);
  29537. });
  29538. this.actionManagers.forEach(function (o) {
  29539. _this.scene.removeActionManager(o);
  29540. });
  29541. this.sounds.forEach(function (o) {
  29542. o.stop();
  29543. o.autoplay = false;
  29544. _this.scene.mainSoundTrack.RemoveSound(o);
  29545. });
  29546. this.textures.forEach(function (o) {
  29547. _this.scene.removeTexture(o);
  29548. });
  29549. this.effectLayers.forEach(function (o) {
  29550. _this.scene.removeEffectLayer(o);
  29551. });
  29552. };
  29553. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29554. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29555. var asset = sourceAssets_1[_i];
  29556. var move = true;
  29557. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29558. var keepAsset = keepAssets_1[_a];
  29559. if (asset === keepAsset) {
  29560. move = false;
  29561. break;
  29562. }
  29563. }
  29564. if (move) {
  29565. targetAssets.push(asset);
  29566. }
  29567. }
  29568. };
  29569. /**
  29570. * Removes all the assets contained in the scene and adds them to the container.
  29571. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29572. */
  29573. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29574. if (keepAssets === undefined) {
  29575. keepAssets = new KeepAssets();
  29576. }
  29577. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29578. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29579. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29580. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29581. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29582. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29583. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29584. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29585. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29586. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29587. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29588. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29589. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29590. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29591. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29592. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29593. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29594. this.removeAllFromScene();
  29595. };
  29596. /**
  29597. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29598. * @returns the root mesh
  29599. */
  29600. AssetContainer.prototype.createRootMesh = function () {
  29601. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29602. this.meshes.forEach(function (m) {
  29603. if (!m.parent) {
  29604. rootMesh.addChild(m);
  29605. }
  29606. });
  29607. this.meshes.unshift(rootMesh);
  29608. return rootMesh;
  29609. };
  29610. return AssetContainer;
  29611. }());
  29612. BABYLON.AssetContainer = AssetContainer;
  29613. })(BABYLON || (BABYLON = {}));
  29614. //# sourceMappingURL=babylon.assetContainer.js.map
  29615. var BABYLON;
  29616. (function (BABYLON) {
  29617. var Buffer = /** @class */ (function () {
  29618. /**
  29619. * Constructor
  29620. * @param engine the engine
  29621. * @param data the data to use for this buffer
  29622. * @param updatable whether the data is updatable
  29623. * @param stride the stride (optional)
  29624. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29625. * @param instanced whether the buffer is instanced (optional)
  29626. * @param useBytes set to true if the stride in in bytes (optional)
  29627. */
  29628. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29629. if (stride === void 0) { stride = 0; }
  29630. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29631. if (instanced === void 0) { instanced = false; }
  29632. if (useBytes === void 0) { useBytes = false; }
  29633. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29634. this._engine = engine.getScene().getEngine();
  29635. }
  29636. else {
  29637. this._engine = engine;
  29638. }
  29639. this._updatable = updatable;
  29640. this._instanced = instanced;
  29641. this._data = data;
  29642. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29643. if (!postponeInternalCreation) { // by default
  29644. this.create();
  29645. }
  29646. }
  29647. /**
  29648. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29649. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29650. * @param offset defines offset in the buffer (0 by default)
  29651. * @param size defines the size in floats of attributes (position is 3 for instance)
  29652. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29653. * @param instanced defines if the vertex buffer contains indexed data
  29654. * @param useBytes defines if the offset and stride are in bytes
  29655. * @returns the new vertex buffer
  29656. */
  29657. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29658. if (useBytes === void 0) { useBytes = false; }
  29659. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29660. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29661. // a lot of these parameters are ignored as they are overriden by the buffer
  29662. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29663. };
  29664. // Properties
  29665. Buffer.prototype.isUpdatable = function () {
  29666. return this._updatable;
  29667. };
  29668. Buffer.prototype.getData = function () {
  29669. return this._data;
  29670. };
  29671. Buffer.prototype.getBuffer = function () {
  29672. return this._buffer;
  29673. };
  29674. /**
  29675. * Gets the stride in float32 units (i.e. byte stride / 4).
  29676. * May not be an integer if the byte stride is not divisible by 4.
  29677. * DEPRECATED. Use byteStride instead.
  29678. * @returns the stride in float32 units
  29679. */
  29680. Buffer.prototype.getStrideSize = function () {
  29681. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29682. };
  29683. // Methods
  29684. Buffer.prototype.create = function (data) {
  29685. if (data === void 0) { data = null; }
  29686. if (!data && this._buffer) {
  29687. return; // nothing to do
  29688. }
  29689. data = data || this._data;
  29690. if (!data) {
  29691. return;
  29692. }
  29693. if (!this._buffer) { // create buffer
  29694. if (this._updatable) {
  29695. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29696. this._data = data;
  29697. }
  29698. else {
  29699. this._buffer = this._engine.createVertexBuffer(data);
  29700. }
  29701. }
  29702. else if (this._updatable) { // update buffer
  29703. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29704. this._data = data;
  29705. }
  29706. };
  29707. Buffer.prototype._rebuild = function () {
  29708. this._buffer = null;
  29709. this.create(this._data);
  29710. };
  29711. Buffer.prototype.update = function (data) {
  29712. this.create(data);
  29713. };
  29714. /**
  29715. * Updates the data directly.
  29716. * @param data the new data
  29717. * @param offset the new offset
  29718. * @param vertexCount the vertex count (optional)
  29719. * @param useBytes set to true if the offset is in bytes
  29720. */
  29721. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29722. if (useBytes === void 0) { useBytes = false; }
  29723. if (!this._buffer) {
  29724. return;
  29725. }
  29726. if (this._updatable) { // update buffer
  29727. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29728. this._data = null;
  29729. }
  29730. };
  29731. Buffer.prototype.dispose = function () {
  29732. if (!this._buffer) {
  29733. return;
  29734. }
  29735. if (this._engine._releaseBuffer(this._buffer)) {
  29736. this._buffer = null;
  29737. }
  29738. };
  29739. return Buffer;
  29740. }());
  29741. BABYLON.Buffer = Buffer;
  29742. })(BABYLON || (BABYLON = {}));
  29743. //# sourceMappingURL=babylon.buffer.js.map
  29744. var BABYLON;
  29745. (function (BABYLON) {
  29746. var VertexBuffer = /** @class */ (function () {
  29747. /**
  29748. * Constructor
  29749. * @param engine the engine
  29750. * @param data the data to use for this vertex buffer
  29751. * @param kind the vertex buffer kind
  29752. * @param updatable whether the data is updatable
  29753. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29754. * @param stride the stride (optional)
  29755. * @param instanced whether the buffer is instanced (optional)
  29756. * @param offset the offset of the data (optional)
  29757. * @param size the number of components (optional)
  29758. * @param type the type of the component (optional)
  29759. * @param normalized whether the data contains normalized data (optional)
  29760. * @param useBytes set to true if stride and offset are in bytes (optional)
  29761. */
  29762. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29763. if (normalized === void 0) { normalized = false; }
  29764. if (useBytes === void 0) { useBytes = false; }
  29765. if (data instanceof BABYLON.Buffer) {
  29766. this._buffer = data;
  29767. this._ownsBuffer = false;
  29768. }
  29769. else {
  29770. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29771. this._ownsBuffer = true;
  29772. }
  29773. this._kind = kind;
  29774. if (type == undefined) {
  29775. var data_1 = this.getData();
  29776. this.type = VertexBuffer.FLOAT;
  29777. if (data_1 instanceof Int8Array)
  29778. this.type = VertexBuffer.BYTE;
  29779. else if (data_1 instanceof Uint8Array)
  29780. this.type = VertexBuffer.UNSIGNED_BYTE;
  29781. else if (data_1 instanceof Int16Array)
  29782. this.type = VertexBuffer.SHORT;
  29783. else if (data_1 instanceof Uint16Array)
  29784. this.type = VertexBuffer.UNSIGNED_SHORT;
  29785. else if (data_1 instanceof Int32Array)
  29786. this.type = VertexBuffer.INT;
  29787. else if (data_1 instanceof Uint32Array)
  29788. this.type = VertexBuffer.UNSIGNED_INT;
  29789. }
  29790. else {
  29791. this.type = type;
  29792. }
  29793. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29794. if (useBytes) {
  29795. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29796. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29797. this.byteOffset = offset || 0;
  29798. }
  29799. else {
  29800. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29801. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29802. this.byteOffset = (offset || 0) * typeByteLength;
  29803. }
  29804. this.normalized = normalized;
  29805. this._instanced = instanced !== undefined ? instanced : false;
  29806. this._instanceDivisor = instanced ? 1 : 0;
  29807. }
  29808. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29809. /**
  29810. * Gets or sets the instance divisor when in instanced mode
  29811. */
  29812. get: function () {
  29813. return this._instanceDivisor;
  29814. },
  29815. set: function (value) {
  29816. this._instanceDivisor = value;
  29817. if (value == 0) {
  29818. this._instanced = false;
  29819. }
  29820. else {
  29821. this._instanced = true;
  29822. }
  29823. },
  29824. enumerable: true,
  29825. configurable: true
  29826. });
  29827. VertexBuffer.prototype._rebuild = function () {
  29828. if (!this._buffer) {
  29829. return;
  29830. }
  29831. this._buffer._rebuild();
  29832. };
  29833. /**
  29834. * Returns the kind of the VertexBuffer (string).
  29835. */
  29836. VertexBuffer.prototype.getKind = function () {
  29837. return this._kind;
  29838. };
  29839. // Properties
  29840. /**
  29841. * Boolean : is the VertexBuffer updatable ?
  29842. */
  29843. VertexBuffer.prototype.isUpdatable = function () {
  29844. return this._buffer.isUpdatable();
  29845. };
  29846. /**
  29847. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29848. */
  29849. VertexBuffer.prototype.getData = function () {
  29850. return this._buffer.getData();
  29851. };
  29852. /**
  29853. * Returns the WebGLBuffer associated to the VertexBuffer.
  29854. */
  29855. VertexBuffer.prototype.getBuffer = function () {
  29856. return this._buffer.getBuffer();
  29857. };
  29858. /**
  29859. * Returns the stride as a multiple of the type byte length.
  29860. * DEPRECATED. Use byteStride instead.
  29861. */
  29862. VertexBuffer.prototype.getStrideSize = function () {
  29863. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29864. };
  29865. /**
  29866. * Returns the offset as a multiple of the type byte length.
  29867. * DEPRECATED. Use byteOffset instead.
  29868. */
  29869. VertexBuffer.prototype.getOffset = function () {
  29870. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29871. };
  29872. /**
  29873. * Returns the number of components per vertex attribute (integer).
  29874. */
  29875. VertexBuffer.prototype.getSize = function () {
  29876. return this._size;
  29877. };
  29878. /**
  29879. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29880. */
  29881. VertexBuffer.prototype.getIsInstanced = function () {
  29882. return this._instanced;
  29883. };
  29884. /**
  29885. * Returns the instancing divisor, zero for non-instanced (integer).
  29886. */
  29887. VertexBuffer.prototype.getInstanceDivisor = function () {
  29888. return this._instanceDivisor;
  29889. };
  29890. // Methods
  29891. /**
  29892. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29893. * Returns the created WebGLBuffer.
  29894. */
  29895. VertexBuffer.prototype.create = function (data) {
  29896. return this._buffer.create(data);
  29897. };
  29898. /**
  29899. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29900. * This function will create a new buffer if the current one is not updatable
  29901. * Returns the updated WebGLBuffer.
  29902. */
  29903. VertexBuffer.prototype.update = function (data) {
  29904. return this._buffer.update(data);
  29905. };
  29906. /**
  29907. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29908. * Returns the directly updated WebGLBuffer.
  29909. * @param data the new data
  29910. * @param offset the new offset
  29911. * @param useBytes set to true if the offset is in bytes
  29912. */
  29913. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29914. if (useBytes === void 0) { useBytes = false; }
  29915. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29916. };
  29917. /**
  29918. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29919. */
  29920. VertexBuffer.prototype.dispose = function () {
  29921. if (this._ownsBuffer) {
  29922. this._buffer.dispose();
  29923. }
  29924. };
  29925. /**
  29926. * Enumerates each value of this vertex buffer as numbers.
  29927. * @param count the number of values to enumerate
  29928. * @param callback the callback function called for each value
  29929. */
  29930. VertexBuffer.prototype.forEach = function (count, callback) {
  29931. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29932. };
  29933. Object.defineProperty(VertexBuffer, "PositionKind", {
  29934. get: function () {
  29935. return VertexBuffer._PositionKind;
  29936. },
  29937. enumerable: true,
  29938. configurable: true
  29939. });
  29940. Object.defineProperty(VertexBuffer, "NormalKind", {
  29941. get: function () {
  29942. return VertexBuffer._NormalKind;
  29943. },
  29944. enumerable: true,
  29945. configurable: true
  29946. });
  29947. Object.defineProperty(VertexBuffer, "TangentKind", {
  29948. get: function () {
  29949. return VertexBuffer._TangentKind;
  29950. },
  29951. enumerable: true,
  29952. configurable: true
  29953. });
  29954. Object.defineProperty(VertexBuffer, "UVKind", {
  29955. get: function () {
  29956. return VertexBuffer._UVKind;
  29957. },
  29958. enumerable: true,
  29959. configurable: true
  29960. });
  29961. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29962. get: function () {
  29963. return VertexBuffer._UV2Kind;
  29964. },
  29965. enumerable: true,
  29966. configurable: true
  29967. });
  29968. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29969. get: function () {
  29970. return VertexBuffer._UV3Kind;
  29971. },
  29972. enumerable: true,
  29973. configurable: true
  29974. });
  29975. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29976. get: function () {
  29977. return VertexBuffer._UV4Kind;
  29978. },
  29979. enumerable: true,
  29980. configurable: true
  29981. });
  29982. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29983. get: function () {
  29984. return VertexBuffer._UV5Kind;
  29985. },
  29986. enumerable: true,
  29987. configurable: true
  29988. });
  29989. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29990. get: function () {
  29991. return VertexBuffer._UV6Kind;
  29992. },
  29993. enumerable: true,
  29994. configurable: true
  29995. });
  29996. Object.defineProperty(VertexBuffer, "ColorKind", {
  29997. get: function () {
  29998. return VertexBuffer._ColorKind;
  29999. },
  30000. enumerable: true,
  30001. configurable: true
  30002. });
  30003. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  30004. get: function () {
  30005. return VertexBuffer._MatricesIndicesKind;
  30006. },
  30007. enumerable: true,
  30008. configurable: true
  30009. });
  30010. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30011. get: function () {
  30012. return VertexBuffer._MatricesWeightsKind;
  30013. },
  30014. enumerable: true,
  30015. configurable: true
  30016. });
  30017. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30018. get: function () {
  30019. return VertexBuffer._MatricesIndicesExtraKind;
  30020. },
  30021. enumerable: true,
  30022. configurable: true
  30023. });
  30024. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30025. get: function () {
  30026. return VertexBuffer._MatricesWeightsExtraKind;
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. /**
  30032. * Deduces the stride given a kind.
  30033. * @param kind The kind string to deduce
  30034. * @returns The deduced stride
  30035. */
  30036. VertexBuffer.DeduceStride = function (kind) {
  30037. switch (kind) {
  30038. case VertexBuffer.UVKind:
  30039. case VertexBuffer.UV2Kind:
  30040. case VertexBuffer.UV3Kind:
  30041. case VertexBuffer.UV4Kind:
  30042. case VertexBuffer.UV5Kind:
  30043. case VertexBuffer.UV6Kind:
  30044. return 2;
  30045. case VertexBuffer.NormalKind:
  30046. case VertexBuffer.PositionKind:
  30047. return 3;
  30048. case VertexBuffer.ColorKind:
  30049. case VertexBuffer.MatricesIndicesKind:
  30050. case VertexBuffer.MatricesIndicesExtraKind:
  30051. case VertexBuffer.MatricesWeightsKind:
  30052. case VertexBuffer.MatricesWeightsExtraKind:
  30053. case VertexBuffer.TangentKind:
  30054. return 4;
  30055. default:
  30056. throw new Error("Invalid kind '" + kind + "'");
  30057. }
  30058. };
  30059. /**
  30060. * Gets the byte length of the given type.
  30061. * @param type the type
  30062. * @returns the number of bytes
  30063. */
  30064. VertexBuffer.GetTypeByteLength = function (type) {
  30065. switch (type) {
  30066. case VertexBuffer.BYTE:
  30067. case VertexBuffer.UNSIGNED_BYTE:
  30068. return 1;
  30069. case VertexBuffer.SHORT:
  30070. case VertexBuffer.UNSIGNED_SHORT:
  30071. return 2;
  30072. case VertexBuffer.INT:
  30073. case VertexBuffer.FLOAT:
  30074. return 4;
  30075. default:
  30076. throw new Error("Invalid type '" + type + "'");
  30077. }
  30078. };
  30079. /**
  30080. * Enumerates each value of the given parameters as numbers.
  30081. * @param data the data to enumerate
  30082. * @param byteOffset the byte offset of the data
  30083. * @param byteStride the byte stride of the data
  30084. * @param componentCount the number of components per element
  30085. * @param componentType the type of the component
  30086. * @param count the total number of components
  30087. * @param normalized whether the data is normalized
  30088. * @param callback the callback function called for each value
  30089. */
  30090. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30091. if (data instanceof Array) {
  30092. var offset = byteOffset / 4;
  30093. var stride = byteStride / 4;
  30094. for (var index = 0; index < count; index += componentCount) {
  30095. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30096. callback(data[offset + componentIndex], index + componentIndex);
  30097. }
  30098. offset += stride;
  30099. }
  30100. }
  30101. else {
  30102. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30103. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30104. for (var index = 0; index < count; index += componentCount) {
  30105. var componentByteOffset = byteOffset;
  30106. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30107. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30108. callback(value, index + componentIndex);
  30109. componentByteOffset += componentByteLength;
  30110. }
  30111. byteOffset += byteStride;
  30112. }
  30113. }
  30114. };
  30115. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30116. switch (type) {
  30117. case VertexBuffer.BYTE: {
  30118. var value = dataView.getInt8(byteOffset);
  30119. if (normalized) {
  30120. value = Math.max(value / 127, -1);
  30121. }
  30122. return value;
  30123. }
  30124. case VertexBuffer.UNSIGNED_BYTE: {
  30125. var value = dataView.getUint8(byteOffset);
  30126. if (normalized) {
  30127. value = value / 255;
  30128. }
  30129. return value;
  30130. }
  30131. case VertexBuffer.SHORT: {
  30132. var value = dataView.getInt16(byteOffset, true);
  30133. if (normalized) {
  30134. value = Math.max(value / 16383, -1);
  30135. }
  30136. return value;
  30137. }
  30138. case VertexBuffer.UNSIGNED_SHORT: {
  30139. var value = dataView.getUint16(byteOffset, true);
  30140. if (normalized) {
  30141. value = value / 65535;
  30142. }
  30143. return value;
  30144. }
  30145. case VertexBuffer.FLOAT: {
  30146. return dataView.getFloat32(byteOffset, true);
  30147. }
  30148. default: {
  30149. throw new Error("Invalid component type " + type);
  30150. }
  30151. }
  30152. };
  30153. /**
  30154. * The byte type.
  30155. */
  30156. VertexBuffer.BYTE = 5120;
  30157. /**
  30158. * The unsigned byte type.
  30159. */
  30160. VertexBuffer.UNSIGNED_BYTE = 5121;
  30161. /**
  30162. * The short type.
  30163. */
  30164. VertexBuffer.SHORT = 5122;
  30165. /**
  30166. * The unsigned short type.
  30167. */
  30168. VertexBuffer.UNSIGNED_SHORT = 5123;
  30169. /**
  30170. * The integer type.
  30171. */
  30172. VertexBuffer.INT = 5124;
  30173. /**
  30174. * The unsigned integer type.
  30175. */
  30176. VertexBuffer.UNSIGNED_INT = 5125;
  30177. /**
  30178. * The float type.
  30179. */
  30180. VertexBuffer.FLOAT = 5126;
  30181. // Enums
  30182. VertexBuffer._PositionKind = "position";
  30183. VertexBuffer._NormalKind = "normal";
  30184. VertexBuffer._TangentKind = "tangent";
  30185. VertexBuffer._UVKind = "uv";
  30186. VertexBuffer._UV2Kind = "uv2";
  30187. VertexBuffer._UV3Kind = "uv3";
  30188. VertexBuffer._UV4Kind = "uv4";
  30189. VertexBuffer._UV5Kind = "uv5";
  30190. VertexBuffer._UV6Kind = "uv6";
  30191. VertexBuffer._ColorKind = "color";
  30192. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30193. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30194. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30195. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30196. return VertexBuffer;
  30197. }());
  30198. BABYLON.VertexBuffer = VertexBuffer;
  30199. })(BABYLON || (BABYLON = {}));
  30200. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30201. var BABYLON;
  30202. (function (BABYLON) {
  30203. /**
  30204. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30205. */
  30206. var DummyInternalTextureTracker = /** @class */ (function () {
  30207. function DummyInternalTextureTracker() {
  30208. /**
  30209. * Gets or set the previous tracker in the list
  30210. */
  30211. this.previous = null;
  30212. /**
  30213. * Gets or set the next tracker in the list
  30214. */
  30215. this.next = null;
  30216. }
  30217. return DummyInternalTextureTracker;
  30218. }());
  30219. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30220. })(BABYLON || (BABYLON = {}));
  30221. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30222. var BABYLON;
  30223. (function (BABYLON) {
  30224. /**
  30225. * Class used to store data associated with WebGL texture data for the engine
  30226. * This class should not be used directly
  30227. */
  30228. var InternalTexture = /** @class */ (function () {
  30229. /**
  30230. * Creates a new InternalTexture
  30231. * @param engine defines the engine to use
  30232. * @param dataSource defines the type of data that will be used
  30233. */
  30234. function InternalTexture(engine, dataSource) {
  30235. /**
  30236. * Observable called when the texture is loaded
  30237. */
  30238. this.onLoadedObservable = new BABYLON.Observable();
  30239. /**
  30240. * Gets or set the previous tracker in the list
  30241. */
  30242. this.previous = null;
  30243. /**
  30244. * Gets or set the next tracker in the list
  30245. */
  30246. this.next = null;
  30247. // Private
  30248. /** @hidden */
  30249. this._initialSlot = -1;
  30250. /** @hidden */
  30251. this._designatedSlot = -1;
  30252. /** @hidden */
  30253. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30254. /** @hidden */
  30255. this._comparisonFunction = 0;
  30256. /** @hidden */
  30257. this._lodGenerationScale = 0;
  30258. /** @hidden */
  30259. this._lodGenerationOffset = 0;
  30260. /** @hidden */
  30261. this._isRGBD = false;
  30262. /** @hidden */
  30263. this._references = 1;
  30264. this._engine = engine;
  30265. this._dataSource = dataSource;
  30266. this._webGLTexture = engine._createTexture();
  30267. }
  30268. /**
  30269. * Gets the Engine the texture belongs to.
  30270. * @returns The babylon engine
  30271. */
  30272. InternalTexture.prototype.getEngine = function () {
  30273. return this._engine;
  30274. };
  30275. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30276. /**
  30277. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30278. */
  30279. get: function () {
  30280. return this._dataSource;
  30281. },
  30282. enumerable: true,
  30283. configurable: true
  30284. });
  30285. /**
  30286. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30287. */
  30288. InternalTexture.prototype.incrementReferences = function () {
  30289. this._references++;
  30290. };
  30291. /**
  30292. * Change the size of the texture (not the size of the content)
  30293. * @param width defines the new width
  30294. * @param height defines the new height
  30295. * @param depth defines the new depth (1 by default)
  30296. */
  30297. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30298. if (depth === void 0) { depth = 1; }
  30299. this.width = width;
  30300. this.height = height;
  30301. this.depth = depth;
  30302. this.baseWidth = width;
  30303. this.baseHeight = height;
  30304. this.baseDepth = depth;
  30305. this._size = width * height * depth;
  30306. };
  30307. /** @hidden */
  30308. InternalTexture.prototype._rebuild = function () {
  30309. var _this = this;
  30310. var proxy;
  30311. this.isReady = false;
  30312. this._cachedCoordinatesMode = null;
  30313. this._cachedWrapU = null;
  30314. this._cachedWrapV = null;
  30315. this._cachedAnisotropicFilteringLevel = null;
  30316. switch (this._dataSource) {
  30317. case InternalTexture.DATASOURCE_TEMP:
  30318. return;
  30319. case InternalTexture.DATASOURCE_URL:
  30320. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30321. _this.isReady = true;
  30322. }, null, this._buffer, undefined, this.format);
  30323. proxy._swapAndDie(this);
  30324. return;
  30325. case InternalTexture.DATASOURCE_RAW:
  30326. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30327. proxy._swapAndDie(this);
  30328. this.isReady = true;
  30329. return;
  30330. case InternalTexture.DATASOURCE_RAW3D:
  30331. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30332. proxy._swapAndDie(this);
  30333. this.isReady = true;
  30334. return;
  30335. case InternalTexture.DATASOURCE_DYNAMIC:
  30336. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30337. proxy._swapAndDie(this);
  30338. // The engine will make sure to update content so no need to flag it as isReady = true
  30339. return;
  30340. case InternalTexture.DATASOURCE_RENDERTARGET:
  30341. var options = new BABYLON.RenderTargetCreationOptions();
  30342. options.generateDepthBuffer = this._generateDepthBuffer;
  30343. options.generateMipMaps = this.generateMipMaps;
  30344. options.generateStencilBuffer = this._generateStencilBuffer;
  30345. options.samplingMode = this.samplingMode;
  30346. options.type = this.type;
  30347. if (this.isCube) {
  30348. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30349. }
  30350. else {
  30351. var size = {
  30352. width: this.width,
  30353. height: this.height
  30354. };
  30355. proxy = this._engine.createRenderTargetTexture(size, options);
  30356. }
  30357. proxy._swapAndDie(this);
  30358. this.isReady = true;
  30359. return;
  30360. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30361. var depthTextureOptions = {
  30362. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30363. comparisonFunction: this._comparisonFunction,
  30364. generateStencil: this._generateStencilBuffer,
  30365. isCube: this.isCube
  30366. };
  30367. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30368. proxy._swapAndDie(this);
  30369. this.isReady = true;
  30370. return;
  30371. case InternalTexture.DATASOURCE_CUBE:
  30372. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30373. _this.isReady = true;
  30374. }, null, this.format, this._extension);
  30375. proxy._swapAndDie(this);
  30376. return;
  30377. case InternalTexture.DATASOURCE_CUBERAW:
  30378. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30379. proxy._swapAndDie(this);
  30380. this.isReady = true;
  30381. return;
  30382. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30383. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30384. if (proxy) {
  30385. proxy._swapAndDie(_this);
  30386. }
  30387. _this.isReady = true;
  30388. }, null, this.format, this._extension);
  30389. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30390. return;
  30391. }
  30392. };
  30393. InternalTexture.prototype._swapAndDie = function (target) {
  30394. target._webGLTexture = this._webGLTexture;
  30395. if (this._framebuffer) {
  30396. target._framebuffer = this._framebuffer;
  30397. }
  30398. if (this._depthStencilBuffer) {
  30399. target._depthStencilBuffer = this._depthStencilBuffer;
  30400. }
  30401. if (this._lodTextureHigh) {
  30402. if (target._lodTextureHigh) {
  30403. target._lodTextureHigh.dispose();
  30404. }
  30405. target._lodTextureHigh = this._lodTextureHigh;
  30406. }
  30407. if (this._lodTextureMid) {
  30408. if (target._lodTextureMid) {
  30409. target._lodTextureMid.dispose();
  30410. }
  30411. target._lodTextureMid = this._lodTextureMid;
  30412. }
  30413. if (this._lodTextureLow) {
  30414. if (target._lodTextureLow) {
  30415. target._lodTextureLow.dispose();
  30416. }
  30417. target._lodTextureLow = this._lodTextureLow;
  30418. }
  30419. var cache = this._engine.getLoadedTexturesCache();
  30420. var index = cache.indexOf(this);
  30421. if (index !== -1) {
  30422. cache.splice(index, 1);
  30423. }
  30424. };
  30425. /**
  30426. * Dispose the current allocated resources
  30427. */
  30428. InternalTexture.prototype.dispose = function () {
  30429. if (!this._webGLTexture) {
  30430. return;
  30431. }
  30432. this._references--;
  30433. if (this._references === 0) {
  30434. this._engine._releaseTexture(this);
  30435. this._webGLTexture = null;
  30436. this.previous = null;
  30437. this.next = null;
  30438. }
  30439. };
  30440. /**
  30441. * The source of the texture data is unknown
  30442. */
  30443. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30444. /**
  30445. * Texture data comes from an URL
  30446. */
  30447. InternalTexture.DATASOURCE_URL = 1;
  30448. /**
  30449. * Texture data is only used for temporary storage
  30450. */
  30451. InternalTexture.DATASOURCE_TEMP = 2;
  30452. /**
  30453. * Texture data comes from raw data (ArrayBuffer)
  30454. */
  30455. InternalTexture.DATASOURCE_RAW = 3;
  30456. /**
  30457. * Texture content is dynamic (video or dynamic texture)
  30458. */
  30459. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30460. /**
  30461. * Texture content is generated by rendering to it
  30462. */
  30463. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30464. /**
  30465. * Texture content is part of a multi render target process
  30466. */
  30467. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30468. /**
  30469. * Texture data comes from a cube data file
  30470. */
  30471. InternalTexture.DATASOURCE_CUBE = 7;
  30472. /**
  30473. * Texture data comes from a raw cube data
  30474. */
  30475. InternalTexture.DATASOURCE_CUBERAW = 8;
  30476. /**
  30477. * Texture data come from a prefiltered cube data file
  30478. */
  30479. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30480. /**
  30481. * Texture content is raw 3D data
  30482. */
  30483. InternalTexture.DATASOURCE_RAW3D = 10;
  30484. /**
  30485. * Texture content is a depth texture
  30486. */
  30487. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30488. return InternalTexture;
  30489. }());
  30490. BABYLON.InternalTexture = InternalTexture;
  30491. })(BABYLON || (BABYLON = {}));
  30492. //# sourceMappingURL=babylon.internalTexture.js.map
  30493. var BABYLON;
  30494. (function (BABYLON) {
  30495. var BaseTexture = /** @class */ (function () {
  30496. function BaseTexture(scene) {
  30497. this._hasAlpha = false;
  30498. this.getAlphaFromRGB = false;
  30499. this.level = 1;
  30500. this.coordinatesIndex = 0;
  30501. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30502. /**
  30503. * | Value | Type | Description |
  30504. * | ----- | ------------------ | ----------- |
  30505. * | 0 | CLAMP_ADDRESSMODE | |
  30506. * | 1 | WRAP_ADDRESSMODE | |
  30507. * | 2 | MIRROR_ADDRESSMODE | |
  30508. */
  30509. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30510. /**
  30511. * | Value | Type | Description |
  30512. * | ----- | ------------------ | ----------- |
  30513. * | 0 | CLAMP_ADDRESSMODE | |
  30514. * | 1 | WRAP_ADDRESSMODE | |
  30515. * | 2 | MIRROR_ADDRESSMODE | |
  30516. */
  30517. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30518. /**
  30519. * | Value | Type | Description |
  30520. * | ----- | ------------------ | ----------- |
  30521. * | 0 | CLAMP_ADDRESSMODE | |
  30522. * | 1 | WRAP_ADDRESSMODE | |
  30523. * | 2 | MIRROR_ADDRESSMODE | |
  30524. */
  30525. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30526. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30527. this.isCube = false;
  30528. this.is3D = false;
  30529. this.gammaSpace = true;
  30530. this.invertZ = false;
  30531. this.lodLevelInAlpha = false;
  30532. this.isRenderTarget = false;
  30533. this.animations = new Array();
  30534. /**
  30535. * An event triggered when the texture is disposed.
  30536. */
  30537. this.onDisposeObservable = new BABYLON.Observable();
  30538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30539. this._cachedSize = BABYLON.Size.Zero();
  30540. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30541. if (this._scene) {
  30542. this._scene.textures.push(this);
  30543. }
  30544. this._uid = null;
  30545. }
  30546. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30547. get: function () {
  30548. return this._hasAlpha;
  30549. },
  30550. set: function (value) {
  30551. if (this._hasAlpha === value) {
  30552. return;
  30553. }
  30554. this._hasAlpha = value;
  30555. if (this._scene) {
  30556. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30557. }
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30563. get: function () {
  30564. return this._coordinatesMode;
  30565. },
  30566. /**
  30567. * How a texture is mapped.
  30568. *
  30569. * | Value | Type | Description |
  30570. * | ----- | ----------------------------------- | ----------- |
  30571. * | 0 | EXPLICIT_MODE | |
  30572. * | 1 | SPHERICAL_MODE | |
  30573. * | 2 | PLANAR_MODE | |
  30574. * | 3 | CUBIC_MODE | |
  30575. * | 4 | PROJECTION_MODE | |
  30576. * | 5 | SKYBOX_MODE | |
  30577. * | 6 | INVCUBIC_MODE | |
  30578. * | 7 | EQUIRECTANGULAR_MODE | |
  30579. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30580. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30581. */
  30582. set: function (value) {
  30583. if (this._coordinatesMode === value) {
  30584. return;
  30585. }
  30586. this._coordinatesMode = value;
  30587. if (this._scene) {
  30588. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30589. }
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30595. /**
  30596. * Gets whether or not the texture contains RGBD data.
  30597. */
  30598. get: function () {
  30599. return this._texture != null && this._texture._isRGBD;
  30600. },
  30601. enumerable: true,
  30602. configurable: true
  30603. });
  30604. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30605. get: function () {
  30606. if (this._texture)
  30607. return this._texture._lodGenerationOffset;
  30608. return 0.0;
  30609. },
  30610. set: function (value) {
  30611. if (this._texture)
  30612. this._texture._lodGenerationOffset = value;
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30618. get: function () {
  30619. if (this._texture)
  30620. return this._texture._lodGenerationScale;
  30621. return 0.0;
  30622. },
  30623. set: function (value) {
  30624. if (this._texture)
  30625. this._texture._lodGenerationScale = value;
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. Object.defineProperty(BaseTexture.prototype, "uid", {
  30631. get: function () {
  30632. if (!this._uid) {
  30633. this._uid = BABYLON.Tools.RandomId();
  30634. }
  30635. return this._uid;
  30636. },
  30637. enumerable: true,
  30638. configurable: true
  30639. });
  30640. BaseTexture.prototype.toString = function () {
  30641. return this.name;
  30642. };
  30643. BaseTexture.prototype.getClassName = function () {
  30644. return "BaseTexture";
  30645. };
  30646. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30647. set: function (callback) {
  30648. if (this._onDisposeObserver) {
  30649. this.onDisposeObservable.remove(this._onDisposeObserver);
  30650. }
  30651. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30657. get: function () {
  30658. return true;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. BaseTexture.prototype.getScene = function () {
  30664. return this._scene;
  30665. };
  30666. BaseTexture.prototype.getTextureMatrix = function () {
  30667. return BABYLON.Matrix.IdentityReadOnly;
  30668. };
  30669. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30670. return BABYLON.Matrix.IdentityReadOnly;
  30671. };
  30672. BaseTexture.prototype.getInternalTexture = function () {
  30673. return this._texture;
  30674. };
  30675. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30676. return !this.isBlocking || this.isReady();
  30677. };
  30678. BaseTexture.prototype.isReady = function () {
  30679. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30680. this.delayLoad();
  30681. return false;
  30682. }
  30683. if (this._texture) {
  30684. return this._texture.isReady;
  30685. }
  30686. return false;
  30687. };
  30688. BaseTexture.prototype.getSize = function () {
  30689. if (this._texture) {
  30690. if (this._texture.width) {
  30691. this._cachedSize.width = this._texture.width;
  30692. this._cachedSize.height = this._texture.height;
  30693. return this._cachedSize;
  30694. }
  30695. if (this._texture._size) {
  30696. this._cachedSize.width = this._texture._size;
  30697. this._cachedSize.height = this._texture._size;
  30698. return this._cachedSize;
  30699. }
  30700. }
  30701. return this._cachedSize;
  30702. };
  30703. BaseTexture.prototype.getBaseSize = function () {
  30704. if (!this.isReady() || !this._texture)
  30705. return BABYLON.Size.Zero();
  30706. if (this._texture._size) {
  30707. return new BABYLON.Size(this._texture._size, this._texture._size);
  30708. }
  30709. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30710. };
  30711. BaseTexture.prototype.scale = function (ratio) {
  30712. };
  30713. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30714. get: function () {
  30715. return false;
  30716. },
  30717. enumerable: true,
  30718. configurable: true
  30719. });
  30720. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30721. if (!this._scene) {
  30722. return null;
  30723. }
  30724. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30725. for (var index = 0; index < texturesCache.length; index++) {
  30726. var texturesCacheEntry = texturesCache[index];
  30727. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30728. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30729. texturesCacheEntry.incrementReferences();
  30730. return texturesCacheEntry;
  30731. }
  30732. }
  30733. }
  30734. return null;
  30735. };
  30736. BaseTexture.prototype._rebuild = function () {
  30737. };
  30738. BaseTexture.prototype.delayLoad = function () {
  30739. };
  30740. BaseTexture.prototype.clone = function () {
  30741. return null;
  30742. };
  30743. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30744. get: function () {
  30745. if (!this._texture) {
  30746. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30747. }
  30748. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30749. },
  30750. enumerable: true,
  30751. configurable: true
  30752. });
  30753. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30754. get: function () {
  30755. if (!this._texture) {
  30756. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30757. }
  30758. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30759. },
  30760. enumerable: true,
  30761. configurable: true
  30762. });
  30763. /**
  30764. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30765. * This will returns an RGBA array buffer containing either in values (0-255) or
  30766. * float values (0-1) depending of the underlying buffer type.
  30767. * @param faceIndex The face of the texture to read (in case of cube texture)
  30768. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30769. * @returns The Array buffer containing the pixels data.
  30770. */
  30771. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30772. if (faceIndex === void 0) { faceIndex = 0; }
  30773. if (level === void 0) { level = 0; }
  30774. if (!this._texture) {
  30775. return null;
  30776. }
  30777. var size = this.getSize();
  30778. var width = size.width;
  30779. var height = size.height;
  30780. var scene = this.getScene();
  30781. if (!scene) {
  30782. return null;
  30783. }
  30784. var engine = scene.getEngine();
  30785. if (level != 0) {
  30786. width = width / Math.pow(2, level);
  30787. height = height / Math.pow(2, level);
  30788. width = Math.round(width);
  30789. height = Math.round(height);
  30790. }
  30791. if (this._texture.isCube) {
  30792. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30793. }
  30794. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30795. };
  30796. BaseTexture.prototype.releaseInternalTexture = function () {
  30797. if (this._texture) {
  30798. this._texture.dispose();
  30799. this._texture = null;
  30800. }
  30801. };
  30802. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30803. get: function () {
  30804. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30805. return null;
  30806. }
  30807. if (!this._texture._sphericalPolynomial) {
  30808. this._texture._sphericalPolynomial =
  30809. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30810. }
  30811. return this._texture._sphericalPolynomial;
  30812. },
  30813. set: function (value) {
  30814. if (this._texture) {
  30815. this._texture._sphericalPolynomial = value;
  30816. }
  30817. },
  30818. enumerable: true,
  30819. configurable: true
  30820. });
  30821. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30822. get: function () {
  30823. if (this._texture) {
  30824. return this._texture._lodTextureHigh;
  30825. }
  30826. return null;
  30827. },
  30828. enumerable: true,
  30829. configurable: true
  30830. });
  30831. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30832. get: function () {
  30833. if (this._texture) {
  30834. return this._texture._lodTextureMid;
  30835. }
  30836. return null;
  30837. },
  30838. enumerable: true,
  30839. configurable: true
  30840. });
  30841. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30842. get: function () {
  30843. if (this._texture) {
  30844. return this._texture._lodTextureLow;
  30845. }
  30846. return null;
  30847. },
  30848. enumerable: true,
  30849. configurable: true
  30850. });
  30851. BaseTexture.prototype.dispose = function () {
  30852. if (!this._scene) {
  30853. return;
  30854. }
  30855. // Animations
  30856. this._scene.stopAnimation(this);
  30857. // Remove from scene
  30858. this._scene._removePendingData(this);
  30859. var index = this._scene.textures.indexOf(this);
  30860. if (index >= 0) {
  30861. this._scene.textures.splice(index, 1);
  30862. }
  30863. if (this._texture === undefined) {
  30864. return;
  30865. }
  30866. // Release
  30867. this.releaseInternalTexture();
  30868. // Callback
  30869. this.onDisposeObservable.notifyObservers(this);
  30870. this.onDisposeObservable.clear();
  30871. };
  30872. BaseTexture.prototype.serialize = function () {
  30873. if (!this.name) {
  30874. return null;
  30875. }
  30876. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30877. // Animations
  30878. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30879. return serializationObject;
  30880. };
  30881. BaseTexture.WhenAllReady = function (textures, callback) {
  30882. var numRemaining = textures.length;
  30883. if (numRemaining === 0) {
  30884. callback();
  30885. return;
  30886. }
  30887. var _loop_1 = function () {
  30888. texture = textures[i];
  30889. if (texture.isReady()) {
  30890. if (--numRemaining === 0) {
  30891. callback();
  30892. }
  30893. }
  30894. else {
  30895. onLoadObservable = texture.onLoadObservable;
  30896. var onLoadCallback_1 = function () {
  30897. onLoadObservable.removeCallback(onLoadCallback_1);
  30898. if (--numRemaining === 0) {
  30899. callback();
  30900. }
  30901. };
  30902. onLoadObservable.add(onLoadCallback_1);
  30903. }
  30904. };
  30905. var texture, onLoadObservable;
  30906. for (var i = 0; i < textures.length; i++) {
  30907. _loop_1();
  30908. }
  30909. };
  30910. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30911. __decorate([
  30912. BABYLON.serialize()
  30913. ], BaseTexture.prototype, "name", void 0);
  30914. __decorate([
  30915. BABYLON.serialize("hasAlpha")
  30916. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30917. __decorate([
  30918. BABYLON.serialize()
  30919. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30920. __decorate([
  30921. BABYLON.serialize()
  30922. ], BaseTexture.prototype, "level", void 0);
  30923. __decorate([
  30924. BABYLON.serialize()
  30925. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30926. __decorate([
  30927. BABYLON.serialize("coordinatesMode")
  30928. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30929. __decorate([
  30930. BABYLON.serialize()
  30931. ], BaseTexture.prototype, "wrapU", void 0);
  30932. __decorate([
  30933. BABYLON.serialize()
  30934. ], BaseTexture.prototype, "wrapV", void 0);
  30935. __decorate([
  30936. BABYLON.serialize()
  30937. ], BaseTexture.prototype, "wrapR", void 0);
  30938. __decorate([
  30939. BABYLON.serialize()
  30940. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30941. __decorate([
  30942. BABYLON.serialize()
  30943. ], BaseTexture.prototype, "isCube", void 0);
  30944. __decorate([
  30945. BABYLON.serialize()
  30946. ], BaseTexture.prototype, "is3D", void 0);
  30947. __decorate([
  30948. BABYLON.serialize()
  30949. ], BaseTexture.prototype, "gammaSpace", void 0);
  30950. __decorate([
  30951. BABYLON.serialize()
  30952. ], BaseTexture.prototype, "invertZ", void 0);
  30953. __decorate([
  30954. BABYLON.serialize()
  30955. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30956. __decorate([
  30957. BABYLON.serialize()
  30958. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30959. __decorate([
  30960. BABYLON.serialize()
  30961. ], BaseTexture.prototype, "lodGenerationScale", null);
  30962. __decorate([
  30963. BABYLON.serialize()
  30964. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30965. return BaseTexture;
  30966. }());
  30967. BABYLON.BaseTexture = BaseTexture;
  30968. })(BABYLON || (BABYLON = {}));
  30969. //# sourceMappingURL=babylon.baseTexture.js.map
  30970. var BABYLON;
  30971. (function (BABYLON) {
  30972. var Texture = /** @class */ (function (_super) {
  30973. __extends(Texture, _super);
  30974. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30975. if (noMipmap === void 0) { noMipmap = false; }
  30976. if (invertY === void 0) { invertY = true; }
  30977. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30978. if (onLoad === void 0) { onLoad = null; }
  30979. if (onError === void 0) { onError = null; }
  30980. if (buffer === void 0) { buffer = null; }
  30981. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30982. var _this = _super.call(this, scene) || this;
  30983. _this.uOffset = 0;
  30984. _this.vOffset = 0;
  30985. _this.uScale = 1.0;
  30986. _this.vScale = 1.0;
  30987. _this.uAng = 0;
  30988. _this.vAng = 0;
  30989. _this.wAng = 0;
  30990. /**
  30991. * Defines the center of rotation (U)
  30992. */
  30993. _this.uRotationCenter = 0.5;
  30994. /**
  30995. * Defines the center of rotation (V)
  30996. */
  30997. _this.vRotationCenter = 0.5;
  30998. /**
  30999. * Defines the center of rotation (W)
  31000. */
  31001. _this.wRotationCenter = 0.5;
  31002. _this._isBlocking = true;
  31003. _this.name = url || "";
  31004. _this.url = url;
  31005. _this._noMipmap = noMipmap;
  31006. _this._invertY = invertY;
  31007. _this._samplingMode = samplingMode;
  31008. _this._buffer = buffer;
  31009. _this._deleteBuffer = deleteBuffer;
  31010. if (format) {
  31011. _this._format = format;
  31012. }
  31013. scene = _this.getScene();
  31014. if (!scene) {
  31015. return _this;
  31016. }
  31017. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31018. var load = function () {
  31019. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31020. _this.onLoadObservable.notifyObservers(_this);
  31021. }
  31022. if (onLoad) {
  31023. onLoad();
  31024. }
  31025. if (!_this.isBlocking && scene) {
  31026. scene.resetCachedMaterial();
  31027. }
  31028. };
  31029. if (!_this.url) {
  31030. _this._delayedOnLoad = load;
  31031. _this._delayedOnError = onError;
  31032. return _this;
  31033. }
  31034. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31035. if (!_this._texture) {
  31036. if (!scene.useDelayedTextureLoading) {
  31037. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31038. if (deleteBuffer) {
  31039. delete _this._buffer;
  31040. }
  31041. }
  31042. else {
  31043. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31044. _this._delayedOnLoad = load;
  31045. _this._delayedOnError = onError;
  31046. }
  31047. }
  31048. else {
  31049. if (_this._texture.isReady) {
  31050. BABYLON.Tools.SetImmediate(function () { return load(); });
  31051. }
  31052. else {
  31053. _this._texture.onLoadedObservable.add(load);
  31054. }
  31055. }
  31056. return _this;
  31057. }
  31058. Object.defineProperty(Texture.prototype, "noMipmap", {
  31059. get: function () {
  31060. return this._noMipmap;
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Texture.prototype, "isBlocking", {
  31066. get: function () {
  31067. return this._isBlocking;
  31068. },
  31069. set: function (value) {
  31070. this._isBlocking = value;
  31071. },
  31072. enumerable: true,
  31073. configurable: true
  31074. });
  31075. Object.defineProperty(Texture.prototype, "samplingMode", {
  31076. get: function () {
  31077. return this._samplingMode;
  31078. },
  31079. enumerable: true,
  31080. configurable: true
  31081. });
  31082. /**
  31083. * Update the url (and optional buffer) of this texture if url was null during construction.
  31084. * @param url the url of the texture
  31085. * @param buffer the buffer of the texture (defaults to null)
  31086. */
  31087. Texture.prototype.updateURL = function (url, buffer) {
  31088. if (buffer === void 0) { buffer = null; }
  31089. if (this.url) {
  31090. throw new Error("URL is already set");
  31091. }
  31092. this.url = url;
  31093. this._buffer = buffer;
  31094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31095. this.delayLoad();
  31096. };
  31097. Texture.prototype.delayLoad = function () {
  31098. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31099. return;
  31100. }
  31101. var scene = this.getScene();
  31102. if (!scene) {
  31103. return;
  31104. }
  31105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31106. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31107. if (!this._texture) {
  31108. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31109. if (this._deleteBuffer) {
  31110. delete this._buffer;
  31111. }
  31112. }
  31113. else {
  31114. if (this._delayedOnLoad) {
  31115. if (this._texture.isReady) {
  31116. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31117. }
  31118. else {
  31119. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31120. }
  31121. }
  31122. }
  31123. this._delayedOnLoad = null;
  31124. this._delayedOnError = null;
  31125. };
  31126. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31127. if (!this._texture) {
  31128. return;
  31129. }
  31130. var scene = this.getScene();
  31131. if (!scene) {
  31132. return;
  31133. }
  31134. this._samplingMode = samplingMode;
  31135. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31136. };
  31137. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31138. x *= this.uScale;
  31139. y *= this.vScale;
  31140. x -= this.uRotationCenter * this.uScale;
  31141. y -= this.vRotationCenter * this.vScale;
  31142. z -= this.wRotationCenter;
  31143. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31144. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31145. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31146. t.z += this.wRotationCenter;
  31147. };
  31148. Texture.prototype.getTextureMatrix = function () {
  31149. var _this = this;
  31150. if (this.uOffset === this._cachedUOffset &&
  31151. this.vOffset === this._cachedVOffset &&
  31152. this.uScale === this._cachedUScale &&
  31153. this.vScale === this._cachedVScale &&
  31154. this.uAng === this._cachedUAng &&
  31155. this.vAng === this._cachedVAng &&
  31156. this.wAng === this._cachedWAng) {
  31157. return this._cachedTextureMatrix;
  31158. }
  31159. this._cachedUOffset = this.uOffset;
  31160. this._cachedVOffset = this.vOffset;
  31161. this._cachedUScale = this.uScale;
  31162. this._cachedVScale = this.vScale;
  31163. this._cachedUAng = this.uAng;
  31164. this._cachedVAng = this.vAng;
  31165. this._cachedWAng = this.wAng;
  31166. if (!this._cachedTextureMatrix) {
  31167. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31168. this._rowGenerationMatrix = new BABYLON.Matrix();
  31169. this._t0 = BABYLON.Vector3.Zero();
  31170. this._t1 = BABYLON.Vector3.Zero();
  31171. this._t2 = BABYLON.Vector3.Zero();
  31172. }
  31173. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31174. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31175. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31176. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31177. this._t1.subtractInPlace(this._t0);
  31178. this._t2.subtractInPlace(this._t0);
  31179. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31180. this._cachedTextureMatrix.m[0] = this._t1.x;
  31181. this._cachedTextureMatrix.m[1] = this._t1.y;
  31182. this._cachedTextureMatrix.m[2] = this._t1.z;
  31183. this._cachedTextureMatrix.m[4] = this._t2.x;
  31184. this._cachedTextureMatrix.m[5] = this._t2.y;
  31185. this._cachedTextureMatrix.m[6] = this._t2.z;
  31186. this._cachedTextureMatrix.m[8] = this._t0.x;
  31187. this._cachedTextureMatrix.m[9] = this._t0.y;
  31188. this._cachedTextureMatrix.m[10] = this._t0.z;
  31189. var scene = this.getScene();
  31190. if (!scene) {
  31191. return this._cachedTextureMatrix;
  31192. }
  31193. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31194. return mat.hasTexture(_this);
  31195. });
  31196. return this._cachedTextureMatrix;
  31197. };
  31198. Texture.prototype.getReflectionTextureMatrix = function () {
  31199. var _this = this;
  31200. var scene = this.getScene();
  31201. if (!scene) {
  31202. return this._cachedTextureMatrix;
  31203. }
  31204. if (this.uOffset === this._cachedUOffset &&
  31205. this.vOffset === this._cachedVOffset &&
  31206. this.uScale === this._cachedUScale &&
  31207. this.vScale === this._cachedVScale &&
  31208. this.coordinatesMode === this._cachedCoordinatesMode) {
  31209. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31210. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31211. return this._cachedTextureMatrix;
  31212. }
  31213. }
  31214. else {
  31215. return this._cachedTextureMatrix;
  31216. }
  31217. }
  31218. if (!this._cachedTextureMatrix) {
  31219. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31220. }
  31221. if (!this._projectionModeMatrix) {
  31222. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31223. }
  31224. this._cachedUOffset = this.uOffset;
  31225. this._cachedVOffset = this.vOffset;
  31226. this._cachedUScale = this.uScale;
  31227. this._cachedVScale = this.vScale;
  31228. this._cachedCoordinatesMode = this.coordinatesMode;
  31229. switch (this.coordinatesMode) {
  31230. case Texture.PLANAR_MODE:
  31231. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31232. this._cachedTextureMatrix[0] = this.uScale;
  31233. this._cachedTextureMatrix[5] = this.vScale;
  31234. this._cachedTextureMatrix[12] = this.uOffset;
  31235. this._cachedTextureMatrix[13] = this.vOffset;
  31236. break;
  31237. case Texture.PROJECTION_MODE:
  31238. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31239. this._projectionModeMatrix.m[0] = 0.5;
  31240. this._projectionModeMatrix.m[5] = -0.5;
  31241. this._projectionModeMatrix.m[10] = 0.0;
  31242. this._projectionModeMatrix.m[12] = 0.5;
  31243. this._projectionModeMatrix.m[13] = 0.5;
  31244. this._projectionModeMatrix.m[14] = 1.0;
  31245. this._projectionModeMatrix.m[15] = 1.0;
  31246. var projectionMatrix = scene.getProjectionMatrix();
  31247. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31248. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31249. break;
  31250. default:
  31251. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31252. break;
  31253. }
  31254. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31255. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31256. });
  31257. return this._cachedTextureMatrix;
  31258. };
  31259. Texture.prototype.clone = function () {
  31260. var _this = this;
  31261. return BABYLON.SerializationHelper.Clone(function () {
  31262. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31263. }, this);
  31264. };
  31265. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31266. get: function () {
  31267. if (!this._onLoadObservable) {
  31268. this._onLoadObservable = new BABYLON.Observable();
  31269. }
  31270. return this._onLoadObservable;
  31271. },
  31272. enumerable: true,
  31273. configurable: true
  31274. });
  31275. Texture.prototype.serialize = function () {
  31276. var serializationObject = _super.prototype.serialize.call(this);
  31277. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31278. serializationObject.base64String = this._buffer;
  31279. serializationObject.name = serializationObject.name.replace("data:", "");
  31280. }
  31281. serializationObject.invertY = this._invertY;
  31282. serializationObject.samplingMode = this.samplingMode;
  31283. return serializationObject;
  31284. };
  31285. Texture.prototype.getClassName = function () {
  31286. return "Texture";
  31287. };
  31288. Texture.prototype.dispose = function () {
  31289. _super.prototype.dispose.call(this);
  31290. if (this._onLoadObservable) {
  31291. this._onLoadObservable.clear();
  31292. this._onLoadObservable = null;
  31293. }
  31294. this._delayedOnLoad = null;
  31295. this._delayedOnError = null;
  31296. };
  31297. // Statics
  31298. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31299. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31300. if (onLoad === void 0) { onLoad = null; }
  31301. if (onError === void 0) { onError = null; }
  31302. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31303. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31304. };
  31305. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31306. if (parsedTexture.customType) {
  31307. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31308. // Update Sampling Mode
  31309. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31310. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31311. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31312. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31313. }
  31314. }
  31315. return parsedCustomTexture;
  31316. }
  31317. if (parsedTexture.isCube) {
  31318. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31319. }
  31320. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31321. return null;
  31322. }
  31323. var texture = BABYLON.SerializationHelper.Parse(function () {
  31324. var generateMipMaps = true;
  31325. if (parsedTexture.noMipmap) {
  31326. generateMipMaps = false;
  31327. }
  31328. if (parsedTexture.mirrorPlane) {
  31329. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31330. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31331. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31332. return mirrorTexture;
  31333. }
  31334. else if (parsedTexture.isRenderTarget) {
  31335. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31336. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31337. return renderTargetTexture;
  31338. }
  31339. else {
  31340. var texture;
  31341. if (parsedTexture.base64String) {
  31342. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31343. }
  31344. else {
  31345. var url = rootUrl + parsedTexture.name;
  31346. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31347. url = parsedTexture.url;
  31348. }
  31349. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31350. }
  31351. return texture;
  31352. }
  31353. }, parsedTexture, scene);
  31354. // Update Sampling Mode
  31355. if (parsedTexture.samplingMode) {
  31356. var sampling = parsedTexture.samplingMode;
  31357. if (texture._samplingMode !== sampling) {
  31358. texture.updateSamplingMode(sampling);
  31359. }
  31360. }
  31361. // Animations
  31362. if (parsedTexture.animations) {
  31363. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31364. var parsedAnimation = parsedTexture.animations[animationIndex];
  31365. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31366. }
  31367. }
  31368. return texture;
  31369. };
  31370. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31371. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31372. if (noMipmap === void 0) { noMipmap = false; }
  31373. if (invertY === void 0) { invertY = true; }
  31374. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31375. if (onLoad === void 0) { onLoad = null; }
  31376. if (onError === void 0) { onError = null; }
  31377. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31378. if (name.substr(0, 5) !== "data:") {
  31379. name = "data:" + name;
  31380. }
  31381. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31382. };
  31383. // Constants
  31384. Texture.NEAREST_SAMPLINGMODE = 1;
  31385. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31386. Texture.BILINEAR_SAMPLINGMODE = 2;
  31387. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31388. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31389. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31390. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31391. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31392. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31393. Texture.NEAREST_LINEAR = 7;
  31394. Texture.NEAREST_NEAREST = 8;
  31395. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31396. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31397. Texture.LINEAR_LINEAR = 11;
  31398. Texture.LINEAR_NEAREST = 12;
  31399. Texture.EXPLICIT_MODE = 0;
  31400. Texture.SPHERICAL_MODE = 1;
  31401. Texture.PLANAR_MODE = 2;
  31402. Texture.CUBIC_MODE = 3;
  31403. Texture.PROJECTION_MODE = 4;
  31404. Texture.SKYBOX_MODE = 5;
  31405. Texture.INVCUBIC_MODE = 6;
  31406. Texture.EQUIRECTANGULAR_MODE = 7;
  31407. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31408. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31409. Texture.CLAMP_ADDRESSMODE = 0;
  31410. Texture.WRAP_ADDRESSMODE = 1;
  31411. Texture.MIRROR_ADDRESSMODE = 2;
  31412. /**
  31413. * 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
  31414. */
  31415. Texture.UseSerializedUrlIfAny = false;
  31416. __decorate([
  31417. BABYLON.serialize()
  31418. ], Texture.prototype, "url", void 0);
  31419. __decorate([
  31420. BABYLON.serialize()
  31421. ], Texture.prototype, "uOffset", void 0);
  31422. __decorate([
  31423. BABYLON.serialize()
  31424. ], Texture.prototype, "vOffset", void 0);
  31425. __decorate([
  31426. BABYLON.serialize()
  31427. ], Texture.prototype, "uScale", void 0);
  31428. __decorate([
  31429. BABYLON.serialize()
  31430. ], Texture.prototype, "vScale", void 0);
  31431. __decorate([
  31432. BABYLON.serialize()
  31433. ], Texture.prototype, "uAng", void 0);
  31434. __decorate([
  31435. BABYLON.serialize()
  31436. ], Texture.prototype, "vAng", void 0);
  31437. __decorate([
  31438. BABYLON.serialize()
  31439. ], Texture.prototype, "wAng", void 0);
  31440. __decorate([
  31441. BABYLON.serialize()
  31442. ], Texture.prototype, "uRotationCenter", void 0);
  31443. __decorate([
  31444. BABYLON.serialize()
  31445. ], Texture.prototype, "vRotationCenter", void 0);
  31446. __decorate([
  31447. BABYLON.serialize()
  31448. ], Texture.prototype, "wRotationCenter", void 0);
  31449. __decorate([
  31450. BABYLON.serialize()
  31451. ], Texture.prototype, "isBlocking", null);
  31452. return Texture;
  31453. }(BABYLON.BaseTexture));
  31454. BABYLON.Texture = Texture;
  31455. })(BABYLON || (BABYLON = {}));
  31456. //# sourceMappingURL=babylon.texture.js.map
  31457. var BABYLON;
  31458. (function (BABYLON) {
  31459. /**
  31460. * @hidden
  31461. **/
  31462. var _InstancesBatch = /** @class */ (function () {
  31463. function _InstancesBatch() {
  31464. this.mustReturn = false;
  31465. this.visibleInstances = new Array();
  31466. this.renderSelf = new Array();
  31467. }
  31468. return _InstancesBatch;
  31469. }());
  31470. BABYLON._InstancesBatch = _InstancesBatch;
  31471. var Mesh = /** @class */ (function (_super) {
  31472. __extends(Mesh, _super);
  31473. /**
  31474. * @constructor
  31475. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31476. * @param {Scene} scene The scene to add this mesh to.
  31477. * @param {Node} parent The parent of this mesh, if it has one
  31478. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31479. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31480. * When false, achieved by calling a clone(), also passing False.
  31481. * This will make creation of children, recursive.
  31482. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31483. */
  31484. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31485. if (scene === void 0) { scene = null; }
  31486. if (parent === void 0) { parent = null; }
  31487. if (source === void 0) { source = null; }
  31488. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31489. var _this = _super.call(this, name, scene) || this;
  31490. // Events
  31491. /**
  31492. * An event triggered before rendering the mesh
  31493. */
  31494. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31495. /**
  31496. * An event triggered after rendering the mesh
  31497. */
  31498. _this.onAfterRenderObservable = new BABYLON.Observable();
  31499. /**
  31500. * An event triggered before drawing the mesh
  31501. */
  31502. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31503. // Members
  31504. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31505. _this.instances = new Array();
  31506. _this._LODLevels = new Array();
  31507. _this._visibleInstances = {};
  31508. _this._renderIdForInstances = new Array();
  31509. _this._batchCache = new _InstancesBatch();
  31510. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31511. // Use by builder only to know what orientation were the mesh build in.
  31512. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31513. _this.overrideMaterialSideOrientation = null;
  31514. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31515. // Will be used to save a source mesh reference, If any
  31516. _this._source = null;
  31517. scene = _this.getScene();
  31518. if (source) {
  31519. // Geometry
  31520. if (source._geometry) {
  31521. source._geometry.applyToMesh(_this);
  31522. }
  31523. // Deep copy
  31524. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31525. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31526. // Source mesh
  31527. _this._source = source;
  31528. // Metadata
  31529. if (source.metadata && source.metadata.clone) {
  31530. _this.metadata = source.metadata.clone();
  31531. }
  31532. else {
  31533. _this.metadata = source.metadata;
  31534. }
  31535. // Tags
  31536. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31537. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31538. }
  31539. // Parent
  31540. _this.parent = source.parent;
  31541. // Pivot
  31542. _this.setPivotMatrix(source.getPivotMatrix());
  31543. _this.id = name + "." + source.id;
  31544. // Material
  31545. _this.material = source.material;
  31546. var index;
  31547. if (!doNotCloneChildren) {
  31548. // Children
  31549. var directDescendants = source.getDescendants(true);
  31550. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31551. var child = directDescendants[index_1];
  31552. if (child.clone) {
  31553. child.clone(name + "." + child.name, _this);
  31554. }
  31555. }
  31556. }
  31557. // Physics clone
  31558. var physicsEngine = _this.getScene().getPhysicsEngine();
  31559. if (clonePhysicsImpostor && physicsEngine) {
  31560. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31561. if (impostor) {
  31562. _this.physicsImpostor = impostor.clone(_this);
  31563. }
  31564. }
  31565. // Particles
  31566. for (index = 0; index < scene.particleSystems.length; index++) {
  31567. var system = scene.particleSystems[index];
  31568. if (system.emitter === source) {
  31569. system.clone(system.name, _this);
  31570. }
  31571. }
  31572. _this.refreshBoundingInfo();
  31573. _this.computeWorldMatrix(true);
  31574. }
  31575. // Parent
  31576. if (parent !== null) {
  31577. _this.parent = parent;
  31578. }
  31579. return _this;
  31580. }
  31581. Object.defineProperty(Mesh, "FRONTSIDE", {
  31582. /**
  31583. * Mesh side orientation : usually the external or front surface
  31584. */
  31585. get: function () {
  31586. return Mesh._FRONTSIDE;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Mesh, "BACKSIDE", {
  31592. /**
  31593. * Mesh side orientation : usually the internal or back surface
  31594. */
  31595. get: function () {
  31596. return Mesh._BACKSIDE;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31602. /**
  31603. * Mesh side orientation : both internal and external or front and back surfaces
  31604. */
  31605. get: function () {
  31606. return Mesh._DOUBLESIDE;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31612. /**
  31613. * Mesh side orientation : by default, `FRONTSIDE`
  31614. */
  31615. get: function () {
  31616. return Mesh._DEFAULTSIDE;
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(Mesh, "NO_CAP", {
  31622. /**
  31623. * Mesh cap setting : no cap
  31624. */
  31625. get: function () {
  31626. return Mesh._NO_CAP;
  31627. },
  31628. enumerable: true,
  31629. configurable: true
  31630. });
  31631. Object.defineProperty(Mesh, "CAP_START", {
  31632. /**
  31633. * Mesh cap setting : one cap at the beginning of the mesh
  31634. */
  31635. get: function () {
  31636. return Mesh._CAP_START;
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(Mesh, "CAP_END", {
  31642. /**
  31643. * Mesh cap setting : one cap at the end of the mesh
  31644. */
  31645. get: function () {
  31646. return Mesh._CAP_END;
  31647. },
  31648. enumerable: true,
  31649. configurable: true
  31650. });
  31651. Object.defineProperty(Mesh, "CAP_ALL", {
  31652. /**
  31653. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31654. */
  31655. get: function () {
  31656. return Mesh._CAP_ALL;
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31662. set: function (callback) {
  31663. if (this._onBeforeDrawObserver) {
  31664. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31665. }
  31666. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31667. },
  31668. enumerable: true,
  31669. configurable: true
  31670. });
  31671. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31672. get: function () {
  31673. return this._morphTargetManager;
  31674. },
  31675. set: function (value) {
  31676. if (this._morphTargetManager === value) {
  31677. return;
  31678. }
  31679. this._morphTargetManager = value;
  31680. this._syncGeometryWithMorphTargetManager();
  31681. },
  31682. enumerable: true,
  31683. configurable: true
  31684. });
  31685. Object.defineProperty(Mesh.prototype, "source", {
  31686. get: function () {
  31687. return this._source;
  31688. },
  31689. enumerable: true,
  31690. configurable: true
  31691. });
  31692. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31693. get: function () {
  31694. return this._unIndexed;
  31695. },
  31696. set: function (value) {
  31697. if (this._unIndexed !== value) {
  31698. this._unIndexed = value;
  31699. this._markSubMeshesAsAttributesDirty();
  31700. }
  31701. },
  31702. enumerable: true,
  31703. configurable: true
  31704. });
  31705. // Methods
  31706. /**
  31707. * Returns the string "Mesh".
  31708. */
  31709. Mesh.prototype.getClassName = function () {
  31710. return "Mesh";
  31711. };
  31712. /**
  31713. * Returns a string.
  31714. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31715. */
  31716. Mesh.prototype.toString = function (fullDetails) {
  31717. var ret = _super.prototype.toString.call(this, fullDetails);
  31718. ret += ", n vertices: " + this.getTotalVertices();
  31719. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31720. if (this.animations) {
  31721. for (var i = 0; i < this.animations.length; i++) {
  31722. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31723. }
  31724. }
  31725. if (fullDetails) {
  31726. if (this._geometry) {
  31727. var ib = this.getIndices();
  31728. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31729. if (vb && ib) {
  31730. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31731. }
  31732. }
  31733. else {
  31734. ret += ", flat shading: UNKNOWN";
  31735. }
  31736. }
  31737. return ret;
  31738. };
  31739. Mesh.prototype._unBindEffect = function () {
  31740. _super.prototype._unBindEffect.call(this);
  31741. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31742. var instance = _a[_i];
  31743. instance._unBindEffect();
  31744. }
  31745. };
  31746. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31747. /**
  31748. * True if the mesh has some Levels Of Details (LOD).
  31749. * Returns a boolean.
  31750. */
  31751. get: function () {
  31752. return this._LODLevels.length > 0;
  31753. },
  31754. enumerable: true,
  31755. configurable: true
  31756. });
  31757. /**
  31758. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31759. * @returns an array of {BABYLON.MeshLODLevel}
  31760. */
  31761. Mesh.prototype.getLODLevels = function () {
  31762. return this._LODLevels;
  31763. };
  31764. Mesh.prototype._sortLODLevels = function () {
  31765. this._LODLevels.sort(function (a, b) {
  31766. if (a.distance < b.distance) {
  31767. return 1;
  31768. }
  31769. if (a.distance > b.distance) {
  31770. return -1;
  31771. }
  31772. return 0;
  31773. });
  31774. };
  31775. /**
  31776. * Add a mesh as LOD level triggered at the given distance.
  31777. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31778. * @param distance The distance from the center of the object to show this level
  31779. * @param mesh The mesh to be added as LOD level (can be null)
  31780. * @return This mesh (for chaining)
  31781. */
  31782. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31783. if (mesh && mesh._masterMesh) {
  31784. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31785. return this;
  31786. }
  31787. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31788. this._LODLevels.push(level);
  31789. if (mesh) {
  31790. mesh._masterMesh = this;
  31791. }
  31792. this._sortLODLevels();
  31793. return this;
  31794. };
  31795. /**
  31796. * Returns the LOD level mesh at the passed distance or null if not found.
  31797. * It is related to the method `addLODLevel(distance, mesh)`.
  31798. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31799. * Returns an object Mesh or `null`.
  31800. */
  31801. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31802. for (var index = 0; index < this._LODLevels.length; index++) {
  31803. var level = this._LODLevels[index];
  31804. if (level.distance === distance) {
  31805. return level.mesh;
  31806. }
  31807. }
  31808. return null;
  31809. };
  31810. /**
  31811. * Remove a mesh from the LOD array
  31812. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31813. * @param {Mesh} mesh The mesh to be removed.
  31814. * @return {Mesh} This mesh (for chaining)
  31815. */
  31816. Mesh.prototype.removeLODLevel = function (mesh) {
  31817. for (var index = 0; index < this._LODLevels.length; index++) {
  31818. if (this._LODLevels[index].mesh === mesh) {
  31819. this._LODLevels.splice(index, 1);
  31820. if (mesh) {
  31821. mesh._masterMesh = null;
  31822. }
  31823. }
  31824. }
  31825. this._sortLODLevels();
  31826. return this;
  31827. };
  31828. /**
  31829. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31830. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31831. */
  31832. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31833. if (!this._LODLevels || this._LODLevels.length === 0) {
  31834. return this;
  31835. }
  31836. var bSphere;
  31837. if (boundingSphere) {
  31838. bSphere = boundingSphere;
  31839. }
  31840. else {
  31841. var boundingInfo = this.getBoundingInfo();
  31842. bSphere = boundingInfo.boundingSphere;
  31843. }
  31844. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31845. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31846. if (this.onLODLevelSelection) {
  31847. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31848. }
  31849. return this;
  31850. }
  31851. for (var index = 0; index < this._LODLevels.length; index++) {
  31852. var level = this._LODLevels[index];
  31853. if (level.distance < distanceToCamera) {
  31854. if (level.mesh) {
  31855. level.mesh._preActivate();
  31856. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31857. }
  31858. if (this.onLODLevelSelection) {
  31859. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31860. }
  31861. return level.mesh;
  31862. }
  31863. }
  31864. if (this.onLODLevelSelection) {
  31865. this.onLODLevelSelection(distanceToCamera, this, this);
  31866. }
  31867. return this;
  31868. };
  31869. Object.defineProperty(Mesh.prototype, "geometry", {
  31870. /**
  31871. * Returns the mesh internal Geometry object.
  31872. */
  31873. get: function () {
  31874. return this._geometry;
  31875. },
  31876. enumerable: true,
  31877. configurable: true
  31878. });
  31879. /**
  31880. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31881. */
  31882. Mesh.prototype.getTotalVertices = function () {
  31883. if (this._geometry === null || this._geometry === undefined) {
  31884. return 0;
  31885. }
  31886. return this._geometry.getTotalVertices();
  31887. };
  31888. /**
  31889. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31890. * 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.
  31891. * You can force the copy with forceCopy === true
  31892. * Returns null if the mesh has no geometry or no vertex buffer.
  31893. * Possible `kind` values :
  31894. * - BABYLON.VertexBuffer.PositionKind
  31895. * - BABYLON.VertexBuffer.UVKind
  31896. * - BABYLON.VertexBuffer.UV2Kind
  31897. * - BABYLON.VertexBuffer.UV3Kind
  31898. * - BABYLON.VertexBuffer.UV4Kind
  31899. * - BABYLON.VertexBuffer.UV5Kind
  31900. * - BABYLON.VertexBuffer.UV6Kind
  31901. * - BABYLON.VertexBuffer.ColorKind
  31902. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31903. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31904. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31905. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31906. */
  31907. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31908. if (!this._geometry) {
  31909. return null;
  31910. }
  31911. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31912. };
  31913. /**
  31914. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31915. * Returns `null` if the mesh has no geometry.
  31916. * Possible `kind` values :
  31917. * - BABYLON.VertexBuffer.PositionKind
  31918. * - BABYLON.VertexBuffer.UVKind
  31919. * - BABYLON.VertexBuffer.UV2Kind
  31920. * - BABYLON.VertexBuffer.UV3Kind
  31921. * - BABYLON.VertexBuffer.UV4Kind
  31922. * - BABYLON.VertexBuffer.UV5Kind
  31923. * - BABYLON.VertexBuffer.UV6Kind
  31924. * - BABYLON.VertexBuffer.ColorKind
  31925. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31926. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31927. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31928. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31929. */
  31930. Mesh.prototype.getVertexBuffer = function (kind) {
  31931. if (!this._geometry) {
  31932. return null;
  31933. }
  31934. return this._geometry.getVertexBuffer(kind);
  31935. };
  31936. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31937. if (!this._geometry) {
  31938. if (this._delayInfo) {
  31939. return this._delayInfo.indexOf(kind) !== -1;
  31940. }
  31941. return false;
  31942. }
  31943. return this._geometry.isVerticesDataPresent(kind);
  31944. };
  31945. /**
  31946. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31947. * Possible `kind` values :
  31948. * - BABYLON.VertexBuffer.PositionKind
  31949. * - BABYLON.VertexBuffer.UVKind
  31950. * - BABYLON.VertexBuffer.UV2Kind
  31951. * - BABYLON.VertexBuffer.UV3Kind
  31952. * - BABYLON.VertexBuffer.UV4Kind
  31953. * - BABYLON.VertexBuffer.UV5Kind
  31954. * - BABYLON.VertexBuffer.UV6Kind
  31955. * - BABYLON.VertexBuffer.ColorKind
  31956. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31957. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31958. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31959. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31960. */
  31961. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31962. if (!this._geometry) {
  31963. if (this._delayInfo) {
  31964. return this._delayInfo.indexOf(kind) !== -1;
  31965. }
  31966. return false;
  31967. }
  31968. return this._geometry.isVertexBufferUpdatable(kind);
  31969. };
  31970. /**
  31971. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31972. * Possible `kind` values :
  31973. * - BABYLON.VertexBuffer.PositionKind
  31974. * - BABYLON.VertexBuffer.UVKind
  31975. * - BABYLON.VertexBuffer.UV2Kind
  31976. * - BABYLON.VertexBuffer.UV3Kind
  31977. * - BABYLON.VertexBuffer.UV4Kind
  31978. * - BABYLON.VertexBuffer.UV5Kind
  31979. * - BABYLON.VertexBuffer.UV6Kind
  31980. * - BABYLON.VertexBuffer.ColorKind
  31981. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31982. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31983. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31984. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31985. */
  31986. Mesh.prototype.getVerticesDataKinds = function () {
  31987. if (!this._geometry) {
  31988. var result = new Array();
  31989. if (this._delayInfo) {
  31990. this._delayInfo.forEach(function (kind, index, array) {
  31991. result.push(kind);
  31992. });
  31993. }
  31994. return result;
  31995. }
  31996. return this._geometry.getVerticesDataKinds();
  31997. };
  31998. /**
  31999. * Returns a positive integer : the total number of indices in this mesh geometry.
  32000. * Returns zero if the mesh has no geometry.
  32001. */
  32002. Mesh.prototype.getTotalIndices = function () {
  32003. if (!this._geometry) {
  32004. return 0;
  32005. }
  32006. return this._geometry.getTotalIndices();
  32007. };
  32008. /**
  32009. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32010. * 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.
  32011. * Returns an empty array if the mesh has no geometry.
  32012. */
  32013. Mesh.prototype.getIndices = function (copyWhenShared) {
  32014. if (!this._geometry) {
  32015. return [];
  32016. }
  32017. return this._geometry.getIndices(copyWhenShared);
  32018. };
  32019. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32020. get: function () {
  32021. return this._masterMesh !== null && this._masterMesh !== undefined;
  32022. },
  32023. enumerable: true,
  32024. configurable: true
  32025. });
  32026. /**
  32027. * Determine if the current mesh is ready to be rendered
  32028. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32029. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32030. * @returns true if all associated assets are ready (material, textures, shaders)
  32031. */
  32032. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32033. if (completeCheck === void 0) { completeCheck = false; }
  32034. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32035. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32036. return false;
  32037. }
  32038. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32039. return false;
  32040. }
  32041. if (!this.subMeshes || this.subMeshes.length === 0) {
  32042. return true;
  32043. }
  32044. if (!completeCheck) {
  32045. return true;
  32046. }
  32047. var engine = this.getEngine();
  32048. var scene = this.getScene();
  32049. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32050. this.computeWorldMatrix();
  32051. var mat = this.material || scene.defaultMaterial;
  32052. if (mat) {
  32053. if (mat.storeEffectOnSubMeshes) {
  32054. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32055. var subMesh = _a[_i];
  32056. var effectiveMaterial = subMesh.getMaterial();
  32057. if (effectiveMaterial) {
  32058. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32059. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32060. return false;
  32061. }
  32062. }
  32063. else {
  32064. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32065. return false;
  32066. }
  32067. }
  32068. }
  32069. }
  32070. }
  32071. else {
  32072. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32073. return false;
  32074. }
  32075. }
  32076. }
  32077. // Shadows
  32078. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32079. var light = _c[_b];
  32080. var generator = light.getShadowGenerator();
  32081. if (generator) {
  32082. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32083. var subMesh = _e[_d];
  32084. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32085. return false;
  32086. }
  32087. }
  32088. }
  32089. }
  32090. // LOD
  32091. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32092. var lod = _g[_f];
  32093. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32094. return false;
  32095. }
  32096. }
  32097. return true;
  32098. };
  32099. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32100. /**
  32101. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32102. * This property is pertinent only for updatable parametric shapes.
  32103. */
  32104. get: function () {
  32105. return this._areNormalsFrozen;
  32106. },
  32107. enumerable: true,
  32108. configurable: true
  32109. });
  32110. /**
  32111. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32112. * It has no effect at all on other shapes.
  32113. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32114. * Returns the Mesh.
  32115. */
  32116. Mesh.prototype.freezeNormals = function () {
  32117. this._areNormalsFrozen = true;
  32118. return this;
  32119. };
  32120. /**
  32121. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32122. * It has no effect at all on other shapes.
  32123. * It reactivates the mesh normals computation if it was previously frozen.
  32124. * Returns the Mesh.
  32125. */
  32126. Mesh.prototype.unfreezeNormals = function () {
  32127. this._areNormalsFrozen = false;
  32128. return this;
  32129. };
  32130. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32131. /**
  32132. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32133. */
  32134. set: function (count) {
  32135. this._overridenInstanceCount = count;
  32136. },
  32137. enumerable: true,
  32138. configurable: true
  32139. });
  32140. // Methods
  32141. Mesh.prototype._preActivate = function () {
  32142. var sceneRenderId = this.getScene().getRenderId();
  32143. if (this._preActivateId === sceneRenderId) {
  32144. return this;
  32145. }
  32146. this._preActivateId = sceneRenderId;
  32147. this._visibleInstances = null;
  32148. return this;
  32149. };
  32150. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32151. if (this._visibleInstances) {
  32152. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32153. }
  32154. return this;
  32155. };
  32156. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32157. if (!this._visibleInstances) {
  32158. this._visibleInstances = {};
  32159. this._visibleInstances.defaultRenderId = renderId;
  32160. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32161. }
  32162. if (!this._visibleInstances[renderId]) {
  32163. this._visibleInstances[renderId] = new Array();
  32164. }
  32165. this._visibleInstances[renderId].push(instance);
  32166. return this;
  32167. };
  32168. /**
  32169. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32170. * This means the mesh underlying bounding box and sphere are recomputed.
  32171. * Returns the Mesh.
  32172. */
  32173. Mesh.prototype.refreshBoundingInfo = function () {
  32174. return this._refreshBoundingInfo(false);
  32175. };
  32176. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32177. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32178. return this;
  32179. }
  32180. var data = this._getPositionData(applySkeleton);
  32181. if (data) {
  32182. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32183. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32184. }
  32185. if (this.subMeshes) {
  32186. for (var index = 0; index < this.subMeshes.length; index++) {
  32187. this.subMeshes[index].refreshBoundingInfo();
  32188. }
  32189. }
  32190. this._updateBoundingInfo();
  32191. return this;
  32192. };
  32193. Mesh.prototype._getPositionData = function (applySkeleton) {
  32194. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32195. if (data && applySkeleton && this.skeleton) {
  32196. data = BABYLON.Tools.Slice(data);
  32197. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32198. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32199. if (matricesWeightsData && matricesIndicesData) {
  32200. var needExtras = this.numBoneInfluencers > 4;
  32201. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32202. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32203. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32204. var tempVector = BABYLON.Tmp.Vector3[0];
  32205. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32206. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32207. var matWeightIdx = 0;
  32208. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32209. finalMatrix.reset();
  32210. var inf;
  32211. var weight;
  32212. for (inf = 0; inf < 4; inf++) {
  32213. weight = matricesWeightsData[matWeightIdx + inf];
  32214. if (weight <= 0)
  32215. break;
  32216. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32217. finalMatrix.addToSelf(tempMatrix);
  32218. }
  32219. if (needExtras) {
  32220. for (inf = 0; inf < 4; inf++) {
  32221. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32222. if (weight <= 0)
  32223. break;
  32224. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32225. finalMatrix.addToSelf(tempMatrix);
  32226. }
  32227. }
  32228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32229. tempVector.toArray(data, index);
  32230. }
  32231. }
  32232. }
  32233. return data;
  32234. };
  32235. Mesh.prototype._createGlobalSubMesh = function (force) {
  32236. var totalVertices = this.getTotalVertices();
  32237. if (!totalVertices || !this.getIndices()) {
  32238. return null;
  32239. }
  32240. // Check if we need to recreate the submeshes
  32241. if (this.subMeshes && this.subMeshes.length > 0) {
  32242. var ib = this.getIndices();
  32243. if (!ib) {
  32244. return null;
  32245. }
  32246. var totalIndices = ib.length;
  32247. var needToRecreate = false;
  32248. if (force) {
  32249. needToRecreate = true;
  32250. }
  32251. else {
  32252. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32253. var submesh = _a[_i];
  32254. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32255. needToRecreate = true;
  32256. break;
  32257. }
  32258. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32259. needToRecreate = true;
  32260. break;
  32261. }
  32262. }
  32263. }
  32264. if (!needToRecreate) {
  32265. return this.subMeshes[0];
  32266. }
  32267. }
  32268. this.releaseSubMeshes();
  32269. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32270. };
  32271. Mesh.prototype.subdivide = function (count) {
  32272. if (count < 1) {
  32273. return;
  32274. }
  32275. var totalIndices = this.getTotalIndices();
  32276. var subdivisionSize = (totalIndices / count) | 0;
  32277. var offset = 0;
  32278. // Ensure that subdivisionSize is a multiple of 3
  32279. while (subdivisionSize % 3 !== 0) {
  32280. subdivisionSize++;
  32281. }
  32282. this.releaseSubMeshes();
  32283. for (var index = 0; index < count; index++) {
  32284. if (offset >= totalIndices) {
  32285. break;
  32286. }
  32287. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32288. offset += subdivisionSize;
  32289. }
  32290. this.synchronizeInstances();
  32291. };
  32292. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32293. if (updatable === void 0) { updatable = false; }
  32294. if (!this._geometry) {
  32295. var vertexData = new BABYLON.VertexData();
  32296. vertexData.set(data, kind);
  32297. var scene = this.getScene();
  32298. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32299. }
  32300. else {
  32301. this._geometry.setVerticesData(kind, data, updatable, stride);
  32302. }
  32303. return this;
  32304. };
  32305. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32306. if (updatable === void 0) { updatable = true; }
  32307. var vb = this.getVertexBuffer(kind);
  32308. if (!vb || vb.isUpdatable() === updatable) {
  32309. return;
  32310. }
  32311. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32312. };
  32313. /**
  32314. * Sets the mesh VertexBuffer.
  32315. * Returns the Mesh.
  32316. */
  32317. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32318. if (!this._geometry) {
  32319. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32320. }
  32321. this._geometry.setVerticesBuffer(buffer);
  32322. return this;
  32323. };
  32324. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32325. if (!this._geometry) {
  32326. return this;
  32327. }
  32328. if (!makeItUnique) {
  32329. this._geometry.updateVerticesData(kind, data, updateExtends);
  32330. }
  32331. else {
  32332. this.makeGeometryUnique();
  32333. this.updateVerticesData(kind, data, updateExtends, false);
  32334. }
  32335. return this;
  32336. };
  32337. /**
  32338. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32339. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32340. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32341. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32342. * Returns the Mesh.
  32343. */
  32344. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32345. if (computeNormals === void 0) { computeNormals = true; }
  32346. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32347. if (!positions) {
  32348. return this;
  32349. }
  32350. positionFunction(positions);
  32351. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32352. if (computeNormals) {
  32353. var indices = this.getIndices();
  32354. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32355. if (!normals) {
  32356. return this;
  32357. }
  32358. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32359. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32360. }
  32361. return this;
  32362. };
  32363. /**
  32364. * Creates a un-shared specific occurence of the geometry for the mesh.
  32365. * Returns the Mesh.
  32366. */
  32367. Mesh.prototype.makeGeometryUnique = function () {
  32368. if (!this._geometry) {
  32369. return this;
  32370. }
  32371. var oldGeometry = this._geometry;
  32372. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32373. oldGeometry.releaseForMesh(this, true);
  32374. geometry.applyToMesh(this);
  32375. return this;
  32376. };
  32377. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32378. if (totalVertices === void 0) { totalVertices = null; }
  32379. if (updatable === void 0) { updatable = false; }
  32380. if (!this._geometry) {
  32381. var vertexData = new BABYLON.VertexData();
  32382. vertexData.indices = indices;
  32383. var scene = this.getScene();
  32384. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32385. }
  32386. else {
  32387. this._geometry.setIndices(indices, totalVertices, updatable);
  32388. }
  32389. return this;
  32390. };
  32391. /**
  32392. * Update the current index buffer
  32393. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32394. * Returns the Mesh.
  32395. */
  32396. Mesh.prototype.updateIndices = function (indices, offset) {
  32397. if (!this._geometry) {
  32398. return this;
  32399. }
  32400. this._geometry.updateIndices(indices, offset);
  32401. return this;
  32402. };
  32403. /**
  32404. * Invert the geometry to move from a right handed system to a left handed one.
  32405. * Returns the Mesh.
  32406. */
  32407. Mesh.prototype.toLeftHanded = function () {
  32408. if (!this._geometry) {
  32409. return this;
  32410. }
  32411. this._geometry.toLeftHanded();
  32412. return this;
  32413. };
  32414. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32415. if (!this._geometry) {
  32416. return this;
  32417. }
  32418. var engine = this.getScene().getEngine();
  32419. // Wireframe
  32420. var indexToBind;
  32421. if (this._unIndexed) {
  32422. indexToBind = null;
  32423. }
  32424. else {
  32425. switch (fillMode) {
  32426. case BABYLON.Material.PointFillMode:
  32427. indexToBind = null;
  32428. break;
  32429. case BABYLON.Material.WireFrameFillMode:
  32430. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32431. break;
  32432. default:
  32433. case BABYLON.Material.TriangleFillMode:
  32434. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32435. break;
  32436. }
  32437. }
  32438. // VBOs
  32439. this._geometry._bind(effect, indexToBind);
  32440. return this;
  32441. };
  32442. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32443. if (alternate === void 0) { alternate = false; }
  32444. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32445. return this;
  32446. }
  32447. this.onBeforeDrawObservable.notifyObservers(this);
  32448. var scene = this.getScene();
  32449. var engine = scene.getEngine();
  32450. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32451. // or triangles as points
  32452. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32453. }
  32454. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32455. // Triangles as wireframe
  32456. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32457. }
  32458. else {
  32459. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32460. }
  32461. if (scene._isAlternateRenderingEnabled && !alternate) {
  32462. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32463. if (!effect || !scene.activeCamera) {
  32464. return this;
  32465. }
  32466. scene._switchToAlternateCameraConfiguration(true);
  32467. this._effectiveMaterial.bindView(effect);
  32468. this._effectiveMaterial.bindViewProjection(effect);
  32469. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32470. this._draw(subMesh, fillMode, instancesCount, true);
  32471. engine.setViewport(scene.activeCamera.viewport);
  32472. scene._switchToAlternateCameraConfiguration(false);
  32473. this._effectiveMaterial.bindView(effect);
  32474. this._effectiveMaterial.bindViewProjection(effect);
  32475. }
  32476. return this;
  32477. };
  32478. /**
  32479. * Registers for this mesh a javascript function called just before the rendering process.
  32480. * This function is passed the current mesh.
  32481. * Return the Mesh.
  32482. */
  32483. Mesh.prototype.registerBeforeRender = function (func) {
  32484. this.onBeforeRenderObservable.add(func);
  32485. return this;
  32486. };
  32487. /**
  32488. * Disposes a previously registered javascript function called before the rendering.
  32489. * This function is passed the current mesh.
  32490. * Returns the Mesh.
  32491. */
  32492. Mesh.prototype.unregisterBeforeRender = function (func) {
  32493. this.onBeforeRenderObservable.removeCallback(func);
  32494. return this;
  32495. };
  32496. /**
  32497. * Registers for this mesh a javascript function called just after the rendering is complete.
  32498. * This function is passed the current mesh.
  32499. * Returns the Mesh.
  32500. */
  32501. Mesh.prototype.registerAfterRender = function (func) {
  32502. this.onAfterRenderObservable.add(func);
  32503. return this;
  32504. };
  32505. /**
  32506. * Disposes a previously registered javascript function called after the rendering.
  32507. * This function is passed the current mesh.
  32508. * Return the Mesh.
  32509. */
  32510. Mesh.prototype.unregisterAfterRender = function (func) {
  32511. this.onAfterRenderObservable.removeCallback(func);
  32512. return this;
  32513. };
  32514. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32515. var scene = this.getScene();
  32516. this._batchCache.mustReturn = false;
  32517. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32518. this._batchCache.visibleInstances[subMeshId] = null;
  32519. if (this._visibleInstances) {
  32520. var currentRenderId = scene.getRenderId();
  32521. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32522. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32523. var selfRenderId = this._renderId;
  32524. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32525. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32526. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32527. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32528. }
  32529. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32530. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32531. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32532. this._batchCache.mustReturn = true;
  32533. return this._batchCache;
  32534. }
  32535. if (currentRenderId !== selfRenderId) {
  32536. this._batchCache.renderSelf[subMeshId] = false;
  32537. }
  32538. }
  32539. this._renderIdForInstances[subMeshId] = currentRenderId;
  32540. }
  32541. return this._batchCache;
  32542. };
  32543. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32544. var visibleInstances = batch.visibleInstances[subMesh._id];
  32545. if (!visibleInstances) {
  32546. return this;
  32547. }
  32548. var matricesCount = visibleInstances.length + 1;
  32549. var bufferSize = matricesCount * 16 * 4;
  32550. var currentInstancesBufferSize = this._instancesBufferSize;
  32551. var instancesBuffer = this._instancesBuffer;
  32552. while (this._instancesBufferSize < bufferSize) {
  32553. this._instancesBufferSize *= 2;
  32554. }
  32555. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32556. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32557. }
  32558. var offset = 0;
  32559. var instancesCount = 0;
  32560. var world = this.getWorldMatrix();
  32561. if (batch.renderSelf[subMesh._id]) {
  32562. world.copyToArray(this._instancesData, offset);
  32563. offset += 16;
  32564. instancesCount++;
  32565. }
  32566. if (visibleInstances) {
  32567. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32568. var instance = visibleInstances[instanceIndex];
  32569. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32570. offset += 16;
  32571. instancesCount++;
  32572. }
  32573. }
  32574. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32575. if (instancesBuffer) {
  32576. instancesBuffer.dispose();
  32577. }
  32578. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32579. this._instancesBuffer = instancesBuffer;
  32580. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32581. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32582. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32583. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32584. }
  32585. else {
  32586. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32587. }
  32588. this._bind(subMesh, effect, fillMode);
  32589. this._draw(subMesh, fillMode, instancesCount);
  32590. engine.unbindInstanceAttributes();
  32591. return this;
  32592. };
  32593. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32594. var scene = this.getScene();
  32595. var engine = scene.getEngine();
  32596. if (hardwareInstancedRendering) {
  32597. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32598. }
  32599. else {
  32600. if (batch.renderSelf[subMesh._id]) {
  32601. // Draw
  32602. if (onBeforeDraw) {
  32603. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32604. }
  32605. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32606. }
  32607. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32608. if (visibleInstancesForSubMesh) {
  32609. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32610. var instance = visibleInstancesForSubMesh[instanceIndex];
  32611. // World
  32612. var world = instance.getWorldMatrix();
  32613. if (onBeforeDraw) {
  32614. onBeforeDraw(true, world, effectiveMaterial);
  32615. }
  32616. // Draw
  32617. this._draw(subMesh, fillMode);
  32618. }
  32619. }
  32620. }
  32621. return this;
  32622. };
  32623. /**
  32624. * Triggers the draw call for the mesh.
  32625. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32626. * Returns the Mesh.
  32627. */
  32628. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32629. this._checkOcclusionQuery();
  32630. if (this._isOccluded) {
  32631. return this;
  32632. }
  32633. var scene = this.getScene();
  32634. // Managing instances
  32635. var batch = this._getInstancesRenderList(subMesh._id);
  32636. if (batch.mustReturn) {
  32637. return this;
  32638. }
  32639. // Checking geometry state
  32640. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32641. return this;
  32642. }
  32643. this.onBeforeRenderObservable.notifyObservers(this);
  32644. var engine = scene.getEngine();
  32645. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32646. // Material
  32647. var material = subMesh.getMaterial();
  32648. if (!material) {
  32649. return this;
  32650. }
  32651. this._effectiveMaterial = material;
  32652. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32653. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32654. return this;
  32655. }
  32656. }
  32657. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32658. return this;
  32659. }
  32660. // Alpha mode
  32661. if (enableAlphaMode) {
  32662. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32663. }
  32664. // Outline - step 1
  32665. var savedDepthWrite = engine.getDepthWrite();
  32666. if (this.renderOutline) {
  32667. engine.setDepthWrite(false);
  32668. scene.getOutlineRenderer().render(subMesh, batch);
  32669. engine.setDepthWrite(savedDepthWrite);
  32670. }
  32671. var effect;
  32672. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32673. effect = subMesh.effect;
  32674. }
  32675. else {
  32676. effect = this._effectiveMaterial.getEffect();
  32677. }
  32678. if (!effect) {
  32679. return this;
  32680. }
  32681. var sideOrientation = this.overrideMaterialSideOrientation;
  32682. if (sideOrientation == null) {
  32683. sideOrientation = this._effectiveMaterial.sideOrientation;
  32684. if (this._getWorldMatrixDeterminant() < 0) {
  32685. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32686. }
  32687. }
  32688. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32689. if (this._effectiveMaterial.forceDepthWrite) {
  32690. engine.setDepthWrite(true);
  32691. }
  32692. // Bind
  32693. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32694. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32695. this._bind(subMesh, effect, fillMode);
  32696. }
  32697. var world = this.getWorldMatrix();
  32698. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32699. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32700. }
  32701. else {
  32702. this._effectiveMaterial.bind(world, this);
  32703. }
  32704. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32705. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32706. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32707. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32708. }
  32709. // Draw
  32710. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32711. // Unbind
  32712. this._effectiveMaterial.unbind();
  32713. // Outline - step 2
  32714. if (this.renderOutline && savedDepthWrite) {
  32715. engine.setDepthWrite(true);
  32716. engine.setColorWrite(false);
  32717. scene.getOutlineRenderer().render(subMesh, batch);
  32718. engine.setColorWrite(true);
  32719. }
  32720. // Overlay
  32721. if (this.renderOverlay) {
  32722. var currentMode = engine.getAlphaMode();
  32723. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32724. scene.getOutlineRenderer().render(subMesh, batch, true);
  32725. engine.setAlphaMode(currentMode);
  32726. }
  32727. this.onAfterRenderObservable.notifyObservers(this);
  32728. return this;
  32729. };
  32730. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32731. if (isInstance && effectiveMaterial) {
  32732. effectiveMaterial.bindOnlyWorldMatrix(world);
  32733. }
  32734. };
  32735. /**
  32736. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32737. */
  32738. Mesh.prototype.getEmittedParticleSystems = function () {
  32739. var results = new Array();
  32740. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32741. var particleSystem = this.getScene().particleSystems[index];
  32742. if (particleSystem.emitter === this) {
  32743. results.push(particleSystem);
  32744. }
  32745. }
  32746. return results;
  32747. };
  32748. /**
  32749. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32750. */
  32751. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32752. var results = new Array();
  32753. var descendants = this.getDescendants();
  32754. descendants.push(this);
  32755. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32756. var particleSystem = this.getScene().particleSystems[index];
  32757. var emitter = particleSystem.emitter;
  32758. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32759. results.push(particleSystem);
  32760. }
  32761. }
  32762. return results;
  32763. };
  32764. /**
  32765. * Normalize matrix weights so that all vertices have a total weight set to 1
  32766. */
  32767. Mesh.prototype.cleanMatrixWeights = function () {
  32768. var epsilon = 1e-3;
  32769. var noInfluenceBoneIndex = 0.0;
  32770. if (this.skeleton) {
  32771. noInfluenceBoneIndex = this.skeleton.bones.length;
  32772. }
  32773. else {
  32774. return;
  32775. }
  32776. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32777. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32778. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32779. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32780. var influencers = this.numBoneInfluencers;
  32781. var size = matricesWeights.length;
  32782. for (var i = 0; i < size; i += 4) {
  32783. var weight = 0.0;
  32784. var firstZeroWeight = -1;
  32785. for (var j = 0; j < 4; j++) {
  32786. var w = matricesWeights[i + j];
  32787. weight += w;
  32788. if (w < epsilon && firstZeroWeight < 0) {
  32789. firstZeroWeight = j;
  32790. }
  32791. }
  32792. if (matricesWeightsExtra) {
  32793. for (var j = 0; j < 4; j++) {
  32794. var w = matricesWeightsExtra[i + j];
  32795. weight += w;
  32796. if (w < epsilon && firstZeroWeight < 0) {
  32797. firstZeroWeight = j + 4;
  32798. }
  32799. }
  32800. }
  32801. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32802. firstZeroWeight = influencers - 1;
  32803. }
  32804. if (weight > epsilon) {
  32805. var mweight = 1.0 / weight;
  32806. for (var j = 0; j < 4; j++) {
  32807. matricesWeights[i + j] *= mweight;
  32808. }
  32809. if (matricesWeightsExtra) {
  32810. for (var j = 0; j < 4; j++) {
  32811. matricesWeightsExtra[i + j] *= mweight;
  32812. }
  32813. }
  32814. }
  32815. else {
  32816. if (firstZeroWeight >= 4) {
  32817. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32818. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32819. }
  32820. else {
  32821. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32822. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32823. }
  32824. }
  32825. }
  32826. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32827. if (matricesIndicesExtra) {
  32828. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32829. }
  32830. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32831. if (matricesWeightsExtra) {
  32832. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32833. }
  32834. };
  32835. Mesh.prototype._checkDelayState = function () {
  32836. var scene = this.getScene();
  32837. if (this._geometry) {
  32838. this._geometry.load(scene);
  32839. }
  32840. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32842. this._queueLoad(scene);
  32843. }
  32844. return this;
  32845. };
  32846. Mesh.prototype._queueLoad = function (scene) {
  32847. var _this = this;
  32848. scene._addPendingData(this);
  32849. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32850. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32851. if (data instanceof ArrayBuffer) {
  32852. _this._delayLoadingFunction(data, _this);
  32853. }
  32854. else {
  32855. _this._delayLoadingFunction(JSON.parse(data), _this);
  32856. }
  32857. _this.instances.forEach(function (instance) {
  32858. instance._syncSubMeshes();
  32859. });
  32860. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32861. scene._removePendingData(_this);
  32862. }, function () { }, scene.database, getBinaryData);
  32863. return this;
  32864. };
  32865. /**
  32866. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32867. */
  32868. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32869. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32870. return false;
  32871. }
  32872. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32873. return false;
  32874. }
  32875. this._checkDelayState();
  32876. return true;
  32877. };
  32878. /**
  32879. * Sets the mesh material by the material or multiMaterial `id` property.
  32880. * The material `id` is a string identifying the material or the multiMaterial.
  32881. * This method returns the Mesh.
  32882. */
  32883. Mesh.prototype.setMaterialByID = function (id) {
  32884. var materials = this.getScene().materials;
  32885. var index;
  32886. for (index = materials.length - 1; index > -1; index--) {
  32887. if (materials[index].id === id) {
  32888. this.material = materials[index];
  32889. return this;
  32890. }
  32891. }
  32892. // Multi
  32893. var multiMaterials = this.getScene().multiMaterials;
  32894. for (index = multiMaterials.length - 1; index > -1; index--) {
  32895. if (multiMaterials[index].id === id) {
  32896. this.material = multiMaterials[index];
  32897. return this;
  32898. }
  32899. }
  32900. return this;
  32901. };
  32902. /**
  32903. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32904. */
  32905. Mesh.prototype.getAnimatables = function () {
  32906. var results = new Array();
  32907. if (this.material) {
  32908. results.push(this.material);
  32909. }
  32910. if (this.skeleton) {
  32911. results.push(this.skeleton);
  32912. }
  32913. return results;
  32914. };
  32915. /**
  32916. * Modifies the mesh geometry according to the passed transformation matrix.
  32917. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32918. * The mesh normals are modified accordingly the same transformation.
  32919. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32920. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32921. * Returns the Mesh.
  32922. */
  32923. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32924. // Position
  32925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32926. return this;
  32927. }
  32928. var submeshes = this.subMeshes.splice(0);
  32929. this._resetPointsArrayCache();
  32930. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32931. var temp = new Array();
  32932. var index;
  32933. for (index = 0; index < data.length; index += 3) {
  32934. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32935. }
  32936. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32937. // Normals
  32938. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32939. return this;
  32940. }
  32941. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32942. temp = [];
  32943. for (index = 0; index < data.length; index += 3) {
  32944. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32945. }
  32946. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32947. // flip faces?
  32948. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32949. this.flipFaces();
  32950. }
  32951. // Restore submeshes
  32952. this.releaseSubMeshes();
  32953. this.subMeshes = submeshes;
  32954. return this;
  32955. };
  32956. /**
  32957. * Modifies the mesh geometry according to its own current World Matrix.
  32958. * The mesh World Matrix is then reset.
  32959. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32960. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32961. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32962. * Returns the Mesh.
  32963. */
  32964. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32965. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32966. this.scaling.copyFromFloats(1, 1, 1);
  32967. this.position.copyFromFloats(0, 0, 0);
  32968. this.rotation.copyFromFloats(0, 0, 0);
  32969. //only if quaternion is already set
  32970. if (this.rotationQuaternion) {
  32971. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32972. }
  32973. this._worldMatrix = BABYLON.Matrix.Identity();
  32974. return this;
  32975. };
  32976. Object.defineProperty(Mesh.prototype, "_positions", {
  32977. // Cache
  32978. get: function () {
  32979. if (this._geometry) {
  32980. return this._geometry._positions;
  32981. }
  32982. return null;
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. Mesh.prototype._resetPointsArrayCache = function () {
  32988. if (this._geometry) {
  32989. this._geometry._resetPointsArrayCache();
  32990. }
  32991. return this;
  32992. };
  32993. Mesh.prototype._generatePointsArray = function () {
  32994. if (this._geometry) {
  32995. return this._geometry._generatePointsArray();
  32996. }
  32997. return false;
  32998. };
  32999. /**
  33000. * Returns a new Mesh object generated from the current mesh properties.
  33001. * This method must not get confused with createInstance().
  33002. * The parameter `name` is a string, the name given to the new mesh.
  33003. * The optional parameter `newParent` can be any Node object (default `null`).
  33004. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  33005. * 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.
  33006. */
  33007. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33008. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33009. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33010. };
  33011. /**
  33012. * Releases resources associated with this mesh.
  33013. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33014. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33015. */
  33016. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33017. var _this = this;
  33018. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33019. this.morphTargetManager = null;
  33020. if (this._geometry) {
  33021. this._geometry.releaseForMesh(this, true);
  33022. }
  33023. // Sources
  33024. var meshes = this.getScene().meshes;
  33025. meshes.forEach(function (abstractMesh) {
  33026. var mesh = abstractMesh;
  33027. if (mesh._source && mesh._source === _this) {
  33028. mesh._source = null;
  33029. }
  33030. });
  33031. this._source = null;
  33032. // Instances
  33033. if (this._instancesBuffer) {
  33034. this._instancesBuffer.dispose();
  33035. this._instancesBuffer = null;
  33036. }
  33037. while (this.instances.length) {
  33038. this.instances[0].dispose();
  33039. }
  33040. // Effect layers.
  33041. var effectLayers = this.getScene().effectLayers;
  33042. for (var i = 0; i < effectLayers.length; i++) {
  33043. var effectLayer = effectLayers[i];
  33044. if (effectLayer) {
  33045. effectLayer._disposeMesh(this);
  33046. }
  33047. }
  33048. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33049. };
  33050. /**
  33051. * Modifies the mesh geometry according to a displacement map.
  33052. * 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.
  33053. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33054. * This method returns nothing.
  33055. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33056. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33057. * 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.
  33058. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33059. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33060. *
  33061. * Returns the Mesh.
  33062. */
  33063. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33064. var _this = this;
  33065. var scene = this.getScene();
  33066. var onload = function (img) {
  33067. // Getting height map data
  33068. var canvas = document.createElement("canvas");
  33069. var context = canvas.getContext("2d");
  33070. var heightMapWidth = img.width;
  33071. var heightMapHeight = img.height;
  33072. canvas.width = heightMapWidth;
  33073. canvas.height = heightMapHeight;
  33074. context.drawImage(img, 0, 0);
  33075. // Create VertexData from map data
  33076. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33077. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33078. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33079. //execute success callback, if set
  33080. if (onSuccess) {
  33081. onSuccess(_this);
  33082. }
  33083. };
  33084. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33085. return this;
  33086. };
  33087. /**
  33088. * Modifies the mesh geometry according to a displacementMap buffer.
  33089. * 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.
  33090. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33091. * This method returns nothing.
  33092. * 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.
  33093. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33094. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33095. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33096. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33097. *
  33098. * Returns the Mesh.
  33099. */
  33100. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33101. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33102. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33103. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33104. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33105. return this;
  33106. }
  33107. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33108. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33109. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33110. var position = BABYLON.Vector3.Zero();
  33111. var normal = BABYLON.Vector3.Zero();
  33112. var uv = BABYLON.Vector2.Zero();
  33113. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33114. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33115. for (var index = 0; index < positions.length; index += 3) {
  33116. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33117. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33118. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33119. // Compute height
  33120. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33121. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33122. var pos = (u + v * heightMapWidth) * 4;
  33123. var r = buffer[pos] / 255.0;
  33124. var g = buffer[pos + 1] / 255.0;
  33125. var b = buffer[pos + 2] / 255.0;
  33126. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33127. normal.normalize();
  33128. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33129. position = position.add(normal);
  33130. position.toArray(positions, index);
  33131. }
  33132. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33133. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33134. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33135. return this;
  33136. };
  33137. /**
  33138. * Modify the mesh to get a flat shading rendering.
  33139. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33140. * This method returns the Mesh.
  33141. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33142. */
  33143. Mesh.prototype.convertToFlatShadedMesh = function () {
  33144. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33145. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33146. var kinds = this.getVerticesDataKinds();
  33147. var vbs = {};
  33148. var data = {};
  33149. var newdata = {};
  33150. var updatableNormals = false;
  33151. var kindIndex;
  33152. var kind;
  33153. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33154. kind = kinds[kindIndex];
  33155. var vertexBuffer = this.getVertexBuffer(kind);
  33156. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33157. updatableNormals = vertexBuffer.isUpdatable();
  33158. kinds.splice(kindIndex, 1);
  33159. kindIndex--;
  33160. continue;
  33161. }
  33162. vbs[kind] = vertexBuffer;
  33163. data[kind] = vbs[kind].getData();
  33164. newdata[kind] = [];
  33165. }
  33166. // Save previous submeshes
  33167. var previousSubmeshes = this.subMeshes.slice(0);
  33168. var indices = this.getIndices();
  33169. var totalIndices = this.getTotalIndices();
  33170. // Generating unique vertices per face
  33171. var index;
  33172. for (index = 0; index < totalIndices; index++) {
  33173. var vertexIndex = indices[index];
  33174. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33175. kind = kinds[kindIndex];
  33176. var stride = vbs[kind].getStrideSize();
  33177. for (var offset = 0; offset < stride; offset++) {
  33178. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33179. }
  33180. }
  33181. }
  33182. // Updating faces & normal
  33183. var normals = [];
  33184. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33185. for (index = 0; index < totalIndices; index += 3) {
  33186. indices[index] = index;
  33187. indices[index + 1] = index + 1;
  33188. indices[index + 2] = index + 2;
  33189. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33190. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33191. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33192. var p1p2 = p1.subtract(p2);
  33193. var p3p2 = p3.subtract(p2);
  33194. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33195. // Store same normals for every vertex
  33196. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33197. normals.push(normal.x);
  33198. normals.push(normal.y);
  33199. normals.push(normal.z);
  33200. }
  33201. }
  33202. this.setIndices(indices);
  33203. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33204. // Updating vertex buffers
  33205. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33206. kind = kinds[kindIndex];
  33207. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33208. }
  33209. // Updating submeshes
  33210. this.releaseSubMeshes();
  33211. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33212. var previousOne = previousSubmeshes[submeshIndex];
  33213. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33214. }
  33215. this.synchronizeInstances();
  33216. return this;
  33217. };
  33218. /**
  33219. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33220. * In other words, more vertices, no more indices and a single bigger VBO.
  33221. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33222. * Returns the Mesh.
  33223. */
  33224. Mesh.prototype.convertToUnIndexedMesh = function () {
  33225. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33226. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33227. var kinds = this.getVerticesDataKinds();
  33228. var vbs = {};
  33229. var data = {};
  33230. var newdata = {};
  33231. var kindIndex;
  33232. var kind;
  33233. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33234. kind = kinds[kindIndex];
  33235. var vertexBuffer = this.getVertexBuffer(kind);
  33236. vbs[kind] = vertexBuffer;
  33237. data[kind] = vbs[kind].getData();
  33238. newdata[kind] = [];
  33239. }
  33240. // Save previous submeshes
  33241. var previousSubmeshes = this.subMeshes.slice(0);
  33242. var indices = this.getIndices();
  33243. var totalIndices = this.getTotalIndices();
  33244. // Generating unique vertices per face
  33245. var index;
  33246. for (index = 0; index < totalIndices; index++) {
  33247. var vertexIndex = indices[index];
  33248. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33249. kind = kinds[kindIndex];
  33250. var stride = vbs[kind].getStrideSize();
  33251. for (var offset = 0; offset < stride; offset++) {
  33252. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33253. }
  33254. }
  33255. }
  33256. // Updating indices
  33257. for (index = 0; index < totalIndices; index += 3) {
  33258. indices[index] = index;
  33259. indices[index + 1] = index + 1;
  33260. indices[index + 2] = index + 2;
  33261. }
  33262. this.setIndices(indices);
  33263. // Updating vertex buffers
  33264. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33265. kind = kinds[kindIndex];
  33266. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33267. }
  33268. // Updating submeshes
  33269. this.releaseSubMeshes();
  33270. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33271. var previousOne = previousSubmeshes[submeshIndex];
  33272. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33273. }
  33274. this._unIndexed = true;
  33275. this.synchronizeInstances();
  33276. return this;
  33277. };
  33278. /**
  33279. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33280. * This method returns the Mesh.
  33281. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33282. */
  33283. Mesh.prototype.flipFaces = function (flipNormals) {
  33284. if (flipNormals === void 0) { flipNormals = false; }
  33285. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33286. var i;
  33287. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33288. for (i = 0; i < vertex_data.normals.length; i++) {
  33289. vertex_data.normals[i] *= -1;
  33290. }
  33291. }
  33292. if (vertex_data.indices) {
  33293. var temp;
  33294. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33295. // reassign indices
  33296. temp = vertex_data.indices[i + 1];
  33297. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33298. vertex_data.indices[i + 2] = temp;
  33299. }
  33300. }
  33301. vertex_data.applyToMesh(this);
  33302. return this;
  33303. };
  33304. // Instances
  33305. /**
  33306. * Creates a new InstancedMesh object from the mesh model.
  33307. * An instance shares the same properties and the same material than its model.
  33308. * Only these properties of each instance can then be set individually :
  33309. * - position
  33310. * - rotation
  33311. * - rotationQuaternion
  33312. * - setPivotMatrix
  33313. * - scaling
  33314. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33315. * Warning : this method is not supported for Line mesh and LineSystem
  33316. */
  33317. Mesh.prototype.createInstance = function (name) {
  33318. return new BABYLON.InstancedMesh(name, this);
  33319. };
  33320. /**
  33321. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33322. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33323. * This method returns the Mesh.
  33324. */
  33325. Mesh.prototype.synchronizeInstances = function () {
  33326. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33327. var instance = this.instances[instanceIndex];
  33328. instance._syncSubMeshes();
  33329. }
  33330. return this;
  33331. };
  33332. /**
  33333. * Simplify the mesh according to the given array of settings.
  33334. * Function will return immediately and will simplify async. It returns the Mesh.
  33335. * @param settings a collection of simplification settings.
  33336. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33337. * @param type the type of simplification to run.
  33338. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33339. */
  33340. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33341. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33342. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33343. this.getScene().simplificationQueue.addTask({
  33344. settings: settings,
  33345. parallelProcessing: parallelProcessing,
  33346. mesh: this,
  33347. simplificationType: simplificationType,
  33348. successCallback: successCallback
  33349. });
  33350. return this;
  33351. };
  33352. /**
  33353. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33354. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33355. * This should be used together with the simplification to avoid disappearing triangles.
  33356. * Returns the Mesh.
  33357. * @param successCallback an optional success callback to be called after the optimization finished.
  33358. */
  33359. Mesh.prototype.optimizeIndices = function (successCallback) {
  33360. var _this = this;
  33361. var indices = this.getIndices();
  33362. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33363. if (!positions || !indices) {
  33364. return this;
  33365. }
  33366. var vectorPositions = new Array();
  33367. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33368. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33369. }
  33370. var dupes = new Array();
  33371. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33372. var realPos = vectorPositions.length - 1 - iteration;
  33373. var testedPosition = vectorPositions[realPos];
  33374. for (var j = 0; j < realPos; ++j) {
  33375. var againstPosition = vectorPositions[j];
  33376. if (testedPosition.equals(againstPosition)) {
  33377. dupes[realPos] = j;
  33378. break;
  33379. }
  33380. }
  33381. }, function () {
  33382. for (var i = 0; i < indices.length; ++i) {
  33383. indices[i] = dupes[indices[i]] || indices[i];
  33384. }
  33385. //indices are now reordered
  33386. var originalSubMeshes = _this.subMeshes.slice(0);
  33387. _this.setIndices(indices);
  33388. _this.subMeshes = originalSubMeshes;
  33389. if (successCallback) {
  33390. successCallback(_this);
  33391. }
  33392. });
  33393. return this;
  33394. };
  33395. Mesh.prototype.serialize = function (serializationObject) {
  33396. serializationObject.name = this.name;
  33397. serializationObject.id = this.id;
  33398. serializationObject.type = this.getClassName();
  33399. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33400. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33401. }
  33402. serializationObject.position = this.position.asArray();
  33403. if (this.rotationQuaternion) {
  33404. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33405. }
  33406. else if (this.rotation) {
  33407. serializationObject.rotation = this.rotation.asArray();
  33408. }
  33409. serializationObject.scaling = this.scaling.asArray();
  33410. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33411. serializationObject.isEnabled = this.isEnabled(false);
  33412. serializationObject.isVisible = this.isVisible;
  33413. serializationObject.infiniteDistance = this.infiniteDistance;
  33414. serializationObject.pickable = this.isPickable;
  33415. serializationObject.receiveShadows = this.receiveShadows;
  33416. serializationObject.billboardMode = this.billboardMode;
  33417. serializationObject.visibility = this.visibility;
  33418. serializationObject.checkCollisions = this.checkCollisions;
  33419. serializationObject.isBlocker = this.isBlocker;
  33420. // Parent
  33421. if (this.parent) {
  33422. serializationObject.parentId = this.parent.id;
  33423. }
  33424. // Geometry
  33425. serializationObject.isUnIndexed = this.isUnIndexed;
  33426. var geometry = this._geometry;
  33427. if (geometry) {
  33428. var geometryId = geometry.id;
  33429. serializationObject.geometryId = geometryId;
  33430. // SubMeshes
  33431. serializationObject.subMeshes = [];
  33432. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33433. var subMesh = this.subMeshes[subIndex];
  33434. serializationObject.subMeshes.push({
  33435. materialIndex: subMesh.materialIndex,
  33436. verticesStart: subMesh.verticesStart,
  33437. verticesCount: subMesh.verticesCount,
  33438. indexStart: subMesh.indexStart,
  33439. indexCount: subMesh.indexCount
  33440. });
  33441. }
  33442. }
  33443. // Material
  33444. if (this.material) {
  33445. serializationObject.materialId = this.material.id;
  33446. }
  33447. else {
  33448. this.material = null;
  33449. }
  33450. // Morph targets
  33451. if (this.morphTargetManager) {
  33452. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33453. }
  33454. // Skeleton
  33455. if (this.skeleton) {
  33456. serializationObject.skeletonId = this.skeleton.id;
  33457. }
  33458. // Physics
  33459. //TODO implement correct serialization for physics impostors.
  33460. var impostor = this.getPhysicsImpostor();
  33461. if (impostor) {
  33462. serializationObject.physicsMass = impostor.getParam("mass");
  33463. serializationObject.physicsFriction = impostor.getParam("friction");
  33464. serializationObject.physicsRestitution = impostor.getParam("mass");
  33465. serializationObject.physicsImpostor = impostor.type;
  33466. }
  33467. // Metadata
  33468. if (this.metadata) {
  33469. serializationObject.metadata = this.metadata;
  33470. }
  33471. // Instances
  33472. serializationObject.instances = [];
  33473. for (var index = 0; index < this.instances.length; index++) {
  33474. var instance = this.instances[index];
  33475. var serializationInstance = {
  33476. name: instance.name,
  33477. id: instance.id,
  33478. position: instance.position.asArray(),
  33479. scaling: instance.scaling.asArray()
  33480. };
  33481. if (instance.rotationQuaternion) {
  33482. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33483. }
  33484. else if (instance.rotation) {
  33485. serializationInstance.rotation = instance.rotation.asArray();
  33486. }
  33487. serializationObject.instances.push(serializationInstance);
  33488. // Animations
  33489. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33490. serializationInstance.ranges = instance.serializeAnimationRanges();
  33491. }
  33492. //
  33493. // Animations
  33494. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33495. serializationObject.ranges = this.serializeAnimationRanges();
  33496. // Layer mask
  33497. serializationObject.layerMask = this.layerMask;
  33498. // Alpha
  33499. serializationObject.alphaIndex = this.alphaIndex;
  33500. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33501. // Overlay
  33502. serializationObject.overlayAlpha = this.overlayAlpha;
  33503. serializationObject.overlayColor = this.overlayColor.asArray();
  33504. serializationObject.renderOverlay = this.renderOverlay;
  33505. // Fog
  33506. serializationObject.applyFog = this.applyFog;
  33507. // Action Manager
  33508. if (this.actionManager) {
  33509. serializationObject.actions = this.actionManager.serialize(this.name);
  33510. }
  33511. };
  33512. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33513. if (!this.geometry) {
  33514. return;
  33515. }
  33516. this._markSubMeshesAsAttributesDirty();
  33517. var morphTargetManager = this._morphTargetManager;
  33518. if (morphTargetManager && morphTargetManager.vertexCount) {
  33519. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33520. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33521. this.morphTargetManager = null;
  33522. return;
  33523. }
  33524. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33525. var morphTarget = morphTargetManager.getActiveTarget(index);
  33526. var positions = morphTarget.getPositions();
  33527. if (!positions) {
  33528. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33529. return;
  33530. }
  33531. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33532. var normals = morphTarget.getNormals();
  33533. if (normals) {
  33534. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33535. }
  33536. var tangents = morphTarget.getTangents();
  33537. if (tangents) {
  33538. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33539. }
  33540. }
  33541. }
  33542. else {
  33543. var index = 0;
  33544. // Positions
  33545. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33546. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33547. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33548. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33549. }
  33550. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33551. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33552. }
  33553. index++;
  33554. }
  33555. }
  33556. };
  33557. // Statics
  33558. /**
  33559. * Returns a new Mesh object parsed from the source provided.
  33560. * The parameter `parsedMesh` is the source.
  33561. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33562. */
  33563. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33564. var mesh;
  33565. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33566. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33567. }
  33568. else {
  33569. mesh = new Mesh(parsedMesh.name, scene);
  33570. }
  33571. mesh.id = parsedMesh.id;
  33572. if (BABYLON.Tags) {
  33573. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33574. }
  33575. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33576. if (parsedMesh.metadata !== undefined) {
  33577. mesh.metadata = parsedMesh.metadata;
  33578. }
  33579. if (parsedMesh.rotationQuaternion) {
  33580. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33581. }
  33582. else if (parsedMesh.rotation) {
  33583. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33584. }
  33585. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33586. if (parsedMesh.localMatrix) {
  33587. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33588. }
  33589. else if (parsedMesh.pivotMatrix) {
  33590. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33591. }
  33592. mesh.setEnabled(parsedMesh.isEnabled);
  33593. mesh.isVisible = parsedMesh.isVisible;
  33594. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33595. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33596. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33597. if (parsedMesh.applyFog !== undefined) {
  33598. mesh.applyFog = parsedMesh.applyFog;
  33599. }
  33600. if (parsedMesh.pickable !== undefined) {
  33601. mesh.isPickable = parsedMesh.pickable;
  33602. }
  33603. if (parsedMesh.alphaIndex !== undefined) {
  33604. mesh.alphaIndex = parsedMesh.alphaIndex;
  33605. }
  33606. mesh.receiveShadows = parsedMesh.receiveShadows;
  33607. mesh.billboardMode = parsedMesh.billboardMode;
  33608. if (parsedMesh.visibility !== undefined) {
  33609. mesh.visibility = parsedMesh.visibility;
  33610. }
  33611. mesh.checkCollisions = parsedMesh.checkCollisions;
  33612. if (parsedMesh.isBlocker !== undefined) {
  33613. mesh.isBlocker = parsedMesh.isBlocker;
  33614. }
  33615. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33616. // freezeWorldMatrix
  33617. if (parsedMesh.freezeWorldMatrix) {
  33618. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33619. }
  33620. // Parent
  33621. if (parsedMesh.parentId) {
  33622. mesh._waitingParentId = parsedMesh.parentId;
  33623. }
  33624. // Actions
  33625. if (parsedMesh.actions !== undefined) {
  33626. mesh._waitingActions = parsedMesh.actions;
  33627. }
  33628. // Overlay
  33629. if (parsedMesh.overlayAlpha !== undefined) {
  33630. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33631. }
  33632. if (parsedMesh.overlayColor !== undefined) {
  33633. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33634. }
  33635. if (parsedMesh.renderOverlay !== undefined) {
  33636. mesh.renderOverlay = parsedMesh.renderOverlay;
  33637. }
  33638. // Geometry
  33639. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33640. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33641. if (parsedMesh.delayLoadingFile) {
  33642. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33643. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33644. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33645. if (parsedMesh._binaryInfo) {
  33646. mesh._binaryInfo = parsedMesh._binaryInfo;
  33647. }
  33648. mesh._delayInfo = [];
  33649. if (parsedMesh.hasUVs) {
  33650. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33651. }
  33652. if (parsedMesh.hasUVs2) {
  33653. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33654. }
  33655. if (parsedMesh.hasUVs3) {
  33656. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33657. }
  33658. if (parsedMesh.hasUVs4) {
  33659. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33660. }
  33661. if (parsedMesh.hasUVs5) {
  33662. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33663. }
  33664. if (parsedMesh.hasUVs6) {
  33665. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33666. }
  33667. if (parsedMesh.hasColors) {
  33668. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33669. }
  33670. if (parsedMesh.hasMatricesIndices) {
  33671. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33672. }
  33673. if (parsedMesh.hasMatricesWeights) {
  33674. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33675. }
  33676. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33677. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33678. mesh._checkDelayState();
  33679. }
  33680. }
  33681. else {
  33682. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33683. }
  33684. // Material
  33685. if (parsedMesh.materialId) {
  33686. mesh.setMaterialByID(parsedMesh.materialId);
  33687. }
  33688. else {
  33689. mesh.material = null;
  33690. }
  33691. // Morph targets
  33692. if (parsedMesh.morphTargetManagerId > -1) {
  33693. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33694. }
  33695. // Skeleton
  33696. if (parsedMesh.skeletonId > -1) {
  33697. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33698. if (parsedMesh.numBoneInfluencers) {
  33699. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33700. }
  33701. }
  33702. // Animations
  33703. if (parsedMesh.animations) {
  33704. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33705. var parsedAnimation = parsedMesh.animations[animationIndex];
  33706. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33707. }
  33708. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33709. }
  33710. if (parsedMesh.autoAnimate) {
  33711. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33712. }
  33713. // Layer Mask
  33714. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33715. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33716. }
  33717. else {
  33718. mesh.layerMask = 0x0FFFFFFF;
  33719. }
  33720. // Physics
  33721. if (parsedMesh.physicsImpostor) {
  33722. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33723. mass: parsedMesh.physicsMass,
  33724. friction: parsedMesh.physicsFriction,
  33725. restitution: parsedMesh.physicsRestitution
  33726. }, scene);
  33727. }
  33728. // Instances
  33729. if (parsedMesh.instances) {
  33730. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33731. var parsedInstance = parsedMesh.instances[index];
  33732. var instance = mesh.createInstance(parsedInstance.name);
  33733. if (parsedInstance.id) {
  33734. instance.id = parsedInstance.id;
  33735. }
  33736. if (BABYLON.Tags) {
  33737. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33738. }
  33739. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33740. if (parsedInstance.parentId) {
  33741. instance._waitingParentId = parsedInstance.parentId;
  33742. }
  33743. if (parsedInstance.rotationQuaternion) {
  33744. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33745. }
  33746. else if (parsedInstance.rotation) {
  33747. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33748. }
  33749. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33750. instance.checkCollisions = mesh.checkCollisions;
  33751. if (parsedMesh.animations) {
  33752. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33753. parsedAnimation = parsedMesh.animations[animationIndex];
  33754. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33755. }
  33756. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33757. if (parsedMesh.autoAnimate) {
  33758. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33759. }
  33760. }
  33761. }
  33762. }
  33763. return mesh;
  33764. };
  33765. /**
  33766. * Creates a ribbon mesh.
  33767. * Please consider using the same method from the MeshBuilder class instead.
  33768. * 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.
  33769. *
  33770. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33771. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33772. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33773. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33774. * 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.
  33775. * 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.
  33776. * 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
  33777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33778. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33780. */
  33781. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33782. if (closeArray === void 0) { closeArray = false; }
  33783. if (updatable === void 0) { updatable = false; }
  33784. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33785. pathArray: pathArray,
  33786. closeArray: closeArray,
  33787. closePath: closePath,
  33788. offset: offset,
  33789. updatable: updatable,
  33790. sideOrientation: sideOrientation,
  33791. instance: instance
  33792. }, scene);
  33793. };
  33794. /**
  33795. * Creates a plane polygonal mesh. By default, this is a disc.
  33796. * Please consider using the same method from the MeshBuilder class instead.
  33797. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33798. * 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.
  33799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33800. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33802. */
  33803. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33804. if (scene === void 0) { scene = null; }
  33805. var options = {
  33806. radius: radius,
  33807. tessellation: tessellation,
  33808. sideOrientation: sideOrientation,
  33809. updatable: updatable
  33810. };
  33811. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33812. };
  33813. /**
  33814. * Creates a box mesh.
  33815. * Please consider using the same method from the MeshBuilder class instead.
  33816. * The parameter `size` sets the size (float) of each box side (default 1).
  33817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33818. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33820. */
  33821. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33822. if (scene === void 0) { scene = null; }
  33823. var options = {
  33824. size: size,
  33825. sideOrientation: sideOrientation,
  33826. updatable: updatable
  33827. };
  33828. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33829. };
  33830. /**
  33831. * Creates a sphere mesh.
  33832. * Please consider using the same method from the MeshBuilder class instead.
  33833. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33834. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33836. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33838. */
  33839. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33840. var options = {
  33841. segments: segments,
  33842. diameterX: diameter,
  33843. diameterY: diameter,
  33844. diameterZ: diameter,
  33845. sideOrientation: sideOrientation,
  33846. updatable: updatable
  33847. };
  33848. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33849. };
  33850. /**
  33851. * Creates a cylinder or a cone mesh.
  33852. * Please consider using the same method from the MeshBuilder class instead.
  33853. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33854. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33855. * 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.
  33856. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33857. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33858. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33859. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33861. */
  33862. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33863. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33864. if (scene !== undefined) {
  33865. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33866. updatable = scene;
  33867. }
  33868. scene = subdivisions;
  33869. subdivisions = 1;
  33870. }
  33871. var options = {
  33872. height: height,
  33873. diameterTop: diameterTop,
  33874. diameterBottom: diameterBottom,
  33875. tessellation: tessellation,
  33876. subdivisions: subdivisions,
  33877. sideOrientation: sideOrientation,
  33878. updatable: updatable
  33879. };
  33880. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33881. };
  33882. // Torus (Code from SharpDX.org)
  33883. /**
  33884. * Creates a torus mesh.
  33885. * Please consider using the same method from the MeshBuilder class instead.
  33886. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33887. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33888. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33889. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33890. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33892. */
  33893. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33894. var options = {
  33895. diameter: diameter,
  33896. thickness: thickness,
  33897. tessellation: tessellation,
  33898. sideOrientation: sideOrientation,
  33899. updatable: updatable
  33900. };
  33901. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33902. };
  33903. /**
  33904. * Creates a torus knot mesh.
  33905. * Please consider using the same method from the MeshBuilder class instead.
  33906. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33907. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33908. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33909. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33911. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33913. */
  33914. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33915. var options = {
  33916. radius: radius,
  33917. tube: tube,
  33918. radialSegments: radialSegments,
  33919. tubularSegments: tubularSegments,
  33920. p: p,
  33921. q: q,
  33922. sideOrientation: sideOrientation,
  33923. updatable: updatable
  33924. };
  33925. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33926. };
  33927. /**
  33928. * Creates a line mesh.
  33929. * Please consider using the same method from the MeshBuilder class instead.
  33930. * 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.
  33931. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33932. * The parameter `points` is an array successive Vector3.
  33933. * 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
  33934. * When updating an instance, remember that only point positions can change, not the number of points.
  33935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33936. */
  33937. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33938. if (scene === void 0) { scene = null; }
  33939. if (updatable === void 0) { updatable = false; }
  33940. if (instance === void 0) { instance = null; }
  33941. var options = {
  33942. points: points,
  33943. updatable: updatable,
  33944. instance: instance
  33945. };
  33946. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33947. };
  33948. /**
  33949. * Creates a dashed line mesh.
  33950. * Please consider using the same method from the MeshBuilder class instead.
  33951. * 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.
  33952. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33953. * The parameter `points` is an array successive Vector3.
  33954. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33955. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33956. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33957. * 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
  33958. * When updating an instance, remember that only point positions can change, not the number of points.
  33959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33960. */
  33961. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33962. if (scene === void 0) { scene = null; }
  33963. var options = {
  33964. points: points,
  33965. dashSize: dashSize,
  33966. gapSize: gapSize,
  33967. dashNb: dashNb,
  33968. updatable: updatable,
  33969. instance: instance
  33970. };
  33971. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33972. };
  33973. /**
  33974. * Creates a polygon mesh.
  33975. * Please consider using the same method from the MeshBuilder class instead.
  33976. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33977. * 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.
  33978. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33980. * Remember you can only change the shape positions, not their number when updating a polygon.
  33981. */
  33982. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33983. var options = {
  33984. shape: shape,
  33985. holes: holes,
  33986. updatable: updatable,
  33987. sideOrientation: sideOrientation
  33988. };
  33989. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33990. };
  33991. /**
  33992. * Creates an extruded polygon mesh, with depth in the Y direction.
  33993. * Please consider using the same method from the MeshBuilder class instead.
  33994. */
  33995. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33996. var options = {
  33997. shape: shape,
  33998. holes: holes,
  33999. depth: depth,
  34000. updatable: updatable,
  34001. sideOrientation: sideOrientation
  34002. };
  34003. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34004. };
  34005. /**
  34006. * Creates an extruded shape mesh.
  34007. * 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.
  34008. * Please consider using the same method from the MeshBuilder class instead.
  34009. *
  34010. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34011. * 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
  34012. * extruded along the Z axis.
  34013. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34014. * 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.
  34015. * The parameter `scale` (float, default 1) is the value to scale the shape.
  34016. * 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
  34017. * 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
  34018. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34020. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34022. */
  34023. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34024. if (scene === void 0) { scene = null; }
  34025. var options = {
  34026. shape: shape,
  34027. path: path,
  34028. scale: scale,
  34029. rotation: rotation,
  34030. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34031. sideOrientation: sideOrientation,
  34032. instance: instance,
  34033. updatable: updatable
  34034. };
  34035. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34036. };
  34037. /**
  34038. * Creates an custom extruded shape mesh.
  34039. * 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.
  34040. * Please consider using the same method from the MeshBuilder class instead.
  34041. *
  34042. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34043. * 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
  34044. * extruded along the Z axis.
  34045. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34046. * 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
  34047. * and the distance of this point from the begining of the path :
  34048. * ```javascript
  34049. * var rotationFunction = function(i, distance) {
  34050. * // do things
  34051. * return rotationValue; }
  34052. * ```
  34053. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34054. * 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
  34055. * and the distance of this point from the begining of the path :
  34056. * ```javascript
  34057. * var scaleFunction = function(i, distance) {
  34058. * // do things
  34059. * return scaleValue;}
  34060. * ```
  34061. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34062. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34063. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34064. * 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
  34065. * 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
  34066. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34068. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34070. */
  34071. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34072. var options = {
  34073. shape: shape,
  34074. path: path,
  34075. scaleFunction: scaleFunction,
  34076. rotationFunction: rotationFunction,
  34077. ribbonCloseArray: ribbonCloseArray,
  34078. ribbonClosePath: ribbonClosePath,
  34079. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34080. sideOrientation: sideOrientation,
  34081. instance: instance,
  34082. updatable: updatable
  34083. };
  34084. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34085. };
  34086. /**
  34087. * Creates lathe mesh.
  34088. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34089. * Please consider using the same method from the MeshBuilder class instead.
  34090. * 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
  34091. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34092. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34093. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34095. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34097. */
  34098. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34099. var options = {
  34100. shape: shape,
  34101. radius: radius,
  34102. tessellation: tessellation,
  34103. sideOrientation: sideOrientation,
  34104. updatable: updatable
  34105. };
  34106. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34107. };
  34108. /**
  34109. * Creates a plane mesh.
  34110. * Please consider using the same method from the MeshBuilder class instead.
  34111. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34113. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34115. */
  34116. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34117. var options = {
  34118. size: size,
  34119. width: size,
  34120. height: size,
  34121. sideOrientation: sideOrientation,
  34122. updatable: updatable
  34123. };
  34124. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34125. };
  34126. /**
  34127. * Creates a ground mesh.
  34128. * Please consider using the same method from the MeshBuilder class instead.
  34129. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34130. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34132. */
  34133. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34134. var options = {
  34135. width: width,
  34136. height: height,
  34137. subdivisions: subdivisions,
  34138. updatable: updatable
  34139. };
  34140. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34141. };
  34142. /**
  34143. * Creates a tiled ground mesh.
  34144. * Please consider using the same method from the MeshBuilder class instead.
  34145. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34146. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34147. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34148. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34149. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34150. * numbers of subdivisions on the ground width and height of each tile.
  34151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34152. */
  34153. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34154. var options = {
  34155. xmin: xmin,
  34156. zmin: zmin,
  34157. xmax: xmax,
  34158. zmax: zmax,
  34159. subdivisions: subdivisions,
  34160. precision: precision,
  34161. updatable: updatable
  34162. };
  34163. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34164. };
  34165. /**
  34166. * Creates a ground mesh from a height map.
  34167. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34168. * Please consider using the same method from the MeshBuilder class instead.
  34169. * The parameter `url` sets the URL of the height map image resource.
  34170. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34171. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34172. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34173. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34174. * 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).
  34175. * This function is passed the newly built mesh :
  34176. * ```javascript
  34177. * function(mesh) { // do things
  34178. * return; }
  34179. * ```
  34180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34181. */
  34182. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34183. var options = {
  34184. width: width,
  34185. height: height,
  34186. subdivisions: subdivisions,
  34187. minHeight: minHeight,
  34188. maxHeight: maxHeight,
  34189. updatable: updatable,
  34190. onReady: onReady
  34191. };
  34192. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34193. };
  34194. /**
  34195. * Creates a tube mesh.
  34196. * 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.
  34197. * Please consider using the same method from the MeshBuilder class instead.
  34198. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34199. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34200. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34201. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34202. * 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.
  34203. * It must return a radius value (positive float) :
  34204. * ```javascript
  34205. * var radiusFunction = function(i, distance) {
  34206. * // do things
  34207. * return radius; }
  34208. * ```
  34209. * 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
  34210. * 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
  34211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34212. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34214. */
  34215. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34216. var options = {
  34217. path: path,
  34218. radius: radius,
  34219. tessellation: tessellation,
  34220. radiusFunction: radiusFunction,
  34221. arc: 1,
  34222. cap: cap,
  34223. updatable: updatable,
  34224. sideOrientation: sideOrientation,
  34225. instance: instance
  34226. };
  34227. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34228. };
  34229. /**
  34230. * Creates a polyhedron mesh.
  34231. * Please consider using the same method from the MeshBuilder class instead.
  34232. * 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
  34233. * to choose the wanted type.
  34234. * The parameter `size` (positive float, default 1) sets the polygon size.
  34235. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34236. * 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`.
  34237. * 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
  34238. * 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)`).
  34239. * 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
  34240. * 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.
  34241. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34242. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34244. */
  34245. Mesh.CreatePolyhedron = function (name, options, scene) {
  34246. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34247. };
  34248. /**
  34249. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34250. * Please consider using the same method from the MeshBuilder class instead.
  34251. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34252. * 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`).
  34253. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34254. * 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.
  34255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34256. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34258. */
  34259. Mesh.CreateIcoSphere = function (name, options, scene) {
  34260. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34261. };
  34262. /**
  34263. * Creates a decal mesh.
  34264. * Please consider using the same method from the MeshBuilder class instead.
  34265. * 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.
  34266. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34267. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34268. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34269. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34270. */
  34271. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34272. var options = {
  34273. position: position,
  34274. normal: normal,
  34275. size: size,
  34276. angle: angle
  34277. };
  34278. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34279. };
  34280. // Skeletons
  34281. /**
  34282. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34283. */
  34284. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34285. if (!this._sourcePositions) {
  34286. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34287. if (!source) {
  34288. return this._sourcePositions;
  34289. }
  34290. this._sourcePositions = new Float32Array(source);
  34291. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34292. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34293. }
  34294. }
  34295. return this._sourcePositions;
  34296. };
  34297. /**
  34298. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34299. */
  34300. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34301. if (!this._sourceNormals) {
  34302. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34303. if (!source) {
  34304. return this._sourceNormals;
  34305. }
  34306. this._sourceNormals = new Float32Array(source);
  34307. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34308. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34309. }
  34310. }
  34311. return this._sourceNormals;
  34312. };
  34313. /**
  34314. * Updates the vertex buffer by applying transformation from the bones.
  34315. * Returns the Mesh.
  34316. *
  34317. * @param {skeleton} skeleton to apply
  34318. */
  34319. Mesh.prototype.applySkeleton = function (skeleton) {
  34320. if (!this.geometry) {
  34321. return this;
  34322. }
  34323. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34324. return this;
  34325. }
  34326. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34327. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34328. return this;
  34329. }
  34330. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34331. return this;
  34332. }
  34333. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34334. return this;
  34335. }
  34336. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34337. return this;
  34338. }
  34339. if (!this._sourcePositions) {
  34340. var submeshes = this.subMeshes.slice();
  34341. this.setPositionsForCPUSkinning();
  34342. this.subMeshes = submeshes;
  34343. }
  34344. if (!this._sourceNormals) {
  34345. this.setNormalsForCPUSkinning();
  34346. }
  34347. // positionsData checks for not being Float32Array will only pass at most once
  34348. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34349. if (!positionsData) {
  34350. return this;
  34351. }
  34352. if (!(positionsData instanceof Float32Array)) {
  34353. positionsData = new Float32Array(positionsData);
  34354. }
  34355. // normalsData checks for not being Float32Array will only pass at most once
  34356. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34357. if (!normalsData) {
  34358. return this;
  34359. }
  34360. if (!(normalsData instanceof Float32Array)) {
  34361. normalsData = new Float32Array(normalsData);
  34362. }
  34363. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34364. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34365. if (!matricesWeightsData || !matricesIndicesData) {
  34366. return this;
  34367. }
  34368. var needExtras = this.numBoneInfluencers > 4;
  34369. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34370. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34371. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34372. var tempVector3 = BABYLON.Vector3.Zero();
  34373. var finalMatrix = new BABYLON.Matrix();
  34374. var tempMatrix = new BABYLON.Matrix();
  34375. var matWeightIdx = 0;
  34376. var inf;
  34377. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34378. var weight;
  34379. for (inf = 0; inf < 4; inf++) {
  34380. weight = matricesWeightsData[matWeightIdx + inf];
  34381. if (weight > 0) {
  34382. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34383. finalMatrix.addToSelf(tempMatrix);
  34384. }
  34385. else
  34386. break;
  34387. }
  34388. if (needExtras) {
  34389. for (inf = 0; inf < 4; inf++) {
  34390. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34391. if (weight > 0) {
  34392. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34393. finalMatrix.addToSelf(tempMatrix);
  34394. }
  34395. else
  34396. break;
  34397. }
  34398. }
  34399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34400. tempVector3.toArray(positionsData, index);
  34401. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34402. tempVector3.toArray(normalsData, index);
  34403. finalMatrix.reset();
  34404. }
  34405. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34406. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34407. return this;
  34408. };
  34409. // Tools
  34410. /**
  34411. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34412. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34413. */
  34414. Mesh.MinMax = function (meshes) {
  34415. var minVector = null;
  34416. var maxVector = null;
  34417. meshes.forEach(function (mesh, index, array) {
  34418. var boundingInfo = mesh.getBoundingInfo();
  34419. var boundingBox = boundingInfo.boundingBox;
  34420. if (!minVector || !maxVector) {
  34421. minVector = boundingBox.minimumWorld;
  34422. maxVector = boundingBox.maximumWorld;
  34423. }
  34424. else {
  34425. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34426. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34427. }
  34428. });
  34429. if (!minVector || !maxVector) {
  34430. return {
  34431. min: BABYLON.Vector3.Zero(),
  34432. max: BABYLON.Vector3.Zero()
  34433. };
  34434. }
  34435. return {
  34436. min: minVector,
  34437. max: maxVector
  34438. };
  34439. };
  34440. /**
  34441. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34442. */
  34443. Mesh.Center = function (meshesOrMinMaxVector) {
  34444. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34445. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34446. };
  34447. /**
  34448. * Merge the array of meshes into a single mesh for performance reasons.
  34449. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34450. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34451. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34452. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34453. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34454. */
  34455. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34456. if (disposeSource === void 0) { disposeSource = true; }
  34457. var index;
  34458. if (!allow32BitsIndices) {
  34459. var totalVertices = 0;
  34460. // Counting vertices
  34461. for (index = 0; index < meshes.length; index++) {
  34462. if (meshes[index]) {
  34463. totalVertices += meshes[index].getTotalVertices();
  34464. if (totalVertices > 65536) {
  34465. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34466. return null;
  34467. }
  34468. }
  34469. }
  34470. }
  34471. // Merge
  34472. var vertexData = null;
  34473. var otherVertexData;
  34474. var indiceArray = new Array();
  34475. var source = null;
  34476. for (index = 0; index < meshes.length; index++) {
  34477. if (meshes[index]) {
  34478. meshes[index].computeWorldMatrix(true);
  34479. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34480. otherVertexData.transform(meshes[index].getWorldMatrix());
  34481. if (vertexData) {
  34482. vertexData.merge(otherVertexData);
  34483. }
  34484. else {
  34485. vertexData = otherVertexData;
  34486. source = meshes[index];
  34487. }
  34488. if (subdivideWithSubMeshes) {
  34489. indiceArray.push(meshes[index].getTotalIndices());
  34490. }
  34491. }
  34492. }
  34493. source = source;
  34494. if (!meshSubclass) {
  34495. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34496. }
  34497. vertexData.applyToMesh(meshSubclass);
  34498. // Setting properties
  34499. meshSubclass.material = source.material;
  34500. meshSubclass.checkCollisions = source.checkCollisions;
  34501. // Cleaning
  34502. if (disposeSource) {
  34503. for (index = 0; index < meshes.length; index++) {
  34504. if (meshes[index]) {
  34505. meshes[index].dispose();
  34506. }
  34507. }
  34508. }
  34509. // Subdivide
  34510. if (subdivideWithSubMeshes) {
  34511. //-- removal of global submesh
  34512. meshSubclass.releaseSubMeshes();
  34513. index = 0;
  34514. var offset = 0;
  34515. //-- apply subdivision according to index table
  34516. while (index < indiceArray.length) {
  34517. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34518. offset += indiceArray[index];
  34519. index++;
  34520. }
  34521. }
  34522. return meshSubclass;
  34523. };
  34524. // Consts
  34525. Mesh._FRONTSIDE = 0;
  34526. Mesh._BACKSIDE = 1;
  34527. Mesh._DOUBLESIDE = 2;
  34528. Mesh._DEFAULTSIDE = 0;
  34529. Mesh._NO_CAP = 0;
  34530. Mesh._CAP_START = 1;
  34531. Mesh._CAP_END = 2;
  34532. Mesh._CAP_ALL = 3;
  34533. return Mesh;
  34534. }(BABYLON.AbstractMesh));
  34535. BABYLON.Mesh = Mesh;
  34536. })(BABYLON || (BABYLON = {}));
  34537. //# sourceMappingURL=babylon.mesh.js.map
  34538. var BABYLON;
  34539. (function (BABYLON) {
  34540. var BaseSubMesh = /** @class */ (function () {
  34541. function BaseSubMesh() {
  34542. }
  34543. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34544. get: function () {
  34545. return this._materialEffect;
  34546. },
  34547. enumerable: true,
  34548. configurable: true
  34549. });
  34550. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34551. if (defines === void 0) { defines = null; }
  34552. if (this._materialEffect === effect) {
  34553. if (!effect) {
  34554. this._materialDefines = null;
  34555. }
  34556. return;
  34557. }
  34558. this._materialDefines = defines;
  34559. this._materialEffect = effect;
  34560. };
  34561. return BaseSubMesh;
  34562. }());
  34563. BABYLON.BaseSubMesh = BaseSubMesh;
  34564. var SubMesh = /** @class */ (function (_super) {
  34565. __extends(SubMesh, _super);
  34566. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34567. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34568. var _this = _super.call(this) || this;
  34569. _this.materialIndex = materialIndex;
  34570. _this.verticesStart = verticesStart;
  34571. _this.verticesCount = verticesCount;
  34572. _this.indexStart = indexStart;
  34573. _this.indexCount = indexCount;
  34574. _this._renderId = 0;
  34575. _this._mesh = mesh;
  34576. _this._renderingMesh = renderingMesh || mesh;
  34577. mesh.subMeshes.push(_this);
  34578. _this._trianglePlanes = [];
  34579. _this._id = mesh.subMeshes.length - 1;
  34580. if (createBoundingBox) {
  34581. _this.refreshBoundingInfo();
  34582. mesh.computeWorldMatrix(true);
  34583. }
  34584. return _this;
  34585. }
  34586. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34587. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34588. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34589. };
  34590. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34591. get: function () {
  34592. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. /**
  34598. * Returns the submesh BoudingInfo object.
  34599. */
  34600. SubMesh.prototype.getBoundingInfo = function () {
  34601. if (this.IsGlobal) {
  34602. return this._mesh.getBoundingInfo();
  34603. }
  34604. return this._boundingInfo;
  34605. };
  34606. /**
  34607. * Sets the submesh BoundingInfo.
  34608. * Return the SubMesh.
  34609. */
  34610. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34611. this._boundingInfo = boundingInfo;
  34612. return this;
  34613. };
  34614. /**
  34615. * Returns the mesh of the current submesh.
  34616. */
  34617. SubMesh.prototype.getMesh = function () {
  34618. return this._mesh;
  34619. };
  34620. /**
  34621. * Returns the rendering mesh of the submesh.
  34622. */
  34623. SubMesh.prototype.getRenderingMesh = function () {
  34624. return this._renderingMesh;
  34625. };
  34626. /**
  34627. * Returns the submesh material.
  34628. */
  34629. SubMesh.prototype.getMaterial = function () {
  34630. var rootMaterial = this._renderingMesh.material;
  34631. if (rootMaterial === null || rootMaterial === undefined) {
  34632. return this._mesh.getScene().defaultMaterial;
  34633. }
  34634. else if (rootMaterial.getSubMaterial) {
  34635. var multiMaterial = rootMaterial;
  34636. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34637. if (this._currentMaterial !== effectiveMaterial) {
  34638. this._currentMaterial = effectiveMaterial;
  34639. this._materialDefines = null;
  34640. }
  34641. return effectiveMaterial;
  34642. }
  34643. return rootMaterial;
  34644. };
  34645. // Methods
  34646. /**
  34647. * Sets a new updated BoundingInfo object to the submesh.
  34648. * Returns the SubMesh.
  34649. */
  34650. SubMesh.prototype.refreshBoundingInfo = function () {
  34651. this._lastColliderWorldVertices = null;
  34652. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34653. return this;
  34654. }
  34655. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34656. if (!data) {
  34657. this._boundingInfo = this._mesh.getBoundingInfo();
  34658. return this;
  34659. }
  34660. var indices = this._renderingMesh.getIndices();
  34661. var extend;
  34662. //is this the only submesh?
  34663. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34664. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34665. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34666. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34667. }
  34668. else {
  34669. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34670. }
  34671. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34672. return this;
  34673. };
  34674. SubMesh.prototype._checkCollision = function (collider) {
  34675. var boundingInfo = this.getBoundingInfo();
  34676. return boundingInfo._checkCollision(collider);
  34677. };
  34678. /**
  34679. * Updates the submesh BoundingInfo.
  34680. * Returns the Submesh.
  34681. */
  34682. SubMesh.prototype.updateBoundingInfo = function (world) {
  34683. var boundingInfo = this.getBoundingInfo();
  34684. if (!boundingInfo) {
  34685. this.refreshBoundingInfo();
  34686. boundingInfo = this.getBoundingInfo();
  34687. }
  34688. boundingInfo.update(world);
  34689. return this;
  34690. };
  34691. /**
  34692. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34693. * Boolean returned.
  34694. */
  34695. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34696. var boundingInfo = this.getBoundingInfo();
  34697. if (!boundingInfo) {
  34698. return false;
  34699. }
  34700. return boundingInfo.isInFrustum(frustumPlanes);
  34701. };
  34702. /**
  34703. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34704. * Boolean returned.
  34705. */
  34706. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34707. var boundingInfo = this.getBoundingInfo();
  34708. if (!boundingInfo) {
  34709. return false;
  34710. }
  34711. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34712. };
  34713. /**
  34714. * Renders the submesh.
  34715. * Returns it.
  34716. */
  34717. SubMesh.prototype.render = function (enableAlphaMode) {
  34718. this._renderingMesh.render(this, enableAlphaMode);
  34719. return this;
  34720. };
  34721. /**
  34722. * Returns a new Index Buffer.
  34723. * Type returned : WebGLBuffer.
  34724. */
  34725. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34726. if (!this._linesIndexBuffer) {
  34727. var linesIndices = [];
  34728. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34729. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34730. }
  34731. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34732. this.linesIndexCount = linesIndices.length;
  34733. }
  34734. return this._linesIndexBuffer;
  34735. };
  34736. /**
  34737. * True is the passed Ray intersects the submesh bounding box.
  34738. * Boolean returned.
  34739. */
  34740. SubMesh.prototype.canIntersects = function (ray) {
  34741. var boundingInfo = this.getBoundingInfo();
  34742. if (!boundingInfo) {
  34743. return false;
  34744. }
  34745. return ray.intersectsBox(boundingInfo.boundingBox);
  34746. };
  34747. /**
  34748. * Returns an object IntersectionInfo.
  34749. */
  34750. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34751. var intersectInfo = null;
  34752. var material = this.getMaterial();
  34753. if (!material) {
  34754. return null;
  34755. }
  34756. switch (material.fillMode) {
  34757. case BABYLON.Material.PointListDrawMode:
  34758. case BABYLON.Material.LineListDrawMode:
  34759. case BABYLON.Material.LineLoopDrawMode:
  34760. case BABYLON.Material.LineStripDrawMode:
  34761. case BABYLON.Material.TriangleFanDrawMode:
  34762. case BABYLON.Material.TriangleStripDrawMode:
  34763. return null;
  34764. }
  34765. // LineMesh first as it's also a Mesh...
  34766. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34767. var lineMesh = this._mesh;
  34768. // Line test
  34769. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34770. var p0 = positions[indices[index]];
  34771. var p1 = positions[indices[index + 1]];
  34772. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34773. if (length < 0) {
  34774. continue;
  34775. }
  34776. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34777. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34778. if (fastCheck) {
  34779. break;
  34780. }
  34781. }
  34782. }
  34783. }
  34784. else {
  34785. // Triangles test
  34786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34787. var p0 = positions[indices[index]];
  34788. var p1 = positions[indices[index + 1]];
  34789. var p2 = positions[indices[index + 2]];
  34790. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34791. if (currentIntersectInfo) {
  34792. if (currentIntersectInfo.distance < 0) {
  34793. continue;
  34794. }
  34795. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34796. intersectInfo = currentIntersectInfo;
  34797. intersectInfo.faceId = index / 3;
  34798. if (fastCheck) {
  34799. break;
  34800. }
  34801. }
  34802. }
  34803. }
  34804. }
  34805. return intersectInfo;
  34806. };
  34807. SubMesh.prototype._rebuild = function () {
  34808. if (this._linesIndexBuffer) {
  34809. this._linesIndexBuffer = null;
  34810. }
  34811. };
  34812. // Clone
  34813. /**
  34814. * Creates a new Submesh from the passed Mesh.
  34815. */
  34816. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34817. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34818. if (!this.IsGlobal) {
  34819. var boundingInfo = this.getBoundingInfo();
  34820. if (!boundingInfo) {
  34821. return result;
  34822. }
  34823. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34824. }
  34825. return result;
  34826. };
  34827. // Dispose
  34828. /**
  34829. * Disposes the Submesh.
  34830. * Returns nothing.
  34831. */
  34832. SubMesh.prototype.dispose = function () {
  34833. if (this._linesIndexBuffer) {
  34834. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34835. this._linesIndexBuffer = null;
  34836. }
  34837. // Remove from mesh
  34838. var index = this._mesh.subMeshes.indexOf(this);
  34839. this._mesh.subMeshes.splice(index, 1);
  34840. };
  34841. // Statics
  34842. /**
  34843. * Creates a new Submesh from the passed parameters :
  34844. * - materialIndex (integer) : the index of the main mesh material.
  34845. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34846. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34847. * - mesh (Mesh) : the main mesh to create the submesh from.
  34848. * - renderingMesh (optional Mesh) : rendering mesh.
  34849. */
  34850. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34851. var minVertexIndex = Number.MAX_VALUE;
  34852. var maxVertexIndex = -Number.MAX_VALUE;
  34853. renderingMesh = (renderingMesh || mesh);
  34854. var indices = renderingMesh.getIndices();
  34855. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34856. var vertexIndex = indices[index];
  34857. if (vertexIndex < minVertexIndex)
  34858. minVertexIndex = vertexIndex;
  34859. if (vertexIndex > maxVertexIndex)
  34860. maxVertexIndex = vertexIndex;
  34861. }
  34862. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34863. };
  34864. return SubMesh;
  34865. }(BaseSubMesh));
  34866. BABYLON.SubMesh = SubMesh;
  34867. })(BABYLON || (BABYLON = {}));
  34868. //# sourceMappingURL=babylon.subMesh.js.map
  34869. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34870. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34871. s = arguments[i];
  34872. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34873. t[p] = s[p];
  34874. }
  34875. return t;
  34876. };
  34877. var BABYLON;
  34878. (function (BABYLON) {
  34879. /**
  34880. * Manages the defines for the Material
  34881. */
  34882. var MaterialDefines = /** @class */ (function () {
  34883. function MaterialDefines() {
  34884. this._isDirty = true;
  34885. /** @hidden */
  34886. this._areLightsDirty = true;
  34887. /** @hidden */
  34888. this._areAttributesDirty = true;
  34889. /** @hidden */
  34890. this._areTexturesDirty = true;
  34891. /** @hidden */
  34892. this._areFresnelDirty = true;
  34893. /** @hidden */
  34894. this._areMiscDirty = true;
  34895. /** @hidden */
  34896. this._areImageProcessingDirty = true;
  34897. /** @hidden */
  34898. this._normals = false;
  34899. /** @hidden */
  34900. this._uvs = false;
  34901. /** @hidden */
  34902. this._needNormals = false;
  34903. /** @hidden */
  34904. this._needUVs = false;
  34905. }
  34906. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34907. /**
  34908. * Specifies if the material needs to be re-calculated
  34909. */
  34910. get: function () {
  34911. return this._isDirty;
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. /**
  34917. * Marks the material to indicate that it has been re-calculated
  34918. */
  34919. MaterialDefines.prototype.markAsProcessed = function () {
  34920. this._isDirty = false;
  34921. this._areAttributesDirty = false;
  34922. this._areTexturesDirty = false;
  34923. this._areFresnelDirty = false;
  34924. this._areLightsDirty = false;
  34925. this._areMiscDirty = false;
  34926. this._areImageProcessingDirty = false;
  34927. };
  34928. /**
  34929. * Marks the material to indicate that it needs to be re-calculated
  34930. */
  34931. MaterialDefines.prototype.markAsUnprocessed = function () {
  34932. this._isDirty = true;
  34933. };
  34934. /**
  34935. * Marks the material to indicate all of its defines need to be re-calculated
  34936. */
  34937. MaterialDefines.prototype.markAllAsDirty = function () {
  34938. this._areTexturesDirty = true;
  34939. this._areAttributesDirty = true;
  34940. this._areLightsDirty = true;
  34941. this._areFresnelDirty = true;
  34942. this._areMiscDirty = true;
  34943. this._areImageProcessingDirty = true;
  34944. this._isDirty = true;
  34945. };
  34946. /**
  34947. * Marks the material to indicate that image processing needs to be re-calculated
  34948. */
  34949. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34950. this._areImageProcessingDirty = true;
  34951. this._isDirty = true;
  34952. };
  34953. /**
  34954. * Marks the material to indicate the lights need to be re-calculated
  34955. */
  34956. MaterialDefines.prototype.markAsLightDirty = function () {
  34957. this._areLightsDirty = true;
  34958. this._isDirty = true;
  34959. };
  34960. /**
  34961. * Marks the attribute state as changed
  34962. */
  34963. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34964. this._areAttributesDirty = true;
  34965. this._isDirty = true;
  34966. };
  34967. /**
  34968. * Marks the texture state as changed
  34969. */
  34970. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34971. this._areTexturesDirty = true;
  34972. this._isDirty = true;
  34973. };
  34974. /**
  34975. * Marks the fresnel state as changed
  34976. */
  34977. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34978. this._areFresnelDirty = true;
  34979. this._isDirty = true;
  34980. };
  34981. /**
  34982. * Marks the misc state as changed
  34983. */
  34984. MaterialDefines.prototype.markAsMiscDirty = function () {
  34985. this._areMiscDirty = true;
  34986. this._isDirty = true;
  34987. };
  34988. /**
  34989. * Rebuilds the material defines
  34990. */
  34991. MaterialDefines.prototype.rebuild = function () {
  34992. if (this._keys) {
  34993. delete this._keys;
  34994. }
  34995. this._keys = [];
  34996. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34997. var key = _a[_i];
  34998. if (key[0] === "_") {
  34999. continue;
  35000. }
  35001. this._keys.push(key);
  35002. }
  35003. };
  35004. /**
  35005. * Specifies if two material defines are equal
  35006. * @param other - A material define instance to compare to
  35007. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35008. */
  35009. MaterialDefines.prototype.isEqual = function (other) {
  35010. if (this._keys.length !== other._keys.length) {
  35011. return false;
  35012. }
  35013. for (var index = 0; index < this._keys.length; index++) {
  35014. var prop = this._keys[index];
  35015. if (this[prop] !== other[prop]) {
  35016. return false;
  35017. }
  35018. }
  35019. return true;
  35020. };
  35021. /**
  35022. * Clones this instance's defines to another instance
  35023. * @param other - material defines to clone values to
  35024. */
  35025. MaterialDefines.prototype.cloneTo = function (other) {
  35026. if (this._keys.length !== other._keys.length) {
  35027. other._keys = this._keys.slice(0);
  35028. }
  35029. for (var index = 0; index < this._keys.length; index++) {
  35030. var prop = this._keys[index];
  35031. other[prop] = this[prop];
  35032. }
  35033. };
  35034. /**
  35035. * Resets the material define values
  35036. */
  35037. MaterialDefines.prototype.reset = function () {
  35038. for (var index = 0; index < this._keys.length; index++) {
  35039. var prop = this._keys[index];
  35040. var type = typeof this[prop];
  35041. switch (type) {
  35042. case "number":
  35043. this[prop] = 0;
  35044. break;
  35045. case "string":
  35046. this[prop] = "";
  35047. break;
  35048. default:
  35049. this[prop] = false;
  35050. break;
  35051. }
  35052. }
  35053. };
  35054. /**
  35055. * Converts the material define values to a string
  35056. * @returns - String of material define information
  35057. */
  35058. MaterialDefines.prototype.toString = function () {
  35059. var result = "";
  35060. for (var index = 0; index < this._keys.length; index++) {
  35061. var prop = this._keys[index];
  35062. var value = this[prop];
  35063. var type = typeof value;
  35064. switch (type) {
  35065. case "number":
  35066. case "string":
  35067. result += "#define " + prop + " " + value + "\n";
  35068. break;
  35069. default:
  35070. if (value) {
  35071. result += "#define " + prop + "\n";
  35072. }
  35073. break;
  35074. }
  35075. }
  35076. return result;
  35077. };
  35078. return MaterialDefines;
  35079. }());
  35080. BABYLON.MaterialDefines = MaterialDefines;
  35081. /**
  35082. * Base class for the main features of a material in Babylon.js
  35083. */
  35084. var Material = /** @class */ (function () {
  35085. /**
  35086. * Creates a material instance
  35087. * @param name defines the name of the material
  35088. * @param scene defines the scene to reference
  35089. * @param doNotAdd specifies if the material should be added to the scene
  35090. */
  35091. function Material(name, scene, doNotAdd) {
  35092. /**
  35093. * Specifies if the ready state should be checked on each call
  35094. */
  35095. this.checkReadyOnEveryCall = false;
  35096. /**
  35097. * Specifies if the ready state should be checked once
  35098. */
  35099. this.checkReadyOnlyOnce = false;
  35100. /**
  35101. * The state of the material
  35102. */
  35103. this.state = "";
  35104. /**
  35105. * The alpha value of the material
  35106. */
  35107. this._alpha = 1.0;
  35108. /**
  35109. * Specifies if back face culling is enabled
  35110. */
  35111. this._backFaceCulling = true;
  35112. /**
  35113. * Specifies if the material should be serialized
  35114. */
  35115. this.doNotSerialize = false;
  35116. /**
  35117. * Specifies if the effect should be stored on sub meshes
  35118. */
  35119. this.storeEffectOnSubMeshes = false;
  35120. /**
  35121. * An event triggered when the material is disposed
  35122. */
  35123. this.onDisposeObservable = new BABYLON.Observable();
  35124. /**
  35125. * An event triggered when the material is bound
  35126. */
  35127. this.onBindObservable = new BABYLON.Observable();
  35128. /**
  35129. * An event triggered when the material is unbound
  35130. */
  35131. this.onUnBindObservable = new BABYLON.Observable();
  35132. /**
  35133. * Stores the value of the alpha mode
  35134. */
  35135. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35136. /**
  35137. * Stores the state of the need depth pre-pass value
  35138. */
  35139. this._needDepthPrePass = false;
  35140. /**
  35141. * Specifies if depth writing should be disabled
  35142. */
  35143. this.disableDepthWrite = false;
  35144. /**
  35145. * Specifies if depth writing should be forced
  35146. */
  35147. this.forceDepthWrite = false;
  35148. /**
  35149. * Specifies if there should be a separate pass for culling
  35150. */
  35151. this.separateCullingPass = false;
  35152. /**
  35153. * Stores the state specifing if fog should be enabled
  35154. */
  35155. this._fogEnabled = true;
  35156. /**
  35157. * Stores the size of points
  35158. */
  35159. this.pointSize = 1.0;
  35160. /**
  35161. * Stores the z offset value
  35162. */
  35163. this.zOffset = 0;
  35164. /**
  35165. * Specifies if the material was previously ready
  35166. */
  35167. this._wasPreviouslyReady = false;
  35168. /**
  35169. * Stores the fill mode state
  35170. */
  35171. this._fillMode = Material.TriangleFillMode;
  35172. this.name = name;
  35173. this.id = name || BABYLON.Tools.RandomId();
  35174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35175. this.uniqueId = this._scene.getUniqueId();
  35176. if (this._scene.useRightHandedSystem) {
  35177. this.sideOrientation = Material.ClockWiseSideOrientation;
  35178. }
  35179. else {
  35180. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35181. }
  35182. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35183. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35184. if (!doNotAdd) {
  35185. this._scene.materials.push(this);
  35186. }
  35187. }
  35188. Object.defineProperty(Material, "TriangleFillMode", {
  35189. /**
  35190. * Returns the triangle fill mode
  35191. */
  35192. get: function () {
  35193. return Material._TriangleFillMode;
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. Object.defineProperty(Material, "WireFrameFillMode", {
  35199. /**
  35200. * Returns the wireframe mode
  35201. */
  35202. get: function () {
  35203. return Material._WireFrameFillMode;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(Material, "PointFillMode", {
  35209. /**
  35210. * Returns the point fill mode
  35211. */
  35212. get: function () {
  35213. return Material._PointFillMode;
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(Material, "PointListDrawMode", {
  35219. /**
  35220. * Returns the point list draw mode
  35221. */
  35222. get: function () {
  35223. return Material._PointListDrawMode;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(Material, "LineListDrawMode", {
  35229. /**
  35230. * Returns the line list draw mode
  35231. */
  35232. get: function () {
  35233. return Material._LineListDrawMode;
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Material, "LineLoopDrawMode", {
  35239. /**
  35240. * Returns the line loop draw mode
  35241. */
  35242. get: function () {
  35243. return Material._LineLoopDrawMode;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(Material, "LineStripDrawMode", {
  35249. /**
  35250. * Returns the line strip draw mode
  35251. */
  35252. get: function () {
  35253. return Material._LineStripDrawMode;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35259. /**
  35260. * Returns the triangle strip draw mode
  35261. */
  35262. get: function () {
  35263. return Material._TriangleStripDrawMode;
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35269. /**
  35270. * Returns the triangle fan draw mode
  35271. */
  35272. get: function () {
  35273. return Material._TriangleFanDrawMode;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35279. /**
  35280. * Returns the clock-wise side orientation
  35281. */
  35282. get: function () {
  35283. return Material._ClockWiseSideOrientation;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35289. /**
  35290. * Returns the counter clock-wise side orientation
  35291. */
  35292. get: function () {
  35293. return Material._CounterClockWiseSideOrientation;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(Material, "TextureDirtyFlag", {
  35299. /**
  35300. * Returns the dirty texture flag value
  35301. */
  35302. get: function () {
  35303. return Material._TextureDirtyFlag;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(Material, "LightDirtyFlag", {
  35309. /**
  35310. * Returns the dirty light flag value
  35311. */
  35312. get: function () {
  35313. return Material._LightDirtyFlag;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35319. /**
  35320. * Returns the dirty fresnel flag value
  35321. */
  35322. get: function () {
  35323. return Material._FresnelDirtyFlag;
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35329. /**
  35330. * Returns the dirty attributes flag value
  35331. */
  35332. get: function () {
  35333. return Material._AttributesDirtyFlag;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(Material, "MiscDirtyFlag", {
  35339. /**
  35340. * Returns the dirty misc flag value
  35341. */
  35342. get: function () {
  35343. return Material._MiscDirtyFlag;
  35344. },
  35345. enumerable: true,
  35346. configurable: true
  35347. });
  35348. Object.defineProperty(Material.prototype, "alpha", {
  35349. /**
  35350. * Gets the alpha value of the material
  35351. */
  35352. get: function () {
  35353. return this._alpha;
  35354. },
  35355. /**
  35356. * Sets the alpha value of the material
  35357. */
  35358. set: function (value) {
  35359. if (this._alpha === value) {
  35360. return;
  35361. }
  35362. this._alpha = value;
  35363. this.markAsDirty(Material.MiscDirtyFlag);
  35364. },
  35365. enumerable: true,
  35366. configurable: true
  35367. });
  35368. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35369. /**
  35370. * Gets the back-face culling state
  35371. */
  35372. get: function () {
  35373. return this._backFaceCulling;
  35374. },
  35375. /**
  35376. * Sets the back-face culling state
  35377. */
  35378. set: function (value) {
  35379. if (this._backFaceCulling === value) {
  35380. return;
  35381. }
  35382. this._backFaceCulling = value;
  35383. this.markAsDirty(Material.TextureDirtyFlag);
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. Object.defineProperty(Material.prototype, "onDispose", {
  35389. /**
  35390. * Called during a dispose event
  35391. */
  35392. set: function (callback) {
  35393. if (this._onDisposeObserver) {
  35394. this.onDisposeObservable.remove(this._onDisposeObserver);
  35395. }
  35396. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(Material.prototype, "onBind", {
  35402. /**
  35403. * Called during a bind event
  35404. */
  35405. set: function (callback) {
  35406. if (this._onBindObserver) {
  35407. this.onBindObservable.remove(this._onBindObserver);
  35408. }
  35409. this._onBindObserver = this.onBindObservable.add(callback);
  35410. },
  35411. enumerable: true,
  35412. configurable: true
  35413. });
  35414. Object.defineProperty(Material.prototype, "alphaMode", {
  35415. /**
  35416. * Gets the value of the alpha mode
  35417. */
  35418. get: function () {
  35419. return this._alphaMode;
  35420. },
  35421. /**
  35422. * Sets the value of the alpha mode.
  35423. *
  35424. * | Value | Type | Description |
  35425. * | --- | --- | --- |
  35426. * | 0 | ALPHA_DISABLE | |
  35427. * | 1 | ALPHA_ADD | |
  35428. * | 2 | ALPHA_COMBINE | |
  35429. * | 3 | ALPHA_SUBTRACT | |
  35430. * | 4 | ALPHA_MULTIPLY | |
  35431. * | 5 | ALPHA_MAXIMIZED | |
  35432. * | 6 | ALPHA_ONEONE | |
  35433. * | 7 | ALPHA_PREMULTIPLIED | |
  35434. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35435. * | 9 | ALPHA_INTERPOLATE | |
  35436. * | 10 | ALPHA_SCREENMODE | |
  35437. *
  35438. */
  35439. set: function (value) {
  35440. if (this._alphaMode === value) {
  35441. return;
  35442. }
  35443. this._alphaMode = value;
  35444. this.markAsDirty(Material.TextureDirtyFlag);
  35445. },
  35446. enumerable: true,
  35447. configurable: true
  35448. });
  35449. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35450. /**
  35451. * Gets the depth pre-pass value
  35452. */
  35453. get: function () {
  35454. return this._needDepthPrePass;
  35455. },
  35456. /**
  35457. * Sets the need depth pre-pass value
  35458. */
  35459. set: function (value) {
  35460. if (this._needDepthPrePass === value) {
  35461. return;
  35462. }
  35463. this._needDepthPrePass = value;
  35464. if (this._needDepthPrePass) {
  35465. this.checkReadyOnEveryCall = true;
  35466. }
  35467. },
  35468. enumerable: true,
  35469. configurable: true
  35470. });
  35471. Object.defineProperty(Material.prototype, "fogEnabled", {
  35472. /**
  35473. * Gets the value of the fog enabled state
  35474. */
  35475. get: function () {
  35476. return this._fogEnabled;
  35477. },
  35478. /**
  35479. * Sets the state for enabling fog
  35480. */
  35481. set: function (value) {
  35482. if (this._fogEnabled === value) {
  35483. return;
  35484. }
  35485. this._fogEnabled = value;
  35486. this.markAsDirty(Material.MiscDirtyFlag);
  35487. },
  35488. enumerable: true,
  35489. configurable: true
  35490. });
  35491. Object.defineProperty(Material.prototype, "wireframe", {
  35492. /**
  35493. * Gets a value specifying if wireframe mode is enabled
  35494. */
  35495. get: function () {
  35496. switch (this._fillMode) {
  35497. case Material.WireFrameFillMode:
  35498. case Material.LineListDrawMode:
  35499. case Material.LineLoopDrawMode:
  35500. case Material.LineStripDrawMode:
  35501. return true;
  35502. }
  35503. return this._scene.forceWireframe;
  35504. },
  35505. /**
  35506. * Sets the state of wireframe mode
  35507. */
  35508. set: function (value) {
  35509. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35510. },
  35511. enumerable: true,
  35512. configurable: true
  35513. });
  35514. Object.defineProperty(Material.prototype, "pointsCloud", {
  35515. /**
  35516. * Gets the value specifying if point clouds are enabled
  35517. */
  35518. get: function () {
  35519. switch (this._fillMode) {
  35520. case Material.PointFillMode:
  35521. case Material.PointListDrawMode:
  35522. return true;
  35523. }
  35524. return this._scene.forcePointsCloud;
  35525. },
  35526. /**
  35527. * Sets the state of point cloud mode
  35528. */
  35529. set: function (value) {
  35530. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35531. },
  35532. enumerable: true,
  35533. configurable: true
  35534. });
  35535. Object.defineProperty(Material.prototype, "fillMode", {
  35536. /**
  35537. * Gets the material fill mode
  35538. */
  35539. get: function () {
  35540. return this._fillMode;
  35541. },
  35542. /**
  35543. * Sets the material fill mode
  35544. */
  35545. set: function (value) {
  35546. if (this._fillMode === value) {
  35547. return;
  35548. }
  35549. this._fillMode = value;
  35550. this.markAsDirty(Material.MiscDirtyFlag);
  35551. },
  35552. enumerable: true,
  35553. configurable: true
  35554. });
  35555. /**
  35556. * Returns a string representation of the current material
  35557. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35558. * @returns a string with material information
  35559. */
  35560. Material.prototype.toString = function (fullDetails) {
  35561. var ret = "Name: " + this.name;
  35562. if (fullDetails) {
  35563. }
  35564. return ret;
  35565. };
  35566. /**
  35567. * Gets the class name of the material
  35568. * @returns a string with the class name of the material
  35569. */
  35570. Material.prototype.getClassName = function () {
  35571. return "Material";
  35572. };
  35573. Object.defineProperty(Material.prototype, "isFrozen", {
  35574. /**
  35575. * Specifies if updates for the material been locked
  35576. */
  35577. get: function () {
  35578. return this.checkReadyOnlyOnce;
  35579. },
  35580. enumerable: true,
  35581. configurable: true
  35582. });
  35583. /**
  35584. * Locks updates for the material
  35585. */
  35586. Material.prototype.freeze = function () {
  35587. this.checkReadyOnlyOnce = true;
  35588. };
  35589. /**
  35590. * Unlocks updates for the material
  35591. */
  35592. Material.prototype.unfreeze = function () {
  35593. this.checkReadyOnlyOnce = false;
  35594. };
  35595. /**
  35596. * Specifies if the material is ready to be used
  35597. * @param mesh defines the mesh to check
  35598. * @param useInstances specifies if instances should be used
  35599. * @returns a boolean indicating if the material is ready to be used
  35600. */
  35601. Material.prototype.isReady = function (mesh, useInstances) {
  35602. return true;
  35603. };
  35604. /**
  35605. * Specifies that the submesh is ready to be used
  35606. * @param mesh defines the mesh to check
  35607. * @param subMesh defines which submesh to check
  35608. * @param useInstances specifies that instances should be used
  35609. * @returns a boolean indicating that the submesh is ready or not
  35610. */
  35611. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35612. return false;
  35613. };
  35614. /**
  35615. * Returns the material effect
  35616. * @returns the effect associated with the material
  35617. */
  35618. Material.prototype.getEffect = function () {
  35619. return this._effect;
  35620. };
  35621. /**
  35622. * Returns the current scene
  35623. * @returns a Scene
  35624. */
  35625. Material.prototype.getScene = function () {
  35626. return this._scene;
  35627. };
  35628. /**
  35629. * Specifies if the material will require alpha blending
  35630. * @returns a boolean specifying if alpha blending is needed
  35631. */
  35632. Material.prototype.needAlphaBlending = function () {
  35633. return (this.alpha < 1.0);
  35634. };
  35635. /**
  35636. * Specifies if the mesh will require alpha blending
  35637. * @param mesh defines the mesh to check
  35638. * @returns a boolean specifying if alpha blending is needed for the mesh
  35639. */
  35640. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35641. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35642. };
  35643. /**
  35644. * Specifies if this material should be rendered in alpha test mode
  35645. * @returns a boolean specifying if an alpha test is needed.
  35646. */
  35647. Material.prototype.needAlphaTesting = function () {
  35648. return false;
  35649. };
  35650. /**
  35651. * Gets the texture used for the alpha test
  35652. * @returns the texture to use for alpha testing
  35653. */
  35654. Material.prototype.getAlphaTestTexture = function () {
  35655. return null;
  35656. };
  35657. /**
  35658. * Marks the material to indicate that it needs to be re-calculated
  35659. */
  35660. Material.prototype.markDirty = function () {
  35661. this._wasPreviouslyReady = false;
  35662. };
  35663. /** @hidden */
  35664. Material.prototype._preBind = function (effect, overrideOrientation) {
  35665. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35666. var engine = this._scene.getEngine();
  35667. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35668. var reverse = orientation === Material.ClockWiseSideOrientation;
  35669. engine.enableEffect(effect ? effect : this._effect);
  35670. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35671. return reverse;
  35672. };
  35673. /**
  35674. * Binds the material to the mesh
  35675. * @param world defines the world transformation matrix
  35676. * @param mesh defines the mesh to bind the material to
  35677. */
  35678. Material.prototype.bind = function (world, mesh) {
  35679. };
  35680. /**
  35681. * Binds the submesh to the material
  35682. * @param world defines the world transformation matrix
  35683. * @param mesh defines the mesh containing the submesh
  35684. * @param subMesh defines the submesh to bind the material to
  35685. */
  35686. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35687. };
  35688. /**
  35689. * Binds the world matrix to the material
  35690. * @param world defines the world transformation matrix
  35691. */
  35692. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35693. };
  35694. /**
  35695. * Binds the scene's uniform buffer to the effect.
  35696. * @param effect defines the effect to bind to the scene uniform buffer
  35697. * @param sceneUbo defines the uniform buffer storing scene data
  35698. */
  35699. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35700. sceneUbo.bindToEffect(effect, "Scene");
  35701. };
  35702. /**
  35703. * Binds the view matrix to the effect
  35704. * @param effect defines the effect to bind the view matrix to
  35705. */
  35706. Material.prototype.bindView = function (effect) {
  35707. if (!this._useUBO) {
  35708. effect.setMatrix("view", this.getScene().getViewMatrix());
  35709. }
  35710. else {
  35711. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35712. }
  35713. };
  35714. /**
  35715. * Binds the view projection matrix to the effect
  35716. * @param effect defines the effect to bind the view projection matrix to
  35717. */
  35718. Material.prototype.bindViewProjection = function (effect) {
  35719. if (!this._useUBO) {
  35720. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35721. }
  35722. else {
  35723. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35724. }
  35725. };
  35726. /**
  35727. * Specifies if material alpha testing should be turned on for the mesh
  35728. * @param mesh defines the mesh to check
  35729. */
  35730. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35731. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35732. };
  35733. /**
  35734. * Processes to execute after binding the material to a mesh
  35735. * @param mesh defines the rendered mesh
  35736. */
  35737. Material.prototype._afterBind = function (mesh) {
  35738. this._scene._cachedMaterial = this;
  35739. if (mesh) {
  35740. this._scene._cachedVisibility = mesh.visibility;
  35741. }
  35742. else {
  35743. this._scene._cachedVisibility = 1;
  35744. }
  35745. if (mesh) {
  35746. this.onBindObservable.notifyObservers(mesh);
  35747. }
  35748. if (this.disableDepthWrite) {
  35749. var engine = this._scene.getEngine();
  35750. this._cachedDepthWriteState = engine.getDepthWrite();
  35751. engine.setDepthWrite(false);
  35752. }
  35753. };
  35754. /**
  35755. * Unbinds the material from the mesh
  35756. */
  35757. Material.prototype.unbind = function () {
  35758. this.onUnBindObservable.notifyObservers(this);
  35759. if (this.disableDepthWrite) {
  35760. var engine = this._scene.getEngine();
  35761. engine.setDepthWrite(this._cachedDepthWriteState);
  35762. }
  35763. };
  35764. /**
  35765. * Gets the active textures from the material
  35766. * @returns an array of textures
  35767. */
  35768. Material.prototype.getActiveTextures = function () {
  35769. return [];
  35770. };
  35771. /**
  35772. * Specifies if the material uses a texture
  35773. * @param texture defines the texture to check against the material
  35774. * @returns a boolean specifying if the material uses the texture
  35775. */
  35776. Material.prototype.hasTexture = function (texture) {
  35777. return false;
  35778. };
  35779. /**
  35780. * Makes a duplicate of the material, and gives it a new name
  35781. * @param name defines the new name for the duplicated material
  35782. * @returns the cloned material
  35783. */
  35784. Material.prototype.clone = function (name) {
  35785. return null;
  35786. };
  35787. /**
  35788. * Gets the meshes bound to the material
  35789. * @returns an array of meshes bound to the material
  35790. */
  35791. Material.prototype.getBindedMeshes = function () {
  35792. var result = new Array();
  35793. for (var index = 0; index < this._scene.meshes.length; index++) {
  35794. var mesh = this._scene.meshes[index];
  35795. if (mesh.material === this) {
  35796. result.push(mesh);
  35797. }
  35798. }
  35799. return result;
  35800. };
  35801. /**
  35802. * Force shader compilation
  35803. * @param mesh defines the mesh associated with this material
  35804. * @param onCompiled defines a function to execute once the material is compiled
  35805. * @param options defines the options to configure the compilation
  35806. */
  35807. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35808. var _this = this;
  35809. var localOptions = __assign({ clipPlane: false }, options);
  35810. var subMesh = new BABYLON.BaseSubMesh();
  35811. var scene = this.getScene();
  35812. var checkReady = function () {
  35813. if (!_this._scene || !_this._scene.getEngine()) {
  35814. return;
  35815. }
  35816. if (subMesh._materialDefines) {
  35817. subMesh._materialDefines._renderId = -1;
  35818. }
  35819. var clipPlaneState = scene.clipPlane;
  35820. if (localOptions.clipPlane) {
  35821. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35822. }
  35823. if (_this.storeEffectOnSubMeshes) {
  35824. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35825. if (onCompiled) {
  35826. onCompiled(_this);
  35827. }
  35828. }
  35829. else {
  35830. setTimeout(checkReady, 16);
  35831. }
  35832. }
  35833. else {
  35834. if (_this.isReady(mesh)) {
  35835. if (onCompiled) {
  35836. onCompiled(_this);
  35837. }
  35838. }
  35839. else {
  35840. setTimeout(checkReady, 16);
  35841. }
  35842. }
  35843. if (localOptions.clipPlane) {
  35844. scene.clipPlane = clipPlaneState;
  35845. }
  35846. };
  35847. checkReady();
  35848. };
  35849. /**
  35850. * Force shader compilation
  35851. * @param mesh defines the mesh that will use this material
  35852. * @param options defines additional options for compiling the shaders
  35853. * @returns a promise that resolves when the compilation completes
  35854. */
  35855. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35856. var _this = this;
  35857. return new Promise(function (resolve) {
  35858. _this.forceCompilation(mesh, function () {
  35859. resolve();
  35860. }, options);
  35861. });
  35862. };
  35863. /**
  35864. * Marks a define in the material to indicate that it needs to be re-computed
  35865. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35866. */
  35867. Material.prototype.markAsDirty = function (flag) {
  35868. if (flag & Material.TextureDirtyFlag) {
  35869. this._markAllSubMeshesAsTexturesDirty();
  35870. }
  35871. if (flag & Material.LightDirtyFlag) {
  35872. this._markAllSubMeshesAsLightsDirty();
  35873. }
  35874. if (flag & Material.FresnelDirtyFlag) {
  35875. this._markAllSubMeshesAsFresnelDirty();
  35876. }
  35877. if (flag & Material.AttributesDirtyFlag) {
  35878. this._markAllSubMeshesAsAttributesDirty();
  35879. }
  35880. if (flag & Material.MiscDirtyFlag) {
  35881. this._markAllSubMeshesAsMiscDirty();
  35882. }
  35883. this.getScene().resetCachedMaterial();
  35884. };
  35885. /**
  35886. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35887. * @param func defines a function which checks material defines against the submeshes
  35888. */
  35889. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35890. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35891. var mesh = _a[_i];
  35892. if (!mesh.subMeshes) {
  35893. continue;
  35894. }
  35895. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35896. var subMesh = _c[_b];
  35897. if (subMesh.getMaterial() !== this) {
  35898. continue;
  35899. }
  35900. if (!subMesh._materialDefines) {
  35901. continue;
  35902. }
  35903. func(subMesh._materialDefines);
  35904. }
  35905. }
  35906. };
  35907. /**
  35908. * Indicates that image processing needs to be re-calculated for all submeshes
  35909. */
  35910. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35911. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35912. };
  35913. /**
  35914. * Indicates that textures need to be re-calculated for all submeshes
  35915. */
  35916. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35917. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35918. };
  35919. /**
  35920. * Indicates that fresnel needs to be re-calculated for all submeshes
  35921. */
  35922. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35923. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35924. };
  35925. /**
  35926. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35927. */
  35928. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35929. this._markAllSubMeshesAsDirty(function (defines) {
  35930. defines.markAsFresnelDirty();
  35931. defines.markAsMiscDirty();
  35932. });
  35933. };
  35934. /**
  35935. * Indicates that lights need to be re-calculated for all submeshes
  35936. */
  35937. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35938. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35939. };
  35940. /**
  35941. * Indicates that attributes need to be re-calculated for all submeshes
  35942. */
  35943. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35944. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35945. };
  35946. /**
  35947. * Indicates that misc needs to be re-calculated for all submeshes
  35948. */
  35949. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35950. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35951. };
  35952. /**
  35953. * Indicates that textures and misc need to be re-calculated for all submeshes
  35954. */
  35955. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35956. this._markAllSubMeshesAsDirty(function (defines) {
  35957. defines.markAsTexturesDirty();
  35958. defines.markAsMiscDirty();
  35959. });
  35960. };
  35961. /**
  35962. * Disposes the material
  35963. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35964. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35965. */
  35966. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35967. // Animations
  35968. this.getScene().stopAnimation(this);
  35969. this.getScene().freeProcessedMaterials();
  35970. // Remove from scene
  35971. var index = this._scene.materials.indexOf(this);
  35972. if (index >= 0) {
  35973. this._scene.materials.splice(index, 1);
  35974. }
  35975. // Remove from meshes
  35976. for (index = 0; index < this._scene.meshes.length; index++) {
  35977. var mesh = this._scene.meshes[index];
  35978. if (mesh.material === this) {
  35979. mesh.material = null;
  35980. if (mesh.geometry) {
  35981. var geometry = (mesh.geometry);
  35982. if (this.storeEffectOnSubMeshes) {
  35983. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35984. var subMesh = _a[_i];
  35985. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35986. if (forceDisposeEffect && subMesh._materialEffect) {
  35987. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35988. }
  35989. }
  35990. }
  35991. else {
  35992. geometry._releaseVertexArrayObject(this._effect);
  35993. }
  35994. }
  35995. }
  35996. }
  35997. this._uniformBuffer.dispose();
  35998. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35999. if (forceDisposeEffect && this._effect) {
  36000. if (!this.storeEffectOnSubMeshes) {
  36001. this._scene.getEngine()._releaseEffect(this._effect);
  36002. }
  36003. this._effect = null;
  36004. }
  36005. // Callback
  36006. this.onDisposeObservable.notifyObservers(this);
  36007. this.onDisposeObservable.clear();
  36008. this.onBindObservable.clear();
  36009. this.onUnBindObservable.clear();
  36010. };
  36011. /**
  36012. * Serializes this material
  36013. * @returns the serialized material object
  36014. */
  36015. Material.prototype.serialize = function () {
  36016. return BABYLON.SerializationHelper.Serialize(this);
  36017. };
  36018. /**
  36019. * Creates a MultiMaterial from parsed MultiMaterial data.
  36020. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36021. * @param scene defines the hosting scene
  36022. * @returns a new MultiMaterial
  36023. */
  36024. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36025. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36026. multiMaterial.id = parsedMultiMaterial.id;
  36027. if (BABYLON.Tags) {
  36028. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36029. }
  36030. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36031. var subMatId = parsedMultiMaterial.materials[matIndex];
  36032. if (subMatId) {
  36033. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36034. }
  36035. else {
  36036. multiMaterial.subMaterials.push(null);
  36037. }
  36038. }
  36039. return multiMaterial;
  36040. };
  36041. /**
  36042. * Creates a material from parsed material data
  36043. * @param parsedMaterial defines parsed material data
  36044. * @param scene defines the hosting scene
  36045. * @param rootUrl defines the root URL to use to load textures
  36046. * @returns a new material
  36047. */
  36048. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36049. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36050. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36051. }
  36052. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36053. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36054. if (!BABYLON.LegacyPBRMaterial) {
  36055. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36056. return;
  36057. }
  36058. }
  36059. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36060. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36061. };
  36062. // Triangle views
  36063. Material._TriangleFillMode = 0;
  36064. Material._WireFrameFillMode = 1;
  36065. Material._PointFillMode = 2;
  36066. // Draw modes
  36067. Material._PointListDrawMode = 3;
  36068. Material._LineListDrawMode = 4;
  36069. Material._LineLoopDrawMode = 5;
  36070. Material._LineStripDrawMode = 6;
  36071. Material._TriangleStripDrawMode = 7;
  36072. Material._TriangleFanDrawMode = 8;
  36073. /**
  36074. * Stores the clock-wise side orientation
  36075. */
  36076. Material._ClockWiseSideOrientation = 0;
  36077. /**
  36078. * Stores the counter clock-wise side orientation
  36079. */
  36080. Material._CounterClockWiseSideOrientation = 1;
  36081. /**
  36082. * The dirty texture flag value
  36083. */
  36084. Material._TextureDirtyFlag = 1;
  36085. /**
  36086. * The dirty light flag value
  36087. */
  36088. Material._LightDirtyFlag = 2;
  36089. /**
  36090. * The dirty fresnel flag value
  36091. */
  36092. Material._FresnelDirtyFlag = 4;
  36093. /**
  36094. * The dirty attribute flag value
  36095. */
  36096. Material._AttributesDirtyFlag = 8;
  36097. /**
  36098. * The dirty misc flag value
  36099. */
  36100. Material._MiscDirtyFlag = 16;
  36101. __decorate([
  36102. BABYLON.serialize()
  36103. ], Material.prototype, "id", void 0);
  36104. __decorate([
  36105. BABYLON.serialize()
  36106. ], Material.prototype, "uniqueId", void 0);
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], Material.prototype, "name", void 0);
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36116. __decorate([
  36117. BABYLON.serialize()
  36118. ], Material.prototype, "state", void 0);
  36119. __decorate([
  36120. BABYLON.serialize("alpha")
  36121. ], Material.prototype, "_alpha", void 0);
  36122. __decorate([
  36123. BABYLON.serialize("backFaceCulling")
  36124. ], Material.prototype, "_backFaceCulling", void 0);
  36125. __decorate([
  36126. BABYLON.serialize()
  36127. ], Material.prototype, "sideOrientation", void 0);
  36128. __decorate([
  36129. BABYLON.serialize("alphaMode")
  36130. ], Material.prototype, "_alphaMode", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], Material.prototype, "_needDepthPrePass", void 0);
  36134. __decorate([
  36135. BABYLON.serialize()
  36136. ], Material.prototype, "disableDepthWrite", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], Material.prototype, "forceDepthWrite", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], Material.prototype, "separateCullingPass", void 0);
  36143. __decorate([
  36144. BABYLON.serialize("fogEnabled")
  36145. ], Material.prototype, "_fogEnabled", void 0);
  36146. __decorate([
  36147. BABYLON.serialize()
  36148. ], Material.prototype, "pointSize", void 0);
  36149. __decorate([
  36150. BABYLON.serialize()
  36151. ], Material.prototype, "zOffset", void 0);
  36152. __decorate([
  36153. BABYLON.serialize()
  36154. ], Material.prototype, "wireframe", null);
  36155. __decorate([
  36156. BABYLON.serialize()
  36157. ], Material.prototype, "pointsCloud", null);
  36158. __decorate([
  36159. BABYLON.serialize()
  36160. ], Material.prototype, "fillMode", null);
  36161. return Material;
  36162. }());
  36163. BABYLON.Material = Material;
  36164. })(BABYLON || (BABYLON = {}));
  36165. //# sourceMappingURL=babylon.material.js.map
  36166. var BABYLON;
  36167. (function (BABYLON) {
  36168. var UniformBuffer = /** @class */ (function () {
  36169. /**
  36170. * Uniform buffer objects.
  36171. *
  36172. * Handles blocks of uniform on the GPU.
  36173. *
  36174. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36175. *
  36176. * For more information, please refer to :
  36177. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36178. */
  36179. function UniformBuffer(engine, data, dynamic) {
  36180. this._engine = engine;
  36181. this._noUBO = !engine.supportsUniformBuffers;
  36182. this._dynamic = dynamic;
  36183. this._data = data || [];
  36184. this._uniformLocations = {};
  36185. this._uniformSizes = {};
  36186. this._uniformLocationPointer = 0;
  36187. this._needSync = false;
  36188. if (this._noUBO) {
  36189. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36190. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36191. this.updateFloat = this._updateFloatForEffect;
  36192. this.updateFloat2 = this._updateFloat2ForEffect;
  36193. this.updateFloat3 = this._updateFloat3ForEffect;
  36194. this.updateFloat4 = this._updateFloat4ForEffect;
  36195. this.updateMatrix = this._updateMatrixForEffect;
  36196. this.updateVector3 = this._updateVector3ForEffect;
  36197. this.updateVector4 = this._updateVector4ForEffect;
  36198. this.updateColor3 = this._updateColor3ForEffect;
  36199. this.updateColor4 = this._updateColor4ForEffect;
  36200. }
  36201. else {
  36202. this._engine._uniformBuffers.push(this);
  36203. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36204. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36205. this.updateFloat = this._updateFloatForUniform;
  36206. this.updateFloat2 = this._updateFloat2ForUniform;
  36207. this.updateFloat3 = this._updateFloat3ForUniform;
  36208. this.updateFloat4 = this._updateFloat4ForUniform;
  36209. this.updateMatrix = this._updateMatrixForUniform;
  36210. this.updateVector3 = this._updateVector3ForUniform;
  36211. this.updateVector4 = this._updateVector4ForUniform;
  36212. this.updateColor3 = this._updateColor3ForUniform;
  36213. this.updateColor4 = this._updateColor4ForUniform;
  36214. }
  36215. }
  36216. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36217. // Properties
  36218. /**
  36219. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36220. * or just falling back on setUniformXXX calls.
  36221. */
  36222. get: function () {
  36223. return !this._noUBO;
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36229. /**
  36230. * Indicates if the WebGL underlying uniform buffer is in sync
  36231. * with the javascript cache data.
  36232. */
  36233. get: function () {
  36234. return !this._needSync;
  36235. },
  36236. enumerable: true,
  36237. configurable: true
  36238. });
  36239. /**
  36240. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36241. * Also, a dynamic UniformBuffer will disable cache verification and always
  36242. * update the underlying WebGL uniform buffer to the GPU.
  36243. */
  36244. UniformBuffer.prototype.isDynamic = function () {
  36245. return this._dynamic !== undefined;
  36246. };
  36247. /**
  36248. * The data cache on JS side.
  36249. */
  36250. UniformBuffer.prototype.getData = function () {
  36251. return this._bufferData;
  36252. };
  36253. /**
  36254. * The underlying WebGL Uniform buffer.
  36255. */
  36256. UniformBuffer.prototype.getBuffer = function () {
  36257. return this._buffer;
  36258. };
  36259. /**
  36260. * std140 layout specifies how to align data within an UBO structure.
  36261. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36262. * for specs.
  36263. */
  36264. UniformBuffer.prototype._fillAlignment = function (size) {
  36265. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36266. // and 4x4 matrices
  36267. // TODO : change if other types are used
  36268. var alignment;
  36269. if (size <= 2) {
  36270. alignment = size;
  36271. }
  36272. else {
  36273. alignment = 4;
  36274. }
  36275. if ((this._uniformLocationPointer % alignment) !== 0) {
  36276. var oldPointer = this._uniformLocationPointer;
  36277. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36278. var diff = this._uniformLocationPointer - oldPointer;
  36279. for (var i = 0; i < diff; i++) {
  36280. this._data.push(0);
  36281. }
  36282. }
  36283. };
  36284. /**
  36285. * Adds an uniform in the buffer.
  36286. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36287. * for the layout to be correct !
  36288. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36289. * @param {number|number[]} size Data size, or data directly.
  36290. */
  36291. UniformBuffer.prototype.addUniform = function (name, size) {
  36292. if (this._noUBO) {
  36293. return;
  36294. }
  36295. if (this._uniformLocations[name] !== undefined) {
  36296. // Already existing uniform
  36297. return;
  36298. }
  36299. // This function must be called in the order of the shader layout !
  36300. // size can be the size of the uniform, or data directly
  36301. var data;
  36302. if (size instanceof Array) {
  36303. data = size;
  36304. size = data.length;
  36305. }
  36306. else {
  36307. size = size;
  36308. data = [];
  36309. // Fill with zeros
  36310. for (var i = 0; i < size; i++) {
  36311. data.push(0);
  36312. }
  36313. }
  36314. this._fillAlignment(size);
  36315. this._uniformSizes[name] = size;
  36316. this._uniformLocations[name] = this._uniformLocationPointer;
  36317. this._uniformLocationPointer += size;
  36318. for (var i = 0; i < size; i++) {
  36319. this._data.push(data[i]);
  36320. }
  36321. this._needSync = true;
  36322. };
  36323. /**
  36324. * Wrapper for addUniform.
  36325. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36326. * @param {Matrix} mat A 4x4 matrix.
  36327. */
  36328. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36329. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36330. };
  36331. /**
  36332. * Wrapper for addUniform.
  36333. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36334. * @param {number} x
  36335. * @param {number} y
  36336. */
  36337. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36338. var temp = [x, y];
  36339. this.addUniform(name, temp);
  36340. };
  36341. /**
  36342. * Wrapper for addUniform.
  36343. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36344. * @param {number} x
  36345. * @param {number} y
  36346. * @param {number} z
  36347. */
  36348. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36349. var temp = [x, y, z];
  36350. this.addUniform(name, temp);
  36351. };
  36352. /**
  36353. * Wrapper for addUniform.
  36354. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36355. * @param {Color3} color
  36356. */
  36357. UniformBuffer.prototype.addColor3 = function (name, color) {
  36358. var temp = new Array();
  36359. color.toArray(temp);
  36360. this.addUniform(name, temp);
  36361. };
  36362. /**
  36363. * Wrapper for addUniform.
  36364. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36365. * @param {Color3} color
  36366. * @param {number} alpha
  36367. */
  36368. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36369. var temp = new Array();
  36370. color.toArray(temp);
  36371. temp.push(alpha);
  36372. this.addUniform(name, temp);
  36373. };
  36374. /**
  36375. * Wrapper for addUniform.
  36376. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36377. * @param {Vector3} vector
  36378. */
  36379. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36380. var temp = new Array();
  36381. vector.toArray(temp);
  36382. this.addUniform(name, temp);
  36383. };
  36384. /**
  36385. * Wrapper for addUniform.
  36386. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36387. */
  36388. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36389. this.addUniform(name, 12);
  36390. };
  36391. /**
  36392. * Wrapper for addUniform.
  36393. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36394. */
  36395. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36396. this.addUniform(name, 8);
  36397. };
  36398. /**
  36399. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36400. */
  36401. UniformBuffer.prototype.create = function () {
  36402. if (this._noUBO) {
  36403. return;
  36404. }
  36405. if (this._buffer) {
  36406. return; // nothing to do
  36407. }
  36408. // See spec, alignment must be filled as a vec4
  36409. this._fillAlignment(4);
  36410. this._bufferData = new Float32Array(this._data);
  36411. this._rebuild();
  36412. this._needSync = true;
  36413. };
  36414. UniformBuffer.prototype._rebuild = function () {
  36415. if (this._noUBO) {
  36416. return;
  36417. }
  36418. if (this._dynamic) {
  36419. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36420. }
  36421. else {
  36422. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36423. }
  36424. };
  36425. /**
  36426. * Updates the WebGL Uniform Buffer on the GPU.
  36427. * If the `dynamic` flag is set to true, no cache comparison is done.
  36428. * Otherwise, the buffer will be updated only if the cache differs.
  36429. */
  36430. UniformBuffer.prototype.update = function () {
  36431. if (!this._buffer) {
  36432. this.create();
  36433. return;
  36434. }
  36435. if (!this._dynamic && !this._needSync) {
  36436. return;
  36437. }
  36438. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36439. this._needSync = false;
  36440. };
  36441. /**
  36442. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36443. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36444. * @param {number[]|Float32Array} data Flattened data
  36445. * @param {number} size Size of the data.
  36446. */
  36447. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36448. var location = this._uniformLocations[uniformName];
  36449. if (location === undefined) {
  36450. if (this._buffer) {
  36451. // Cannot add an uniform if the buffer is already created
  36452. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36453. return;
  36454. }
  36455. this.addUniform(uniformName, size);
  36456. location = this._uniformLocations[uniformName];
  36457. }
  36458. if (!this._buffer) {
  36459. this.create();
  36460. }
  36461. if (!this._dynamic) {
  36462. // Cache for static uniform buffers
  36463. var changed = false;
  36464. for (var i = 0; i < size; i++) {
  36465. if (this._bufferData[location + i] !== data[i]) {
  36466. changed = true;
  36467. this._bufferData[location + i] = data[i];
  36468. }
  36469. }
  36470. this._needSync = this._needSync || changed;
  36471. }
  36472. else {
  36473. // No cache for dynamic
  36474. for (var i = 0; i < size; i++) {
  36475. this._bufferData[location + i] = data[i];
  36476. }
  36477. }
  36478. };
  36479. // Update methods
  36480. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36481. // To match std140, matrix must be realigned
  36482. for (var i = 0; i < 3; i++) {
  36483. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36484. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36485. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36486. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36487. }
  36488. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36489. };
  36490. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36491. this._currentEffect.setMatrix3x3(name, matrix);
  36492. };
  36493. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36494. this._currentEffect.setMatrix2x2(name, matrix);
  36495. };
  36496. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36497. // To match std140, matrix must be realigned
  36498. for (var i = 0; i < 2; i++) {
  36499. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36500. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36501. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36502. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36503. }
  36504. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36505. };
  36506. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36507. this._currentEffect.setFloat(name, x);
  36508. };
  36509. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36510. UniformBuffer._tempBuffer[0] = x;
  36511. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36512. };
  36513. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36514. if (suffix === void 0) { suffix = ""; }
  36515. this._currentEffect.setFloat2(name + suffix, x, y);
  36516. };
  36517. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36518. if (suffix === void 0) { suffix = ""; }
  36519. UniformBuffer._tempBuffer[0] = x;
  36520. UniformBuffer._tempBuffer[1] = y;
  36521. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36522. };
  36523. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36524. if (suffix === void 0) { suffix = ""; }
  36525. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36526. };
  36527. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36528. if (suffix === void 0) { suffix = ""; }
  36529. UniformBuffer._tempBuffer[0] = x;
  36530. UniformBuffer._tempBuffer[1] = y;
  36531. UniformBuffer._tempBuffer[2] = z;
  36532. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36533. };
  36534. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36535. if (suffix === void 0) { suffix = ""; }
  36536. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36537. };
  36538. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36539. if (suffix === void 0) { suffix = ""; }
  36540. UniformBuffer._tempBuffer[0] = x;
  36541. UniformBuffer._tempBuffer[1] = y;
  36542. UniformBuffer._tempBuffer[2] = z;
  36543. UniformBuffer._tempBuffer[3] = w;
  36544. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36545. };
  36546. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36547. this._currentEffect.setMatrix(name, mat);
  36548. };
  36549. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36550. this.updateUniform(name, mat.toArray(), 16);
  36551. };
  36552. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36553. this._currentEffect.setVector3(name, vector);
  36554. };
  36555. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36556. vector.toArray(UniformBuffer._tempBuffer);
  36557. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36558. };
  36559. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36560. this._currentEffect.setVector4(name, vector);
  36561. };
  36562. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36563. vector.toArray(UniformBuffer._tempBuffer);
  36564. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36565. };
  36566. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36567. if (suffix === void 0) { suffix = ""; }
  36568. this._currentEffect.setColor3(name + suffix, color);
  36569. };
  36570. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36571. if (suffix === void 0) { suffix = ""; }
  36572. color.toArray(UniformBuffer._tempBuffer);
  36573. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36574. };
  36575. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36576. if (suffix === void 0) { suffix = ""; }
  36577. this._currentEffect.setColor4(name + suffix, color, alpha);
  36578. };
  36579. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36580. if (suffix === void 0) { suffix = ""; }
  36581. color.toArray(UniformBuffer._tempBuffer);
  36582. UniformBuffer._tempBuffer[3] = alpha;
  36583. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36584. };
  36585. /**
  36586. * Sets a sampler uniform on the effect.
  36587. * @param {string} name Name of the sampler.
  36588. * @param {Texture} texture
  36589. */
  36590. UniformBuffer.prototype.setTexture = function (name, texture) {
  36591. this._currentEffect.setTexture(name, texture);
  36592. };
  36593. /**
  36594. * Directly updates the value of the uniform in the cache AND on the GPU.
  36595. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36596. * @param {number[]|Float32Array} data Flattened data
  36597. */
  36598. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36599. this.updateUniform(uniformName, data, data.length);
  36600. this.update();
  36601. };
  36602. /**
  36603. * Binds this uniform buffer to an effect.
  36604. * @param {Effect} effect
  36605. * @param {string} name Name of the uniform block in the shader.
  36606. */
  36607. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36608. this._currentEffect = effect;
  36609. if (this._noUBO || !this._buffer) {
  36610. return;
  36611. }
  36612. effect.bindUniformBuffer(this._buffer, name);
  36613. };
  36614. /**
  36615. * Disposes the uniform buffer.
  36616. */
  36617. UniformBuffer.prototype.dispose = function () {
  36618. if (this._noUBO) {
  36619. return;
  36620. }
  36621. var index = this._engine._uniformBuffers.indexOf(this);
  36622. if (index !== -1) {
  36623. this._engine._uniformBuffers.splice(index, 1);
  36624. }
  36625. if (!this._buffer) {
  36626. return;
  36627. }
  36628. if (this._engine._releaseBuffer(this._buffer)) {
  36629. this._buffer = null;
  36630. }
  36631. };
  36632. // Pool for avoiding memory leaks
  36633. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36634. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36635. return UniformBuffer;
  36636. }());
  36637. BABYLON.UniformBuffer = UniformBuffer;
  36638. })(BABYLON || (BABYLON = {}));
  36639. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36640. var BABYLON;
  36641. (function (BABYLON) {
  36642. /**
  36643. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36644. */
  36645. var VertexData = /** @class */ (function () {
  36646. function VertexData() {
  36647. }
  36648. /**
  36649. * Uses the passed data array to set the set the values for the specified kind of data
  36650. * @param data a linear array of floating numbers
  36651. * @param kind the type of data that is being set, eg positions, colors etc
  36652. */
  36653. VertexData.prototype.set = function (data, kind) {
  36654. switch (kind) {
  36655. case BABYLON.VertexBuffer.PositionKind:
  36656. this.positions = data;
  36657. break;
  36658. case BABYLON.VertexBuffer.NormalKind:
  36659. this.normals = data;
  36660. break;
  36661. case BABYLON.VertexBuffer.TangentKind:
  36662. this.tangents = data;
  36663. break;
  36664. case BABYLON.VertexBuffer.UVKind:
  36665. this.uvs = data;
  36666. break;
  36667. case BABYLON.VertexBuffer.UV2Kind:
  36668. this.uvs2 = data;
  36669. break;
  36670. case BABYLON.VertexBuffer.UV3Kind:
  36671. this.uvs3 = data;
  36672. break;
  36673. case BABYLON.VertexBuffer.UV4Kind:
  36674. this.uvs4 = data;
  36675. break;
  36676. case BABYLON.VertexBuffer.UV5Kind:
  36677. this.uvs5 = data;
  36678. break;
  36679. case BABYLON.VertexBuffer.UV6Kind:
  36680. this.uvs6 = data;
  36681. break;
  36682. case BABYLON.VertexBuffer.ColorKind:
  36683. this.colors = data;
  36684. break;
  36685. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36686. this.matricesIndices = data;
  36687. break;
  36688. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36689. this.matricesWeights = data;
  36690. break;
  36691. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36692. this.matricesIndicesExtra = data;
  36693. break;
  36694. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36695. this.matricesWeightsExtra = data;
  36696. break;
  36697. }
  36698. };
  36699. /**
  36700. * Associates the vertexData to the passed Mesh.
  36701. * Sets it as updatable or not (default `false`)
  36702. * @param mesh the mesh the vertexData is applied to
  36703. * @param updatable when used and having the value true allows new data to update the vertexData
  36704. * @returns the VertexData
  36705. */
  36706. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36707. this._applyTo(mesh, updatable);
  36708. return this;
  36709. };
  36710. /**
  36711. * Associates the vertexData to the passed Geometry.
  36712. * Sets it as updatable or not (default `false`)
  36713. * @param geometry the geometry the vertexData is applied to
  36714. * @param updatable when used and having the value true allows new data to update the vertexData
  36715. * @returns VertexData
  36716. */
  36717. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36718. this._applyTo(geometry, updatable);
  36719. return this;
  36720. };
  36721. /**
  36722. * Updates the associated mesh
  36723. * @param mesh the mesh to be updated
  36724. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36725. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36726. * @returns VertexData
  36727. */
  36728. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36729. this._update(mesh);
  36730. return this;
  36731. };
  36732. /**
  36733. * Updates the associated geometry
  36734. * @param geometry the geometry to be updated
  36735. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36736. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36737. * @returns VertexData.
  36738. */
  36739. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36740. this._update(geometry);
  36741. return this;
  36742. };
  36743. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36744. if (updatable === void 0) { updatable = false; }
  36745. if (this.positions) {
  36746. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36747. }
  36748. if (this.normals) {
  36749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36750. }
  36751. if (this.tangents) {
  36752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36753. }
  36754. if (this.uvs) {
  36755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36756. }
  36757. if (this.uvs2) {
  36758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36759. }
  36760. if (this.uvs3) {
  36761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36762. }
  36763. if (this.uvs4) {
  36764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36765. }
  36766. if (this.uvs5) {
  36767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36768. }
  36769. if (this.uvs6) {
  36770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36771. }
  36772. if (this.colors) {
  36773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36774. }
  36775. if (this.matricesIndices) {
  36776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36777. }
  36778. if (this.matricesWeights) {
  36779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36780. }
  36781. if (this.matricesIndicesExtra) {
  36782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36783. }
  36784. if (this.matricesWeightsExtra) {
  36785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36786. }
  36787. if (this.indices) {
  36788. meshOrGeometry.setIndices(this.indices, null, updatable);
  36789. }
  36790. else {
  36791. meshOrGeometry.setIndices([], null);
  36792. }
  36793. return this;
  36794. };
  36795. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36796. if (this.positions) {
  36797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36798. }
  36799. if (this.normals) {
  36800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36801. }
  36802. if (this.tangents) {
  36803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36804. }
  36805. if (this.uvs) {
  36806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36807. }
  36808. if (this.uvs2) {
  36809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36810. }
  36811. if (this.uvs3) {
  36812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36813. }
  36814. if (this.uvs4) {
  36815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36816. }
  36817. if (this.uvs5) {
  36818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36819. }
  36820. if (this.uvs6) {
  36821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36822. }
  36823. if (this.colors) {
  36824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36825. }
  36826. if (this.matricesIndices) {
  36827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36828. }
  36829. if (this.matricesWeights) {
  36830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36831. }
  36832. if (this.matricesIndicesExtra) {
  36833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36834. }
  36835. if (this.matricesWeightsExtra) {
  36836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36837. }
  36838. if (this.indices) {
  36839. meshOrGeometry.setIndices(this.indices, null);
  36840. }
  36841. return this;
  36842. };
  36843. /**
  36844. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36845. * @param matrix the transforming matrix
  36846. * @returns the VertexData
  36847. */
  36848. VertexData.prototype.transform = function (matrix) {
  36849. var transformed = BABYLON.Vector3.Zero();
  36850. var index;
  36851. if (this.positions) {
  36852. var position = BABYLON.Vector3.Zero();
  36853. for (index = 0; index < this.positions.length; index += 3) {
  36854. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36855. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36856. this.positions[index] = transformed.x;
  36857. this.positions[index + 1] = transformed.y;
  36858. this.positions[index + 2] = transformed.z;
  36859. }
  36860. }
  36861. if (this.normals) {
  36862. var normal = BABYLON.Vector3.Zero();
  36863. for (index = 0; index < this.normals.length; index += 3) {
  36864. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36865. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36866. this.normals[index] = transformed.x;
  36867. this.normals[index + 1] = transformed.y;
  36868. this.normals[index + 2] = transformed.z;
  36869. }
  36870. }
  36871. if (this.tangents) {
  36872. var tangent = BABYLON.Vector4.Zero();
  36873. var tangentTransformed = BABYLON.Vector4.Zero();
  36874. for (index = 0; index < this.tangents.length; index += 4) {
  36875. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36876. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36877. this.tangents[index] = tangentTransformed.x;
  36878. this.tangents[index + 1] = tangentTransformed.y;
  36879. this.tangents[index + 2] = tangentTransformed.z;
  36880. this.tangents[index + 3] = tangentTransformed.w;
  36881. }
  36882. }
  36883. return this;
  36884. };
  36885. /**
  36886. * Merges the passed VertexData into the current one
  36887. * @param other the VertexData to be merged into the current one
  36888. * @returns the modified VertexData
  36889. */
  36890. VertexData.prototype.merge = function (other) {
  36891. this._validate();
  36892. other._validate();
  36893. if (!this.normals !== !other.normals ||
  36894. !this.tangents !== !other.tangents ||
  36895. !this.uvs !== !other.uvs ||
  36896. !this.uvs2 !== !other.uvs2 ||
  36897. !this.uvs3 !== !other.uvs3 ||
  36898. !this.uvs4 !== !other.uvs4 ||
  36899. !this.uvs5 !== !other.uvs5 ||
  36900. !this.uvs6 !== !other.uvs6 ||
  36901. !this.colors !== !other.colors ||
  36902. !this.matricesIndices !== !other.matricesIndices ||
  36903. !this.matricesWeights !== !other.matricesWeights ||
  36904. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36905. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36906. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36907. }
  36908. if (other.indices) {
  36909. if (!this.indices) {
  36910. this.indices = [];
  36911. }
  36912. var offset = this.positions ? this.positions.length / 3 : 0;
  36913. for (var index = 0; index < other.indices.length; index++) {
  36914. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36915. this.indices.push(other.indices[index] + offset);
  36916. }
  36917. }
  36918. this.positions = this._mergeElement(this.positions, other.positions);
  36919. this.normals = this._mergeElement(this.normals, other.normals);
  36920. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36921. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36922. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36923. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36924. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36925. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36926. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36927. this.colors = this._mergeElement(this.colors, other.colors);
  36928. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36929. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36930. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36931. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36932. return this;
  36933. };
  36934. VertexData.prototype._mergeElement = function (source, other) {
  36935. if (!source) {
  36936. return other;
  36937. }
  36938. if (!other) {
  36939. return source;
  36940. }
  36941. var len = other.length + source.length;
  36942. var isSrcTypedArray = source instanceof Float32Array;
  36943. var isOthTypedArray = other instanceof Float32Array;
  36944. // use non-loop method when the source is Float32Array
  36945. if (isSrcTypedArray) {
  36946. var ret32 = new Float32Array(len);
  36947. ret32.set(source);
  36948. ret32.set(other, source.length);
  36949. return ret32;
  36950. // source is number[], when other is also use concat
  36951. }
  36952. else if (!isOthTypedArray) {
  36953. return source.concat(other);
  36954. // source is a number[], but other is a Float32Array, loop required
  36955. }
  36956. else {
  36957. var ret = source.slice(0); // copy source to a separate array
  36958. for (var i = 0, len = other.length; i < len; i++) {
  36959. ret.push(other[i]);
  36960. }
  36961. return ret;
  36962. }
  36963. };
  36964. VertexData.prototype._validate = function () {
  36965. if (!this.positions) {
  36966. throw new Error("Positions are required");
  36967. }
  36968. var getElementCount = function (kind, values) {
  36969. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36970. if ((values.length % stride) !== 0) {
  36971. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36972. }
  36973. return values.length / stride;
  36974. };
  36975. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36976. var validateElementCount = function (kind, values) {
  36977. var elementCount = getElementCount(kind, values);
  36978. if (elementCount !== positionsElementCount) {
  36979. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36980. }
  36981. };
  36982. if (this.normals)
  36983. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36984. if (this.tangents)
  36985. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36986. if (this.uvs)
  36987. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36988. if (this.uvs2)
  36989. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36990. if (this.uvs3)
  36991. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36992. if (this.uvs4)
  36993. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36994. if (this.uvs5)
  36995. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36996. if (this.uvs6)
  36997. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36998. if (this.colors)
  36999. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37000. if (this.matricesIndices)
  37001. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37002. if (this.matricesWeights)
  37003. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37004. if (this.matricesIndicesExtra)
  37005. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37006. if (this.matricesWeightsExtra)
  37007. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37008. };
  37009. /**
  37010. * Serializes the VertexData
  37011. * @returns a serialized object
  37012. */
  37013. VertexData.prototype.serialize = function () {
  37014. var serializationObject = this.serialize();
  37015. if (this.positions) {
  37016. serializationObject.positions = this.positions;
  37017. }
  37018. if (this.normals) {
  37019. serializationObject.normals = this.normals;
  37020. }
  37021. if (this.tangents) {
  37022. serializationObject.tangents = this.tangents;
  37023. }
  37024. if (this.uvs) {
  37025. serializationObject.uvs = this.uvs;
  37026. }
  37027. if (this.uvs2) {
  37028. serializationObject.uvs2 = this.uvs2;
  37029. }
  37030. if (this.uvs3) {
  37031. serializationObject.uvs3 = this.uvs3;
  37032. }
  37033. if (this.uvs4) {
  37034. serializationObject.uvs4 = this.uvs4;
  37035. }
  37036. if (this.uvs5) {
  37037. serializationObject.uvs5 = this.uvs5;
  37038. }
  37039. if (this.uvs6) {
  37040. serializationObject.uvs6 = this.uvs6;
  37041. }
  37042. if (this.colors) {
  37043. serializationObject.colors = this.colors;
  37044. }
  37045. if (this.matricesIndices) {
  37046. serializationObject.matricesIndices = this.matricesIndices;
  37047. serializationObject.matricesIndices._isExpanded = true;
  37048. }
  37049. if (this.matricesWeights) {
  37050. serializationObject.matricesWeights = this.matricesWeights;
  37051. }
  37052. if (this.matricesIndicesExtra) {
  37053. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37054. serializationObject.matricesIndicesExtra._isExpanded = true;
  37055. }
  37056. if (this.matricesWeightsExtra) {
  37057. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37058. }
  37059. serializationObject.indices = this.indices;
  37060. return serializationObject;
  37061. };
  37062. // Statics
  37063. /**
  37064. * Extracts the vertexData from a mesh
  37065. * @param mesh the mesh from which to extract the VertexData
  37066. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37067. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37068. * @returns the object VertexData associated to the passed mesh
  37069. */
  37070. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37071. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37072. };
  37073. /**
  37074. * Extracts the vertexData from the geometry
  37075. * @param geometry the geometry from which to extract the VertexData
  37076. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37077. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37078. * @returns the object VertexData associated to the passed mesh
  37079. */
  37080. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37081. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37082. };
  37083. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37084. var result = new VertexData();
  37085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37086. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37087. }
  37088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37089. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37090. }
  37091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37092. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37093. }
  37094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37095. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37096. }
  37097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37098. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37099. }
  37100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37101. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37102. }
  37103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37104. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37105. }
  37106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37107. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37108. }
  37109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37110. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37111. }
  37112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37113. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37114. }
  37115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37116. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37117. }
  37118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37119. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37120. }
  37121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37122. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37123. }
  37124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37125. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37126. }
  37127. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37128. return result;
  37129. };
  37130. /**
  37131. * Creates the VertexData for a Ribbon
  37132. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37133. * * pathArray array of paths, each of which an array of successive Vector3
  37134. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37135. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37136. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  37137. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37138. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37139. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37140. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37141. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37142. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37143. * @returns the VertexData of the ribbon
  37144. */
  37145. VertexData.CreateRibbon = function (options) {
  37146. var pathArray = options.pathArray;
  37147. var closeArray = options.closeArray || false;
  37148. var closePath = options.closePath || false;
  37149. var invertUV = options.invertUV || false;
  37150. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37151. var offset = options.offset || defaultOffset;
  37152. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37153. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37154. var customUV = options.uvs;
  37155. var customColors = options.colors;
  37156. var positions = [];
  37157. var indices = [];
  37158. var normals = [];
  37159. var uvs = [];
  37160. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37161. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37162. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37163. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37164. var minlg; // minimal length among all paths from pathArray
  37165. var lg = []; // array of path lengths : nb of vertex per path
  37166. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37167. var p; // path iterator
  37168. var i; // point iterator
  37169. var j; // point iterator
  37170. // if single path in pathArray
  37171. if (pathArray.length < 2) {
  37172. var ar1 = [];
  37173. var ar2 = [];
  37174. for (i = 0; i < pathArray[0].length - offset; i++) {
  37175. ar1.push(pathArray[0][i]);
  37176. ar2.push(pathArray[0][i + offset]);
  37177. }
  37178. pathArray = [ar1, ar2];
  37179. }
  37180. // positions and horizontal distances (u)
  37181. var idc = 0;
  37182. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37183. var path;
  37184. var l;
  37185. minlg = pathArray[0].length;
  37186. var vectlg;
  37187. var dist;
  37188. for (p = 0; p < pathArray.length; p++) {
  37189. uTotalDistance[p] = 0;
  37190. us[p] = [0];
  37191. path = pathArray[p];
  37192. l = path.length;
  37193. minlg = (minlg < l) ? minlg : l;
  37194. j = 0;
  37195. while (j < l) {
  37196. positions.push(path[j].x, path[j].y, path[j].z);
  37197. if (j > 0) {
  37198. vectlg = path[j].subtract(path[j - 1]).length();
  37199. dist = vectlg + uTotalDistance[p];
  37200. us[p].push(dist);
  37201. uTotalDistance[p] = dist;
  37202. }
  37203. j++;
  37204. }
  37205. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37206. j--;
  37207. positions.push(path[0].x, path[0].y, path[0].z);
  37208. vectlg = path[j].subtract(path[0]).length();
  37209. dist = vectlg + uTotalDistance[p];
  37210. us[p].push(dist);
  37211. uTotalDistance[p] = dist;
  37212. }
  37213. lg[p] = l + closePathCorr;
  37214. idx[p] = idc;
  37215. idc += (l + closePathCorr);
  37216. }
  37217. // vertical distances (v)
  37218. var path1;
  37219. var path2;
  37220. var vertex1 = null;
  37221. var vertex2 = null;
  37222. for (i = 0; i < minlg + closePathCorr; i++) {
  37223. vTotalDistance[i] = 0;
  37224. vs[i] = [0];
  37225. for (p = 0; p < pathArray.length - 1; p++) {
  37226. path1 = pathArray[p];
  37227. path2 = pathArray[p + 1];
  37228. if (i === minlg) { // closePath
  37229. vertex1 = path1[0];
  37230. vertex2 = path2[0];
  37231. }
  37232. else {
  37233. vertex1 = path1[i];
  37234. vertex2 = path2[i];
  37235. }
  37236. vectlg = vertex2.subtract(vertex1).length();
  37237. dist = vectlg + vTotalDistance[i];
  37238. vs[i].push(dist);
  37239. vTotalDistance[i] = dist;
  37240. }
  37241. if (closeArray && vertex2 && vertex1) {
  37242. path1 = pathArray[p];
  37243. path2 = pathArray[0];
  37244. if (i === minlg) { // closePath
  37245. vertex2 = path2[0];
  37246. }
  37247. vectlg = vertex2.subtract(vertex1).length();
  37248. dist = vectlg + vTotalDistance[i];
  37249. vTotalDistance[i] = dist;
  37250. }
  37251. }
  37252. // uvs
  37253. var u;
  37254. var v;
  37255. if (customUV) {
  37256. for (p = 0; p < customUV.length; p++) {
  37257. uvs.push(customUV[p].x, customUV[p].y);
  37258. }
  37259. }
  37260. else {
  37261. for (p = 0; p < pathArray.length; p++) {
  37262. for (i = 0; i < minlg + closePathCorr; i++) {
  37263. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37264. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37265. if (invertUV) {
  37266. uvs.push(v, u);
  37267. }
  37268. else {
  37269. uvs.push(u, v);
  37270. }
  37271. }
  37272. }
  37273. }
  37274. // indices
  37275. p = 0; // path index
  37276. var pi = 0; // positions array index
  37277. var l1 = lg[p] - 1; // path1 length
  37278. var l2 = lg[p + 1] - 1; // path2 length
  37279. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37280. var shft = idx[1] - idx[0]; // shift
  37281. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37282. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37283. // 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
  37284. indices.push(pi, pi + shft, pi + 1);
  37285. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37286. pi += 1;
  37287. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37288. p++;
  37289. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37290. shft = idx[0] - idx[p];
  37291. l1 = lg[p] - 1;
  37292. l2 = lg[0] - 1;
  37293. }
  37294. else {
  37295. shft = idx[p + 1] - idx[p];
  37296. l1 = lg[p] - 1;
  37297. l2 = lg[p + 1] - 1;
  37298. }
  37299. pi = idx[p];
  37300. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37301. }
  37302. }
  37303. // normals
  37304. VertexData.ComputeNormals(positions, indices, normals);
  37305. if (closePath) { // update both the first and last vertex normals to their average value
  37306. var indexFirst = 0;
  37307. var indexLast = 0;
  37308. for (p = 0; p < pathArray.length; p++) {
  37309. indexFirst = idx[p] * 3;
  37310. if (p + 1 < pathArray.length) {
  37311. indexLast = (idx[p + 1] - 1) * 3;
  37312. }
  37313. else {
  37314. indexLast = normals.length - 3;
  37315. }
  37316. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37317. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37318. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37319. normals[indexLast] = normals[indexFirst];
  37320. normals[indexLast + 1] = normals[indexFirst + 1];
  37321. normals[indexLast + 2] = normals[indexFirst + 2];
  37322. }
  37323. }
  37324. // sides
  37325. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37326. // Colors
  37327. var colors = null;
  37328. if (customColors) {
  37329. colors = new Float32Array(customColors.length * 4);
  37330. for (var c = 0; c < customColors.length; c++) {
  37331. colors[c * 4] = customColors[c].r;
  37332. colors[c * 4 + 1] = customColors[c].g;
  37333. colors[c * 4 + 2] = customColors[c].b;
  37334. colors[c * 4 + 3] = customColors[c].a;
  37335. }
  37336. }
  37337. // Result
  37338. var vertexData = new VertexData();
  37339. var positions32 = new Float32Array(positions);
  37340. var normals32 = new Float32Array(normals);
  37341. var uvs32 = new Float32Array(uvs);
  37342. vertexData.indices = indices;
  37343. vertexData.positions = positions32;
  37344. vertexData.normals = normals32;
  37345. vertexData.uvs = uvs32;
  37346. if (colors) {
  37347. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37348. }
  37349. if (closePath) {
  37350. vertexData._idx = idx;
  37351. }
  37352. return vertexData;
  37353. };
  37354. /**
  37355. * Creates the VertexData for a box
  37356. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37357. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37358. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37359. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37360. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37361. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37362. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37363. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37364. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37365. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37366. * @returns the VertexData of the box
  37367. */
  37368. VertexData.CreateBox = function (options) {
  37369. var normalsSource = [
  37370. new BABYLON.Vector3(0, 0, 1),
  37371. new BABYLON.Vector3(0, 0, -1),
  37372. new BABYLON.Vector3(1, 0, 0),
  37373. new BABYLON.Vector3(-1, 0, 0),
  37374. new BABYLON.Vector3(0, 1, 0),
  37375. new BABYLON.Vector3(0, -1, 0)
  37376. ];
  37377. var indices = [];
  37378. var positions = [];
  37379. var normals = [];
  37380. var uvs = [];
  37381. var width = options.width || options.size || 1;
  37382. var height = options.height || options.size || 1;
  37383. var depth = options.depth || options.size || 1;
  37384. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37385. var faceUV = options.faceUV || new Array(6);
  37386. var faceColors = options.faceColors;
  37387. var colors = [];
  37388. // default face colors and UV if undefined
  37389. for (var f = 0; f < 6; f++) {
  37390. if (faceUV[f] === undefined) {
  37391. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37392. }
  37393. if (faceColors && faceColors[f] === undefined) {
  37394. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37395. }
  37396. }
  37397. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37398. // Create each face in turn.
  37399. for (var index = 0; index < normalsSource.length; index++) {
  37400. var normal = normalsSource[index];
  37401. // Get two vectors perpendicular to the face normal and to each other.
  37402. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37403. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37404. // Six indices (two triangles) per face.
  37405. var verticesLength = positions.length / 3;
  37406. indices.push(verticesLength);
  37407. indices.push(verticesLength + 1);
  37408. indices.push(verticesLength + 2);
  37409. indices.push(verticesLength);
  37410. indices.push(verticesLength + 2);
  37411. indices.push(verticesLength + 3);
  37412. // Four vertices per face.
  37413. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37414. positions.push(vertex.x, vertex.y, vertex.z);
  37415. normals.push(normal.x, normal.y, normal.z);
  37416. uvs.push(faceUV[index].z, faceUV[index].w);
  37417. if (faceColors) {
  37418. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37419. }
  37420. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37421. positions.push(vertex.x, vertex.y, vertex.z);
  37422. normals.push(normal.x, normal.y, normal.z);
  37423. uvs.push(faceUV[index].x, faceUV[index].w);
  37424. if (faceColors) {
  37425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37426. }
  37427. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37428. positions.push(vertex.x, vertex.y, vertex.z);
  37429. normals.push(normal.x, normal.y, normal.z);
  37430. uvs.push(faceUV[index].x, faceUV[index].y);
  37431. if (faceColors) {
  37432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37433. }
  37434. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37435. positions.push(vertex.x, vertex.y, vertex.z);
  37436. normals.push(normal.x, normal.y, normal.z);
  37437. uvs.push(faceUV[index].z, faceUV[index].y);
  37438. if (faceColors) {
  37439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37440. }
  37441. }
  37442. // sides
  37443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37444. // Result
  37445. var vertexData = new VertexData();
  37446. vertexData.indices = indices;
  37447. vertexData.positions = positions;
  37448. vertexData.normals = normals;
  37449. vertexData.uvs = uvs;
  37450. if (faceColors) {
  37451. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37452. vertexData.colors = totalColors;
  37453. }
  37454. return vertexData;
  37455. };
  37456. /**
  37457. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37458. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37459. * * segments sets the number of horizontal strips optional, default 32
  37460. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37461. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37462. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37463. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37464. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37465. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37466. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37467. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37468. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37469. * @returns the VertexData of the ellipsoid
  37470. */
  37471. VertexData.CreateSphere = function (options) {
  37472. var segments = options.segments || 32;
  37473. var diameterX = options.diameterX || options.diameter || 1;
  37474. var diameterY = options.diameterY || options.diameter || 1;
  37475. var diameterZ = options.diameterZ || options.diameter || 1;
  37476. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37477. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37479. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37480. var totalZRotationSteps = 2 + segments;
  37481. var totalYRotationSteps = 2 * totalZRotationSteps;
  37482. var indices = [];
  37483. var positions = [];
  37484. var normals = [];
  37485. var uvs = [];
  37486. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37487. var normalizedZ = zRotationStep / totalZRotationSteps;
  37488. var angleZ = normalizedZ * Math.PI * slice;
  37489. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37490. var normalizedY = yRotationStep / totalYRotationSteps;
  37491. var angleY = normalizedY * Math.PI * 2 * arc;
  37492. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37493. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37494. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37495. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37496. var vertex = complete.multiply(radius);
  37497. var normal = complete.divide(radius).normalize();
  37498. positions.push(vertex.x, vertex.y, vertex.z);
  37499. normals.push(normal.x, normal.y, normal.z);
  37500. uvs.push(normalizedY, normalizedZ);
  37501. }
  37502. if (zRotationStep > 0) {
  37503. var verticesCount = positions.length / 3;
  37504. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37505. indices.push((firstIndex));
  37506. indices.push((firstIndex + 1));
  37507. indices.push(firstIndex + totalYRotationSteps + 1);
  37508. indices.push((firstIndex + totalYRotationSteps + 1));
  37509. indices.push((firstIndex + 1));
  37510. indices.push((firstIndex + totalYRotationSteps + 2));
  37511. }
  37512. }
  37513. }
  37514. // Sides
  37515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37516. // Result
  37517. var vertexData = new VertexData();
  37518. vertexData.indices = indices;
  37519. vertexData.positions = positions;
  37520. vertexData.normals = normals;
  37521. vertexData.uvs = uvs;
  37522. return vertexData;
  37523. };
  37524. /**
  37525. * Creates the VertexData for a cylinder, cone or prism
  37526. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37527. * * height sets the height (y direction) of the cylinder, optional, default 2
  37528. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37529. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37530. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37531. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37532. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37533. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37534. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37535. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37536. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37537. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37538. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37539. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37540. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37541. * @returns the VertexData of the cylinder, cone or prism
  37542. */
  37543. VertexData.CreateCylinder = function (options) {
  37544. var height = options.height || 2;
  37545. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37546. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37547. var tessellation = options.tessellation || 24;
  37548. var subdivisions = options.subdivisions || 1;
  37549. var hasRings = options.hasRings ? true : false;
  37550. var enclose = options.enclose ? true : false;
  37551. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37553. var faceUV = options.faceUV || new Array(3);
  37554. var faceColors = options.faceColors;
  37555. // default face colors and UV if undefined
  37556. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37557. var ringNb = (hasRings) ? subdivisions : 1;
  37558. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37559. var f;
  37560. for (f = 0; f < surfaceNb; f++) {
  37561. if (faceColors && faceColors[f] === undefined) {
  37562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37563. }
  37564. }
  37565. for (f = 0; f < surfaceNb; f++) {
  37566. if (faceUV && faceUV[f] === undefined) {
  37567. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37568. }
  37569. }
  37570. var indices = new Array();
  37571. var positions = new Array();
  37572. var normals = new Array();
  37573. var uvs = new Array();
  37574. var colors = new Array();
  37575. var angle_step = Math.PI * 2 * arc / tessellation;
  37576. var angle;
  37577. var h;
  37578. var radius;
  37579. var tan = (diameterBottom - diameterTop) / 2 / height;
  37580. var ringVertex = BABYLON.Vector3.Zero();
  37581. var ringNormal = BABYLON.Vector3.Zero();
  37582. var ringFirstVertex = BABYLON.Vector3.Zero();
  37583. var ringFirstNormal = BABYLON.Vector3.Zero();
  37584. var quadNormal = BABYLON.Vector3.Zero();
  37585. var Y = BABYLON.Axis.Y;
  37586. // positions, normals, uvs
  37587. var i;
  37588. var j;
  37589. var r;
  37590. var ringIdx = 1;
  37591. var s = 1; // surface index
  37592. var cs = 0;
  37593. var v = 0;
  37594. for (i = 0; i <= subdivisions; i++) {
  37595. h = i / subdivisions;
  37596. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37597. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37598. for (r = 0; r < ringIdx; r++) {
  37599. if (hasRings) {
  37600. s += r;
  37601. }
  37602. if (enclose) {
  37603. s += 2 * r;
  37604. }
  37605. for (j = 0; j <= tessellation; j++) {
  37606. angle = j * angle_step;
  37607. // position
  37608. ringVertex.x = Math.cos(-angle) * radius;
  37609. ringVertex.y = -height / 2 + h * height;
  37610. ringVertex.z = Math.sin(-angle) * radius;
  37611. // normal
  37612. if (diameterTop === 0 && i === subdivisions) {
  37613. // if no top cap, reuse former normals
  37614. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37615. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37616. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37617. }
  37618. else {
  37619. ringNormal.x = ringVertex.x;
  37620. ringNormal.z = ringVertex.z;
  37621. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37622. ringNormal.normalize();
  37623. }
  37624. // keep first ring vertex values for enclose
  37625. if (j === 0) {
  37626. ringFirstVertex.copyFrom(ringVertex);
  37627. ringFirstNormal.copyFrom(ringNormal);
  37628. }
  37629. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37630. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37631. if (hasRings) {
  37632. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37633. }
  37634. else {
  37635. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37636. }
  37637. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37638. if (faceColors) {
  37639. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37640. }
  37641. }
  37642. // if enclose, add four vertices and their dedicated normals
  37643. if (arc !== 1 && enclose) {
  37644. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37645. positions.push(0, ringVertex.y, 0);
  37646. positions.push(0, ringVertex.y, 0);
  37647. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37648. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37649. quadNormal.normalize();
  37650. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37651. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37652. quadNormal.normalize();
  37653. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37654. if (hasRings) {
  37655. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37656. }
  37657. else {
  37658. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37659. }
  37660. uvs.push(faceUV[s + 1].x, v);
  37661. uvs.push(faceUV[s + 1].z, v);
  37662. if (hasRings) {
  37663. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37664. }
  37665. else {
  37666. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37667. }
  37668. uvs.push(faceUV[s + 2].x, v);
  37669. uvs.push(faceUV[s + 2].z, v);
  37670. if (faceColors) {
  37671. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37672. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37673. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37674. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37675. }
  37676. }
  37677. if (cs !== s) {
  37678. cs = s;
  37679. }
  37680. }
  37681. }
  37682. // indices
  37683. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37684. var s;
  37685. i = 0;
  37686. for (s = 0; s < subdivisions; s++) {
  37687. var i0 = 0;
  37688. var i1 = 0;
  37689. var i2 = 0;
  37690. var i3 = 0;
  37691. for (j = 0; j < tessellation; j++) {
  37692. i0 = i * (e + 1) + j;
  37693. i1 = (i + 1) * (e + 1) + j;
  37694. i2 = i * (e + 1) + (j + 1);
  37695. i3 = (i + 1) * (e + 1) + (j + 1);
  37696. indices.push(i0, i1, i2);
  37697. indices.push(i3, i2, i1);
  37698. }
  37699. if (arc !== 1 && enclose) { // if enclose, add two quads
  37700. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37701. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37702. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37703. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37704. }
  37705. i = (hasRings) ? (i + 2) : (i + 1);
  37706. }
  37707. // Caps
  37708. var createCylinderCap = function (isTop) {
  37709. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37710. if (radius === 0) {
  37711. return;
  37712. }
  37713. // Cap positions, normals & uvs
  37714. var angle;
  37715. var circleVector;
  37716. var i;
  37717. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37718. var c = null;
  37719. if (faceColors) {
  37720. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37721. }
  37722. // cap center
  37723. var vbase = positions.length / 3;
  37724. var offset = isTop ? height / 2 : -height / 2;
  37725. var center = new BABYLON.Vector3(0, offset, 0);
  37726. positions.push(center.x, center.y, center.z);
  37727. normals.push(0, isTop ? 1 : -1, 0);
  37728. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37729. if (c) {
  37730. colors.push(c.r, c.g, c.b, c.a);
  37731. }
  37732. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37733. for (i = 0; i <= tessellation; i++) {
  37734. angle = Math.PI * 2 * i * arc / tessellation;
  37735. var cos = Math.cos(-angle);
  37736. var sin = Math.sin(-angle);
  37737. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37738. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37739. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37740. normals.push(0, isTop ? 1 : -1, 0);
  37741. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37742. if (c) {
  37743. colors.push(c.r, c.g, c.b, c.a);
  37744. }
  37745. }
  37746. // Cap indices
  37747. for (i = 0; i < tessellation; i++) {
  37748. if (!isTop) {
  37749. indices.push(vbase);
  37750. indices.push(vbase + (i + 1));
  37751. indices.push(vbase + (i + 2));
  37752. }
  37753. else {
  37754. indices.push(vbase);
  37755. indices.push(vbase + (i + 2));
  37756. indices.push(vbase + (i + 1));
  37757. }
  37758. }
  37759. };
  37760. // add caps to geometry
  37761. createCylinderCap(false);
  37762. createCylinderCap(true);
  37763. // Sides
  37764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37765. var vertexData = new VertexData();
  37766. vertexData.indices = indices;
  37767. vertexData.positions = positions;
  37768. vertexData.normals = normals;
  37769. vertexData.uvs = uvs;
  37770. if (faceColors) {
  37771. vertexData.colors = colors;
  37772. }
  37773. return vertexData;
  37774. };
  37775. /**
  37776. * Creates the VertexData for a torus
  37777. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37778. * * diameter the diameter of the torus, optional default 1
  37779. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37780. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37781. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37782. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37783. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37784. * @returns the VertexData of the torus
  37785. */
  37786. VertexData.CreateTorus = function (options) {
  37787. var indices = [];
  37788. var positions = [];
  37789. var normals = [];
  37790. var uvs = [];
  37791. var diameter = options.diameter || 1;
  37792. var thickness = options.thickness || 0.5;
  37793. var tessellation = options.tessellation || 16;
  37794. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37795. var stride = tessellation + 1;
  37796. for (var i = 0; i <= tessellation; i++) {
  37797. var u = i / tessellation;
  37798. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37799. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37800. for (var j = 0; j <= tessellation; j++) {
  37801. var v = 1 - j / tessellation;
  37802. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37803. var dx = Math.cos(innerAngle);
  37804. var dy = Math.sin(innerAngle);
  37805. // Create a vertex.
  37806. var normal = new BABYLON.Vector3(dx, dy, 0);
  37807. var position = normal.scale(thickness / 2);
  37808. var textureCoordinate = new BABYLON.Vector2(u, v);
  37809. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37810. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37811. positions.push(position.x, position.y, position.z);
  37812. normals.push(normal.x, normal.y, normal.z);
  37813. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37814. // And create indices for two triangles.
  37815. var nextI = (i + 1) % stride;
  37816. var nextJ = (j + 1) % stride;
  37817. indices.push(i * stride + j);
  37818. indices.push(i * stride + nextJ);
  37819. indices.push(nextI * stride + j);
  37820. indices.push(i * stride + nextJ);
  37821. indices.push(nextI * stride + nextJ);
  37822. indices.push(nextI * stride + j);
  37823. }
  37824. }
  37825. // Sides
  37826. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37827. // Result
  37828. var vertexData = new VertexData();
  37829. vertexData.indices = indices;
  37830. vertexData.positions = positions;
  37831. vertexData.normals = normals;
  37832. vertexData.uvs = uvs;
  37833. return vertexData;
  37834. };
  37835. /**
  37836. * Creates the VertexData of the LineSystem
  37837. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37838. * - lines an array of lines, each line being an array of successive Vector3
  37839. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37840. * @returns the VertexData of the LineSystem
  37841. */
  37842. VertexData.CreateLineSystem = function (options) {
  37843. var indices = [];
  37844. var positions = [];
  37845. var lines = options.lines;
  37846. var colors = options.colors;
  37847. var vertexColors = [];
  37848. var idx = 0;
  37849. for (var l = 0; l < lines.length; l++) {
  37850. var points = lines[l];
  37851. for (var index = 0; index < points.length; index++) {
  37852. positions.push(points[index].x, points[index].y, points[index].z);
  37853. if (colors) {
  37854. var color = colors[l];
  37855. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37856. }
  37857. if (index > 0) {
  37858. indices.push(idx - 1);
  37859. indices.push(idx);
  37860. }
  37861. idx++;
  37862. }
  37863. }
  37864. var vertexData = new VertexData();
  37865. vertexData.indices = indices;
  37866. vertexData.positions = positions;
  37867. if (colors) {
  37868. vertexData.colors = vertexColors;
  37869. }
  37870. return vertexData;
  37871. };
  37872. /**
  37873. * Create the VertexData for a DashedLines
  37874. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37875. * - points an array successive Vector3
  37876. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37877. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37878. * - dashNb the intended total number of dashes, optional, default 200
  37879. * @returns the VertexData for the DashedLines
  37880. */
  37881. VertexData.CreateDashedLines = function (options) {
  37882. var dashSize = options.dashSize || 3;
  37883. var gapSize = options.gapSize || 1;
  37884. var dashNb = options.dashNb || 200;
  37885. var points = options.points;
  37886. var positions = new Array();
  37887. var indices = new Array();
  37888. var curvect = BABYLON.Vector3.Zero();
  37889. var lg = 0;
  37890. var nb = 0;
  37891. var shft = 0;
  37892. var dashshft = 0;
  37893. var curshft = 0;
  37894. var idx = 0;
  37895. var i = 0;
  37896. for (i = 0; i < points.length - 1; i++) {
  37897. points[i + 1].subtractToRef(points[i], curvect);
  37898. lg += curvect.length();
  37899. }
  37900. shft = lg / dashNb;
  37901. dashshft = dashSize * shft / (dashSize + gapSize);
  37902. for (i = 0; i < points.length - 1; i++) {
  37903. points[i + 1].subtractToRef(points[i], curvect);
  37904. nb = Math.floor(curvect.length() / shft);
  37905. curvect.normalize();
  37906. for (var j = 0; j < nb; j++) {
  37907. curshft = shft * j;
  37908. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37909. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37910. indices.push(idx, idx + 1);
  37911. idx += 2;
  37912. }
  37913. }
  37914. // Result
  37915. var vertexData = new VertexData();
  37916. vertexData.positions = positions;
  37917. vertexData.indices = indices;
  37918. return vertexData;
  37919. };
  37920. /**
  37921. * Creates the VertexData for a Ground
  37922. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37923. * - width the width (x direction) of the ground, optional, default 1
  37924. * - height the height (z direction) of the ground, optional, default 1
  37925. * - subdivisions the number of subdivisions per side, optional, default 1
  37926. * @returns the VertexData of the Ground
  37927. */
  37928. VertexData.CreateGround = function (options) {
  37929. var indices = [];
  37930. var positions = [];
  37931. var normals = [];
  37932. var uvs = [];
  37933. var row, col;
  37934. var width = options.width || 1;
  37935. var height = options.height || 1;
  37936. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37937. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37938. for (row = 0; row <= subdivisionsY; row++) {
  37939. for (col = 0; col <= subdivisionsX; col++) {
  37940. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37941. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37942. positions.push(position.x, position.y, position.z);
  37943. normals.push(normal.x, normal.y, normal.z);
  37944. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37945. }
  37946. }
  37947. for (row = 0; row < subdivisionsY; row++) {
  37948. for (col = 0; col < subdivisionsX; col++) {
  37949. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37950. indices.push(col + 1 + row * (subdivisionsX + 1));
  37951. indices.push(col + row * (subdivisionsX + 1));
  37952. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37953. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37954. indices.push(col + row * (subdivisionsX + 1));
  37955. }
  37956. }
  37957. // Result
  37958. var vertexData = new VertexData();
  37959. vertexData.indices = indices;
  37960. vertexData.positions = positions;
  37961. vertexData.normals = normals;
  37962. vertexData.uvs = uvs;
  37963. return vertexData;
  37964. };
  37965. /**
  37966. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37967. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37968. * * xmin the ground minimum X coordinate, optional, default -1
  37969. * * zmin the ground minimum Z coordinate, optional, default -1
  37970. * * xmax the ground maximum X coordinate, optional, default 1
  37971. * * zmax the ground maximum Z coordinate, optional, default 1
  37972. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37973. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37974. * @returns the VertexData of the TiledGround
  37975. */
  37976. VertexData.CreateTiledGround = function (options) {
  37977. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37978. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37979. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37980. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37981. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37982. var precision = options.precision || { w: 1, h: 1 };
  37983. var indices = new Array();
  37984. var positions = new Array();
  37985. var normals = new Array();
  37986. var uvs = new Array();
  37987. var row, col, tileRow, tileCol;
  37988. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37989. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37990. precision.w = (precision.w < 1) ? 1 : precision.w;
  37991. precision.h = (precision.h < 1) ? 1 : precision.h;
  37992. var tileSize = {
  37993. 'w': (xmax - xmin) / subdivisions.w,
  37994. 'h': (zmax - zmin) / subdivisions.h
  37995. };
  37996. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37997. // Indices
  37998. var base = positions.length / 3;
  37999. var rowLength = precision.w + 1;
  38000. for (row = 0; row < precision.h; row++) {
  38001. for (col = 0; col < precision.w; col++) {
  38002. var square = [
  38003. base + col + row * rowLength,
  38004. base + (col + 1) + row * rowLength,
  38005. base + (col + 1) + (row + 1) * rowLength,
  38006. base + col + (row + 1) * rowLength
  38007. ];
  38008. indices.push(square[1]);
  38009. indices.push(square[2]);
  38010. indices.push(square[3]);
  38011. indices.push(square[0]);
  38012. indices.push(square[1]);
  38013. indices.push(square[3]);
  38014. }
  38015. }
  38016. // Position, normals and uvs
  38017. var position = BABYLON.Vector3.Zero();
  38018. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38019. for (row = 0; row <= precision.h; row++) {
  38020. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38021. for (col = 0; col <= precision.w; col++) {
  38022. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38023. position.y = 0;
  38024. positions.push(position.x, position.y, position.z);
  38025. normals.push(normal.x, normal.y, normal.z);
  38026. uvs.push(col / precision.w, row / precision.h);
  38027. }
  38028. }
  38029. }
  38030. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38031. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38032. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38033. }
  38034. }
  38035. // Result
  38036. var vertexData = new VertexData();
  38037. vertexData.indices = indices;
  38038. vertexData.positions = positions;
  38039. vertexData.normals = normals;
  38040. vertexData.uvs = uvs;
  38041. return vertexData;
  38042. };
  38043. /**
  38044. * Creates the VertexData of the Ground designed from a heightmap
  38045. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38046. * * width the width (x direction) of the ground
  38047. * * height the height (z direction) of the ground
  38048. * * subdivisions the number of subdivisions per side
  38049. * * minHeight the minimum altitude on the ground, optional, default 0
  38050. * * maxHeight the maximum altitude on the ground, optional default 1
  38051. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38052. * * buffer the array holding the image color data
  38053. * * bufferWidth the width of image
  38054. * * bufferHeight the height of image
  38055. * @returns the VertexData of the Ground designed from a heightmap
  38056. */
  38057. VertexData.CreateGroundFromHeightMap = function (options) {
  38058. var indices = [];
  38059. var positions = [];
  38060. var normals = [];
  38061. var uvs = [];
  38062. var row, col;
  38063. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38064. // Vertices
  38065. for (row = 0; row <= options.subdivisions; row++) {
  38066. for (col = 0; col <= options.subdivisions; col++) {
  38067. 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));
  38068. // Compute height
  38069. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38070. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38071. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38072. var r = options.buffer[pos] / 255.0;
  38073. var g = options.buffer[pos + 1] / 255.0;
  38074. var b = options.buffer[pos + 2] / 255.0;
  38075. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38076. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38077. // Add vertex
  38078. positions.push(position.x, position.y, position.z);
  38079. normals.push(0, 0, 0);
  38080. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38081. }
  38082. }
  38083. // Indices
  38084. for (row = 0; row < options.subdivisions; row++) {
  38085. for (col = 0; col < options.subdivisions; col++) {
  38086. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38087. indices.push(col + 1 + row * (options.subdivisions + 1));
  38088. indices.push(col + row * (options.subdivisions + 1));
  38089. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38090. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38091. indices.push(col + row * (options.subdivisions + 1));
  38092. }
  38093. }
  38094. // Normals
  38095. VertexData.ComputeNormals(positions, indices, normals);
  38096. // Result
  38097. var vertexData = new VertexData();
  38098. vertexData.indices = indices;
  38099. vertexData.positions = positions;
  38100. vertexData.normals = normals;
  38101. vertexData.uvs = uvs;
  38102. return vertexData;
  38103. };
  38104. /**
  38105. * Creates the VertexData for a Plane
  38106. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38107. * * size sets the width and height of the plane to the value of size, optional default 1
  38108. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38109. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38110. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38111. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38112. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38113. * @returns the VertexData of the box
  38114. */
  38115. VertexData.CreatePlane = function (options) {
  38116. var indices = [];
  38117. var positions = [];
  38118. var normals = [];
  38119. var uvs = [];
  38120. var width = options.width || options.size || 1;
  38121. var height = options.height || options.size || 1;
  38122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38123. // Vertices
  38124. var halfWidth = width / 2.0;
  38125. var halfHeight = height / 2.0;
  38126. positions.push(-halfWidth, -halfHeight, 0);
  38127. normals.push(0, 0, -1.0);
  38128. uvs.push(0.0, 0.0);
  38129. positions.push(halfWidth, -halfHeight, 0);
  38130. normals.push(0, 0, -1.0);
  38131. uvs.push(1.0, 0.0);
  38132. positions.push(halfWidth, halfHeight, 0);
  38133. normals.push(0, 0, -1.0);
  38134. uvs.push(1.0, 1.0);
  38135. positions.push(-halfWidth, halfHeight, 0);
  38136. normals.push(0, 0, -1.0);
  38137. uvs.push(0.0, 1.0);
  38138. // Indices
  38139. indices.push(0);
  38140. indices.push(1);
  38141. indices.push(2);
  38142. indices.push(0);
  38143. indices.push(2);
  38144. indices.push(3);
  38145. // Sides
  38146. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38147. // Result
  38148. var vertexData = new VertexData();
  38149. vertexData.indices = indices;
  38150. vertexData.positions = positions;
  38151. vertexData.normals = normals;
  38152. vertexData.uvs = uvs;
  38153. return vertexData;
  38154. };
  38155. /**
  38156. * Creates the VertexData of the Disc or regular Polygon
  38157. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38158. * * radius the radius of the disc, optional default 0.5
  38159. * * tessellation the number of polygon sides, optional, default 64
  38160. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  38161. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38162. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38163. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38164. * @returns the VertexData of the box
  38165. */
  38166. VertexData.CreateDisc = function (options) {
  38167. var positions = new Array();
  38168. var indices = new Array();
  38169. var normals = new Array();
  38170. var uvs = new Array();
  38171. var radius = options.radius || 0.5;
  38172. var tessellation = options.tessellation || 64;
  38173. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38174. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38175. // positions and uvs
  38176. positions.push(0, 0, 0); // disc center first
  38177. uvs.push(0.5, 0.5);
  38178. var theta = Math.PI * 2 * arc;
  38179. var step = theta / tessellation;
  38180. for (var a = 0; a < theta; a += step) {
  38181. var x = Math.cos(a);
  38182. var y = Math.sin(a);
  38183. var u = (x + 1) / 2;
  38184. var v = (1 - y) / 2;
  38185. positions.push(radius * x, radius * y, 0);
  38186. uvs.push(u, v);
  38187. }
  38188. if (arc === 1) {
  38189. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38190. uvs.push(uvs[2], uvs[3]);
  38191. }
  38192. //indices
  38193. var vertexNb = positions.length / 3;
  38194. for (var i = 1; i < vertexNb - 1; i++) {
  38195. indices.push(i + 1, 0, i);
  38196. }
  38197. // result
  38198. VertexData.ComputeNormals(positions, indices, normals);
  38199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38200. var vertexData = new VertexData();
  38201. vertexData.indices = indices;
  38202. vertexData.positions = positions;
  38203. vertexData.normals = normals;
  38204. vertexData.uvs = uvs;
  38205. return vertexData;
  38206. };
  38207. /**
  38208. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38209. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38210. * @param polygon a mesh built from polygonTriangulation.build()
  38211. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38212. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38213. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38214. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38215. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38216. * @returns the VertexData of the Polygon
  38217. */
  38218. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38219. var faceUV = fUV || new Array(3);
  38220. var faceColors = fColors;
  38221. var colors = [];
  38222. // default face colors and UV if undefined
  38223. for (var f = 0; f < 3; f++) {
  38224. if (faceUV[f] === undefined) {
  38225. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38226. }
  38227. if (faceColors && faceColors[f] === undefined) {
  38228. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38229. }
  38230. }
  38231. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38232. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38233. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38234. var indices = polygon.getIndices();
  38235. // set face colours and textures
  38236. var idx = 0;
  38237. var face = 0;
  38238. for (var index = 0; index < normals.length; index += 3) {
  38239. //Edge Face no. 1
  38240. if (Math.abs(normals[index + 1]) < 0.001) {
  38241. face = 1;
  38242. }
  38243. //Top Face no. 0
  38244. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38245. face = 0;
  38246. }
  38247. //Bottom Face no. 2
  38248. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38249. face = 2;
  38250. }
  38251. idx = index / 3;
  38252. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38253. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38254. if (faceColors) {
  38255. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38256. }
  38257. }
  38258. // sides
  38259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38260. // Result
  38261. var vertexData = new VertexData();
  38262. vertexData.indices = indices;
  38263. vertexData.positions = positions;
  38264. vertexData.normals = normals;
  38265. vertexData.uvs = uvs;
  38266. if (faceColors) {
  38267. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38268. vertexData.colors = totalColors;
  38269. }
  38270. return vertexData;
  38271. };
  38272. /**
  38273. * Creates the VertexData of the IcoSphere
  38274. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38275. * * radius the radius of the IcoSphere, optional default 1
  38276. * * radiusX allows stretching in the x direction, optional, default radius
  38277. * * radiusY allows stretching in the y direction, optional, default radius
  38278. * * radiusZ allows stretching in the z direction, optional, default radius
  38279. * * flat when true creates a flat shaded mesh, optional, default true
  38280. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38281. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38282. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38283. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38284. * @returns the VertexData of the IcoSphere
  38285. */
  38286. VertexData.CreateIcoSphere = function (options) {
  38287. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38288. var radius = options.radius || 1;
  38289. var flat = (options.flat === undefined) ? true : options.flat;
  38290. var subdivisions = options.subdivisions || 4;
  38291. var radiusX = options.radiusX || radius;
  38292. var radiusY = options.radiusY || radius;
  38293. var radiusZ = options.radiusZ || radius;
  38294. var t = (1 + Math.sqrt(5)) / 2;
  38295. // 12 vertex x,y,z
  38296. var ico_vertices = [
  38297. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38298. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38299. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38300. ];
  38301. // index of 3 vertex makes a face of icopshere
  38302. var ico_indices = [
  38303. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38304. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38305. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38306. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38307. ];
  38308. // vertex for uv have aliased position, not for UV
  38309. var vertices_unalias_id = [
  38310. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38311. // vertex alias
  38312. 0,
  38313. 2,
  38314. 3,
  38315. 3,
  38316. 3,
  38317. 4,
  38318. 7,
  38319. 8,
  38320. 9,
  38321. 9,
  38322. 10,
  38323. 11 // 23: B + 12
  38324. ];
  38325. // uv as integer step (not pixels !)
  38326. var ico_vertexuv = [
  38327. 5, 1, 3, 1, 6, 4, 0, 0,
  38328. 5, 3, 4, 2, 2, 2, 4, 0,
  38329. 2, 0, 1, 1, 6, 0, 6, 2,
  38330. // vertex alias (for same vertex on different faces)
  38331. 0, 4,
  38332. 3, 3,
  38333. 4, 4,
  38334. 3, 1,
  38335. 4, 2,
  38336. 4, 4,
  38337. 0, 2,
  38338. 1, 1,
  38339. 2, 2,
  38340. 3, 3,
  38341. 1, 3,
  38342. 2, 4 // 23: B + 12
  38343. ];
  38344. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38345. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38346. // First island of uv mapping
  38347. // v = 4h 3+ 2
  38348. // v = 3h 9+ 4
  38349. // v = 2h 9+ 5 B
  38350. // v = 1h 9 1 0
  38351. // v = 0h 3 8 7 A
  38352. // u = 0 1 2 3 4 5 6 *a
  38353. // Second island of uv mapping
  38354. // v = 4h 0+ B+ 4+
  38355. // v = 3h A+ 2+
  38356. // v = 2h 7+ 6 3+
  38357. // v = 1h 8+ 3+
  38358. // v = 0h
  38359. // u = 0 1 2 3 4 5 6 *a
  38360. // Face layout on texture UV mapping
  38361. // ============
  38362. // \ 4 /\ 16 / ======
  38363. // \ / \ / /\ 11 /
  38364. // \/ 7 \/ / \ /
  38365. // ======= / 10 \/
  38366. // /\ 17 /\ =======
  38367. // / \ / \ \ 15 /\
  38368. // / 8 \/ 12 \ \ / \
  38369. // ============ \/ 6 \
  38370. // \ 18 /\ ============
  38371. // \ / \ \ 5 /\ 0 /
  38372. // \/ 13 \ \ / \ /
  38373. // ======= \/ 1 \/
  38374. // =============
  38375. // /\ 19 /\ 2 /\
  38376. // / \ / \ / \
  38377. // / 14 \/ 9 \/ 3 \
  38378. // ===================
  38379. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38380. var ustep = 138 / 1024;
  38381. var vstep = 239 / 1024;
  38382. var uoffset = 60 / 1024;
  38383. var voffset = 26 / 1024;
  38384. // Second island should have margin, not to touch the first island
  38385. // avoid any borderline artefact in pixel rounding
  38386. var island_u_offset = -40 / 1024;
  38387. var island_v_offset = +20 / 1024;
  38388. // face is either island 0 or 1 :
  38389. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38390. var island = [
  38391. 0, 0, 0, 0, 1,
  38392. 0, 0, 1, 1, 0,
  38393. 0, 0, 1, 1, 0,
  38394. 0, 1, 1, 1, 0 // 15 - 19
  38395. ];
  38396. var indices = new Array();
  38397. var positions = new Array();
  38398. var normals = new Array();
  38399. var uvs = new Array();
  38400. var current_indice = 0;
  38401. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38402. var face_vertex_pos = new Array(3);
  38403. var face_vertex_uv = new Array(3);
  38404. var v012;
  38405. for (v012 = 0; v012 < 3; v012++) {
  38406. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38407. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38408. }
  38409. // create all with normals
  38410. for (var face = 0; face < 20; face++) {
  38411. // 3 vertex per face
  38412. for (v012 = 0; v012 < 3; v012++) {
  38413. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38414. var v_id = ico_indices[3 * face + v012];
  38415. // vertex have 3D position (x,y,z)
  38416. 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]);
  38417. // Normalize to get normal, then scale to radius
  38418. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38419. // uv Coordinates from vertex ID
  38420. 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);
  38421. }
  38422. // Subdivide the face (interpolate pos, norm, uv)
  38423. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38424. // - norm is linear interpolation of vertex corner normal
  38425. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38426. // - uv is linear interpolation
  38427. //
  38428. // Topology is as below for sub-divide by 2
  38429. // vertex shown as v0,v1,v2
  38430. // interp index is i1 to progress in range [v0,v1[
  38431. // interp index is i2 to progress in range [v0,v2[
  38432. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38433. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38434. //
  38435. //
  38436. // i2 v2
  38437. // ^ ^
  38438. // / / \
  38439. // / / \
  38440. // / / \
  38441. // / / (0,1) \
  38442. // / #---------\
  38443. // / / \ (0,0)'/ \
  38444. // / / \ / \
  38445. // / / \ / \
  38446. // / / (0,0) \ / (1,0) \
  38447. // / #---------#---------\
  38448. // v0 v1
  38449. //
  38450. // --------------------> i1
  38451. //
  38452. // interp of (i1,i2):
  38453. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38454. // along i1 : lerp(x0,x1, i1/(S-i2))
  38455. //
  38456. // centroid of triangle is needed to get help normal computation
  38457. // (c1,c2) are used for centroid location
  38458. var interp_vertex = function (i1, i2, c1, c2) {
  38459. // vertex is interpolated from
  38460. // - face_vertex_pos[0..2]
  38461. // - face_vertex_uv[0..2]
  38462. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38463. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38464. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38465. pos_interp.normalize();
  38466. var vertex_normal;
  38467. if (flat) {
  38468. // in flat mode, recalculate normal as face centroid normal
  38469. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38470. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38471. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38472. }
  38473. else {
  38474. // in smooth mode, recalculate normal from each single vertex position
  38475. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38476. }
  38477. // Vertex normal need correction due to X,Y,Z radius scaling
  38478. vertex_normal.x /= radiusX;
  38479. vertex_normal.y /= radiusY;
  38480. vertex_normal.z /= radiusZ;
  38481. vertex_normal.normalize();
  38482. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38483. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38484. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38485. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38486. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38487. uvs.push(uv_interp.x, uv_interp.y);
  38488. // push each vertex has member of a face
  38489. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38490. indices.push(current_indice);
  38491. current_indice++;
  38492. };
  38493. for (var i2 = 0; i2 < subdivisions; i2++) {
  38494. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38495. // face : (i1,i2) for /\ :
  38496. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38497. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38498. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38499. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38500. if (i1 + i2 + 1 < subdivisions) {
  38501. // face : (i1,i2)' for \/ :
  38502. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38503. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38504. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38505. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38506. }
  38507. }
  38508. }
  38509. }
  38510. // Sides
  38511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38512. // Result
  38513. var vertexData = new VertexData();
  38514. vertexData.indices = indices;
  38515. vertexData.positions = positions;
  38516. vertexData.normals = normals;
  38517. vertexData.uvs = uvs;
  38518. return vertexData;
  38519. };
  38520. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38521. /**
  38522. * Creates the VertexData for a Polyhedron
  38523. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38524. * * type provided types are:
  38525. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38526. * * 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)
  38527. * * size the size of the IcoSphere, optional default 1
  38528. * * sizeX allows stretching in the x direction, optional, default size
  38529. * * sizeY allows stretching in the y direction, optional, default size
  38530. * * sizeZ allows stretching in the z direction, optional, default size
  38531. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38532. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38533. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38534. * * flat when true creates a flat shaded mesh, optional, default true
  38535. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38536. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38537. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38538. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38539. * @returns the VertexData of the Polyhedron
  38540. */
  38541. VertexData.CreatePolyhedron = function (options) {
  38542. // provided polyhedron types :
  38543. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38544. // 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)
  38545. var polyhedra = [];
  38546. 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]] };
  38547. 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]] };
  38548. polyhedra[2] = {
  38549. 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]],
  38550. 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]]
  38551. };
  38552. polyhedra[3] = {
  38553. 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]],
  38554. 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]]
  38555. };
  38556. polyhedra[4] = {
  38557. 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]],
  38558. 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]]
  38559. };
  38560. 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]] };
  38561. 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]] };
  38562. 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]] };
  38563. 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]] };
  38564. 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]] };
  38565. 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]] };
  38566. 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]] };
  38567. 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]] };
  38568. 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]] };
  38569. polyhedra[14] = {
  38570. 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]],
  38571. 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]]
  38572. };
  38573. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38574. var size = options.size;
  38575. var sizeX = options.sizeX || size || 1;
  38576. var sizeY = options.sizeY || size || 1;
  38577. var sizeZ = options.sizeZ || size || 1;
  38578. var data = options.custom || polyhedra[type];
  38579. var nbfaces = data.face.length;
  38580. var faceUV = options.faceUV || new Array(nbfaces);
  38581. var faceColors = options.faceColors;
  38582. var flat = (options.flat === undefined) ? true : options.flat;
  38583. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38584. var positions = new Array();
  38585. var indices = new Array();
  38586. var normals = new Array();
  38587. var uvs = new Array();
  38588. var colors = new Array();
  38589. var index = 0;
  38590. var faceIdx = 0; // face cursor in the array "indexes"
  38591. var indexes = new Array();
  38592. var i = 0;
  38593. var f = 0;
  38594. var u, v, ang, x, y, tmp;
  38595. // default face colors and UV if undefined
  38596. if (flat) {
  38597. for (f = 0; f < nbfaces; f++) {
  38598. if (faceColors && faceColors[f] === undefined) {
  38599. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38600. }
  38601. if (faceUV && faceUV[f] === undefined) {
  38602. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38603. }
  38604. }
  38605. }
  38606. if (!flat) {
  38607. for (i = 0; i < data.vertex.length; i++) {
  38608. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38609. uvs.push(0, 0);
  38610. }
  38611. for (f = 0; f < nbfaces; f++) {
  38612. for (i = 0; i < data.face[f].length - 2; i++) {
  38613. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38614. }
  38615. }
  38616. }
  38617. else {
  38618. for (f = 0; f < nbfaces; f++) {
  38619. var fl = data.face[f].length; // number of vertices of the current face
  38620. ang = 2 * Math.PI / fl;
  38621. x = 0.5 * Math.tan(ang / 2);
  38622. y = 0.5;
  38623. // positions, uvs, colors
  38624. for (i = 0; i < fl; i++) {
  38625. // positions
  38626. 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);
  38627. indexes.push(index);
  38628. index++;
  38629. // uvs
  38630. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38631. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38632. uvs.push(u, v);
  38633. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38634. y = x * Math.sin(ang) + y * Math.cos(ang);
  38635. x = tmp;
  38636. // colors
  38637. if (faceColors) {
  38638. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38639. }
  38640. }
  38641. // indices from indexes
  38642. for (i = 0; i < fl - 2; i++) {
  38643. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38644. }
  38645. faceIdx += fl;
  38646. }
  38647. }
  38648. VertexData.ComputeNormals(positions, indices, normals);
  38649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38650. var vertexData = new VertexData();
  38651. vertexData.positions = positions;
  38652. vertexData.indices = indices;
  38653. vertexData.normals = normals;
  38654. vertexData.uvs = uvs;
  38655. if (faceColors && flat) {
  38656. vertexData.colors = colors;
  38657. }
  38658. return vertexData;
  38659. };
  38660. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38661. /**
  38662. * Creates the VertexData for a TorusKnot
  38663. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38664. * * radius the radius of the torus knot, optional, default 2
  38665. * * tube the thickness of the tube, optional, default 0.5
  38666. * * radialSegments the number of sides on each tube segments, optional, default 32
  38667. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38668. * * p the number of windings around the z axis, optional, default 2
  38669. * * q the number of windings around the x axis, optional, default 3
  38670. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38671. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38672. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38673. * @returns the VertexData of the Torus Knot
  38674. */
  38675. VertexData.CreateTorusKnot = function (options) {
  38676. var indices = new Array();
  38677. var positions = new Array();
  38678. var normals = new Array();
  38679. var uvs = new Array();
  38680. var radius = options.radius || 2;
  38681. var tube = options.tube || 0.5;
  38682. var radialSegments = options.radialSegments || 32;
  38683. var tubularSegments = options.tubularSegments || 32;
  38684. var p = options.p || 2;
  38685. var q = options.q || 3;
  38686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38687. // Helper
  38688. var getPos = function (angle) {
  38689. var cu = Math.cos(angle);
  38690. var su = Math.sin(angle);
  38691. var quOverP = q / p * angle;
  38692. var cs = Math.cos(quOverP);
  38693. var tx = radius * (2 + cs) * 0.5 * cu;
  38694. var ty = radius * (2 + cs) * su * 0.5;
  38695. var tz = radius * Math.sin(quOverP) * 0.5;
  38696. return new BABYLON.Vector3(tx, ty, tz);
  38697. };
  38698. // Vertices
  38699. var i;
  38700. var j;
  38701. for (i = 0; i <= radialSegments; i++) {
  38702. var modI = i % radialSegments;
  38703. var u = modI / radialSegments * 2 * p * Math.PI;
  38704. var p1 = getPos(u);
  38705. var p2 = getPos(u + 0.01);
  38706. var tang = p2.subtract(p1);
  38707. var n = p2.add(p1);
  38708. var bitan = BABYLON.Vector3.Cross(tang, n);
  38709. n = BABYLON.Vector3.Cross(bitan, tang);
  38710. bitan.normalize();
  38711. n.normalize();
  38712. for (j = 0; j < tubularSegments; j++) {
  38713. var modJ = j % tubularSegments;
  38714. var v = modJ / tubularSegments * 2 * Math.PI;
  38715. var cx = -tube * Math.cos(v);
  38716. var cy = tube * Math.sin(v);
  38717. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38718. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38719. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38720. uvs.push(i / radialSegments);
  38721. uvs.push(j / tubularSegments);
  38722. }
  38723. }
  38724. for (i = 0; i < radialSegments; i++) {
  38725. for (j = 0; j < tubularSegments; j++) {
  38726. var jNext = (j + 1) % tubularSegments;
  38727. var a = i * tubularSegments + j;
  38728. var b = (i + 1) * tubularSegments + j;
  38729. var c = (i + 1) * tubularSegments + jNext;
  38730. var d = i * tubularSegments + jNext;
  38731. indices.push(d);
  38732. indices.push(b);
  38733. indices.push(a);
  38734. indices.push(d);
  38735. indices.push(c);
  38736. indices.push(b);
  38737. }
  38738. }
  38739. // Normals
  38740. VertexData.ComputeNormals(positions, indices, normals);
  38741. // Sides
  38742. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38743. // Result
  38744. var vertexData = new VertexData();
  38745. vertexData.indices = indices;
  38746. vertexData.positions = positions;
  38747. vertexData.normals = normals;
  38748. vertexData.uvs = uvs;
  38749. return vertexData;
  38750. };
  38751. // Tools
  38752. /**
  38753. * Compute normals for given positions and indices
  38754. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38755. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38756. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38757. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38758. * * facetNormals : optional array of facet normals (vector3)
  38759. * * facetPositions : optional array of facet positions (vector3)
  38760. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38761. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38762. * * bInfo : optional bounding info, required for facetPartitioning computation
  38763. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38764. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38765. * * useRightHandedSystem: optional boolean to for right handed system computation
  38766. * * depthSort : optional boolean to enable the facet depth sort computation
  38767. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38768. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38769. */
  38770. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38771. // temporary scalar variables
  38772. var index = 0; // facet index
  38773. var p1p2x = 0.0; // p1p2 vector x coordinate
  38774. var p1p2y = 0.0; // p1p2 vector y coordinate
  38775. var p1p2z = 0.0; // p1p2 vector z coordinate
  38776. var p3p2x = 0.0; // p3p2 vector x coordinate
  38777. var p3p2y = 0.0; // p3p2 vector y coordinate
  38778. var p3p2z = 0.0; // p3p2 vector z coordinate
  38779. var faceNormalx = 0.0; // facet normal x coordinate
  38780. var faceNormaly = 0.0; // facet normal y coordinate
  38781. var faceNormalz = 0.0; // facet normal z coordinate
  38782. var length = 0.0; // facet normal length before normalization
  38783. var v1x = 0; // vector1 x index in the positions array
  38784. var v1y = 0; // vector1 y index in the positions array
  38785. var v1z = 0; // vector1 z index in the positions array
  38786. var v2x = 0; // vector2 x index in the positions array
  38787. var v2y = 0; // vector2 y index in the positions array
  38788. var v2z = 0; // vector2 z index in the positions array
  38789. var v3x = 0; // vector3 x index in the positions array
  38790. var v3y = 0; // vector3 y index in the positions array
  38791. var v3z = 0; // vector3 z index in the positions array
  38792. var computeFacetNormals = false;
  38793. var computeFacetPositions = false;
  38794. var computeFacetPartitioning = false;
  38795. var computeDepthSort = false;
  38796. var faceNormalSign = 1;
  38797. var ratio = 0;
  38798. var distanceTo = null;
  38799. if (options) {
  38800. computeFacetNormals = (options.facetNormals) ? true : false;
  38801. computeFacetPositions = (options.facetPositions) ? true : false;
  38802. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38803. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38804. ratio = options.ratio || 0;
  38805. computeDepthSort = (options.depthSort) ? true : false;
  38806. distanceTo = (options.distanceTo);
  38807. if (computeDepthSort) {
  38808. if (distanceTo === undefined) {
  38809. distanceTo = BABYLON.Vector3.Zero();
  38810. }
  38811. var depthSortedFacets = options.depthSortedFacets;
  38812. }
  38813. }
  38814. // facetPartitioning reinit if needed
  38815. var xSubRatio = 0;
  38816. var ySubRatio = 0;
  38817. var zSubRatio = 0;
  38818. var subSq = 0;
  38819. if (computeFacetPartitioning && options && options.bbSize) {
  38820. var ox = 0; // X partitioning index for facet position
  38821. var oy = 0; // Y partinioning index for facet position
  38822. var oz = 0; // Z partinioning index for facet position
  38823. var b1x = 0; // X partitioning index for facet v1 vertex
  38824. var b1y = 0; // Y partitioning index for facet v1 vertex
  38825. var b1z = 0; // z partitioning index for facet v1 vertex
  38826. var b2x = 0; // X partitioning index for facet v2 vertex
  38827. var b2y = 0; // Y partitioning index for facet v2 vertex
  38828. var b2z = 0; // Z partitioning index for facet v2 vertex
  38829. var b3x = 0; // X partitioning index for facet v3 vertex
  38830. var b3y = 0; // Y partitioning index for facet v3 vertex
  38831. var b3z = 0; // Z partitioning index for facet v3 vertex
  38832. var block_idx_o = 0; // facet barycenter block index
  38833. var block_idx_v1 = 0; // v1 vertex block index
  38834. var block_idx_v2 = 0; // v2 vertex block index
  38835. var block_idx_v3 = 0; // v3 vertex block index
  38836. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38837. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38838. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38839. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38840. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38841. subSq = options.subDiv.max * options.subDiv.max;
  38842. options.facetPartitioning.length = 0;
  38843. }
  38844. // reset the normals
  38845. for (index = 0; index < positions.length; index++) {
  38846. normals[index] = 0.0;
  38847. }
  38848. // Loop : 1 indice triplet = 1 facet
  38849. var nbFaces = (indices.length / 3) | 0;
  38850. for (index = 0; index < nbFaces; index++) {
  38851. // get the indexes of the coordinates of each vertex of the facet
  38852. v1x = indices[index * 3] * 3;
  38853. v1y = v1x + 1;
  38854. v1z = v1x + 2;
  38855. v2x = indices[index * 3 + 1] * 3;
  38856. v2y = v2x + 1;
  38857. v2z = v2x + 2;
  38858. v3x = indices[index * 3 + 2] * 3;
  38859. v3y = v3x + 1;
  38860. v3z = v3x + 2;
  38861. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38862. p1p2y = positions[v1y] - positions[v2y];
  38863. p1p2z = positions[v1z] - positions[v2z];
  38864. p3p2x = positions[v3x] - positions[v2x];
  38865. p3p2y = positions[v3y] - positions[v2y];
  38866. p3p2z = positions[v3z] - positions[v2z];
  38867. // compute the face normal with the cross product
  38868. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38869. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38870. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38871. // normalize this normal and store it in the array facetData
  38872. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38873. length = (length === 0) ? 1.0 : length;
  38874. faceNormalx /= length;
  38875. faceNormaly /= length;
  38876. faceNormalz /= length;
  38877. if (computeFacetNormals && options) {
  38878. options.facetNormals[index].x = faceNormalx;
  38879. options.facetNormals[index].y = faceNormaly;
  38880. options.facetNormals[index].z = faceNormalz;
  38881. }
  38882. if (computeFacetPositions && options) {
  38883. // compute and the facet barycenter coordinates in the array facetPositions
  38884. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38885. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38886. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38887. }
  38888. if (computeFacetPartitioning && options) {
  38889. // store the facet indexes in arrays in the main facetPartitioning array :
  38890. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38891. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38892. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38893. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38894. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38895. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38896. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38897. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38898. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38899. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38900. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38901. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38902. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38903. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38904. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38905. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38906. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38907. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38908. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38909. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38910. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38911. // push each facet index in each block containing the vertex
  38912. options.facetPartitioning[block_idx_v1].push(index);
  38913. if (block_idx_v2 != block_idx_v1) {
  38914. options.facetPartitioning[block_idx_v2].push(index);
  38915. }
  38916. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38917. options.facetPartitioning[block_idx_v3].push(index);
  38918. }
  38919. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38920. options.facetPartitioning[block_idx_o].push(index);
  38921. }
  38922. }
  38923. if (computeDepthSort && options && options.facetPositions) {
  38924. var dsf = depthSortedFacets[index];
  38925. dsf.ind = index * 3;
  38926. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38927. }
  38928. // compute the normals anyway
  38929. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38930. normals[v1y] += faceNormaly;
  38931. normals[v1z] += faceNormalz;
  38932. normals[v2x] += faceNormalx;
  38933. normals[v2y] += faceNormaly;
  38934. normals[v2z] += faceNormalz;
  38935. normals[v3x] += faceNormalx;
  38936. normals[v3y] += faceNormaly;
  38937. normals[v3z] += faceNormalz;
  38938. }
  38939. // last normalization of each normal
  38940. for (index = 0; index < normals.length / 3; index++) {
  38941. faceNormalx = normals[index * 3];
  38942. faceNormaly = normals[index * 3 + 1];
  38943. faceNormalz = normals[index * 3 + 2];
  38944. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38945. length = (length === 0) ? 1.0 : length;
  38946. faceNormalx /= length;
  38947. faceNormaly /= length;
  38948. faceNormalz /= length;
  38949. normals[index * 3] = faceNormalx;
  38950. normals[index * 3 + 1] = faceNormaly;
  38951. normals[index * 3 + 2] = faceNormalz;
  38952. }
  38953. };
  38954. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38955. var li = indices.length;
  38956. var ln = normals.length;
  38957. var i;
  38958. var n;
  38959. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38960. switch (sideOrientation) {
  38961. case BABYLON.Mesh.FRONTSIDE:
  38962. // nothing changed
  38963. break;
  38964. case BABYLON.Mesh.BACKSIDE:
  38965. var tmp;
  38966. // indices
  38967. for (i = 0; i < li; i += 3) {
  38968. tmp = indices[i];
  38969. indices[i] = indices[i + 2];
  38970. indices[i + 2] = tmp;
  38971. }
  38972. // normals
  38973. for (n = 0; n < ln; n++) {
  38974. normals[n] = -normals[n];
  38975. }
  38976. break;
  38977. case BABYLON.Mesh.DOUBLESIDE:
  38978. // positions
  38979. var lp = positions.length;
  38980. var l = lp / 3;
  38981. for (var p = 0; p < lp; p++) {
  38982. positions[lp + p] = positions[p];
  38983. }
  38984. // indices
  38985. for (i = 0; i < li; i += 3) {
  38986. indices[i + li] = indices[i + 2] + l;
  38987. indices[i + 1 + li] = indices[i + 1] + l;
  38988. indices[i + 2 + li] = indices[i] + l;
  38989. }
  38990. // normals
  38991. for (n = 0; n < ln; n++) {
  38992. normals[ln + n] = -normals[n];
  38993. }
  38994. // uvs
  38995. var lu = uvs.length;
  38996. var u = 0;
  38997. for (u = 0; u < lu; u++) {
  38998. uvs[u + lu] = uvs[u];
  38999. }
  39000. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39001. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39002. u = 0;
  39003. for (i = 0; i < lu / 2; i++) {
  39004. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39005. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39006. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39007. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39008. u += 2;
  39009. }
  39010. break;
  39011. }
  39012. };
  39013. /**
  39014. * Applies VertexData created from the imported parameters to the geometry
  39015. * @param parsedVertexData the parsed data from an imported file
  39016. * @param geometry the geometry to apply the VertexData to
  39017. */
  39018. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39019. var vertexData = new VertexData();
  39020. // positions
  39021. var positions = parsedVertexData.positions;
  39022. if (positions) {
  39023. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39024. }
  39025. // normals
  39026. var normals = parsedVertexData.normals;
  39027. if (normals) {
  39028. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39029. }
  39030. // tangents
  39031. var tangents = parsedVertexData.tangents;
  39032. if (tangents) {
  39033. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39034. }
  39035. // uvs
  39036. var uvs = parsedVertexData.uvs;
  39037. if (uvs) {
  39038. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39039. }
  39040. // uv2s
  39041. var uv2s = parsedVertexData.uv2s;
  39042. if (uv2s) {
  39043. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39044. }
  39045. // uv3s
  39046. var uv3s = parsedVertexData.uv3s;
  39047. if (uv3s) {
  39048. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39049. }
  39050. // uv4s
  39051. var uv4s = parsedVertexData.uv4s;
  39052. if (uv4s) {
  39053. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39054. }
  39055. // uv5s
  39056. var uv5s = parsedVertexData.uv5s;
  39057. if (uv5s) {
  39058. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39059. }
  39060. // uv6s
  39061. var uv6s = parsedVertexData.uv6s;
  39062. if (uv6s) {
  39063. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39064. }
  39065. // colors
  39066. var colors = parsedVertexData.colors;
  39067. if (colors) {
  39068. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39069. }
  39070. // matricesIndices
  39071. var matricesIndices = parsedVertexData.matricesIndices;
  39072. if (matricesIndices) {
  39073. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39074. }
  39075. // matricesWeights
  39076. var matricesWeights = parsedVertexData.matricesWeights;
  39077. if (matricesWeights) {
  39078. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39079. }
  39080. // indices
  39081. var indices = parsedVertexData.indices;
  39082. if (indices) {
  39083. vertexData.indices = indices;
  39084. }
  39085. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39086. };
  39087. return VertexData;
  39088. }());
  39089. BABYLON.VertexData = VertexData;
  39090. })(BABYLON || (BABYLON = {}));
  39091. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39092. var BABYLON;
  39093. (function (BABYLON) {
  39094. /**
  39095. * Class used to store geometry data (vertex buffers + index buffer)
  39096. */
  39097. var Geometry = /** @class */ (function () {
  39098. /**
  39099. * Creates a new geometry
  39100. * @param id defines the unique ID
  39101. * @param scene defines the hosting scene
  39102. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39103. * @param updatable defines if geometry must be updatable (false by default)
  39104. * @param mesh defines the mesh that will be associated with the geometry
  39105. */
  39106. function Geometry(id, scene, vertexData, updatable, mesh) {
  39107. if (updatable === void 0) { updatable = false; }
  39108. if (mesh === void 0) { mesh = null; }
  39109. /**
  39110. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39111. */
  39112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39113. this._totalVertices = 0;
  39114. this._isDisposed = false;
  39115. this._indexBufferIsUpdatable = false;
  39116. this.id = id;
  39117. this._engine = scene.getEngine();
  39118. this._meshes = [];
  39119. this._scene = scene;
  39120. //Init vertex buffer cache
  39121. this._vertexBuffers = {};
  39122. this._indices = [];
  39123. this._updatable = updatable;
  39124. // vertexData
  39125. if (vertexData) {
  39126. this.setAllVerticesData(vertexData, updatable);
  39127. }
  39128. else {
  39129. this._totalVertices = 0;
  39130. this._indices = [];
  39131. }
  39132. if (this._engine.getCaps().vertexArrayObject) {
  39133. this._vertexArrayObjects = {};
  39134. }
  39135. // applyToMesh
  39136. if (mesh) {
  39137. if (mesh.getClassName() === "LinesMesh") {
  39138. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39139. this._updateExtend();
  39140. }
  39141. this.applyToMesh(mesh);
  39142. mesh.computeWorldMatrix(true);
  39143. }
  39144. }
  39145. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39146. /**
  39147. * 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
  39148. */
  39149. get: function () {
  39150. return this._boundingBias;
  39151. },
  39152. /**
  39153. * 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
  39154. */
  39155. set: function (value) {
  39156. if (this._boundingBias && this._boundingBias.equals(value)) {
  39157. return;
  39158. }
  39159. this._boundingBias = value.clone();
  39160. this._updateBoundingInfo(true, null);
  39161. },
  39162. enumerable: true,
  39163. configurable: true
  39164. });
  39165. /**
  39166. * Static function used to attach a new empty geometry to a mesh
  39167. * @param mesh defines the mesh to attach the geometry to
  39168. * @returns the new {BABYLON.Geometry}
  39169. */
  39170. Geometry.CreateGeometryForMesh = function (mesh) {
  39171. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39172. geometry.applyToMesh(mesh);
  39173. return geometry;
  39174. };
  39175. Object.defineProperty(Geometry.prototype, "extend", {
  39176. /**
  39177. * Gets the current extend of the geometry
  39178. */
  39179. get: function () {
  39180. return this._extend;
  39181. },
  39182. enumerable: true,
  39183. configurable: true
  39184. });
  39185. /**
  39186. * Gets the hosting scene
  39187. * @returns the hosting {BABYLON.Scene}
  39188. */
  39189. Geometry.prototype.getScene = function () {
  39190. return this._scene;
  39191. };
  39192. /**
  39193. * Gets the hosting engine
  39194. * @returns the hosting {BABYLON.Engine}
  39195. */
  39196. Geometry.prototype.getEngine = function () {
  39197. return this._engine;
  39198. };
  39199. /**
  39200. * Defines if the geometry is ready to use
  39201. * @returns true if the geometry is ready to be used
  39202. */
  39203. Geometry.prototype.isReady = function () {
  39204. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39205. };
  39206. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39207. /**
  39208. * Gets a value indicating that the geometry should not be serialized
  39209. */
  39210. get: function () {
  39211. for (var index = 0; index < this._meshes.length; index++) {
  39212. if (!this._meshes[index].doNotSerialize) {
  39213. return false;
  39214. }
  39215. }
  39216. return true;
  39217. },
  39218. enumerable: true,
  39219. configurable: true
  39220. });
  39221. /** @hidden */
  39222. Geometry.prototype._rebuild = function () {
  39223. if (this._vertexArrayObjects) {
  39224. this._vertexArrayObjects = {};
  39225. }
  39226. // Index buffer
  39227. if (this._meshes.length !== 0 && this._indices) {
  39228. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39229. }
  39230. // Vertex buffers
  39231. for (var key in this._vertexBuffers) {
  39232. var vertexBuffer = this._vertexBuffers[key];
  39233. vertexBuffer._rebuild();
  39234. }
  39235. };
  39236. /**
  39237. * Affects all geometry data in one call
  39238. * @param vertexData defines the geometry data
  39239. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39240. */
  39241. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39242. vertexData.applyToGeometry(this, updatable);
  39243. this.notifyUpdate();
  39244. };
  39245. /**
  39246. * Set specific vertex data
  39247. * @param kind defines the data kind (Position, normal, etc...)
  39248. * @param data defines the vertex data to use
  39249. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39250. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39251. */
  39252. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39253. if (updatable === void 0) { updatable = false; }
  39254. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39255. this.setVerticesBuffer(buffer);
  39256. };
  39257. /**
  39258. * Removes a specific vertex data
  39259. * @param kind defines the data kind (Position, normal, etc...)
  39260. */
  39261. Geometry.prototype.removeVerticesData = function (kind) {
  39262. if (this._vertexBuffers[kind]) {
  39263. this._vertexBuffers[kind].dispose();
  39264. delete this._vertexBuffers[kind];
  39265. }
  39266. };
  39267. /**
  39268. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39269. * @param buffer defines the vertex buffer to use
  39270. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39271. */
  39272. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39273. if (totalVertices === void 0) { totalVertices = null; }
  39274. var kind = buffer.getKind();
  39275. if (this._vertexBuffers[kind]) {
  39276. this._vertexBuffers[kind].dispose();
  39277. }
  39278. this._vertexBuffers[kind] = buffer;
  39279. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39280. var data = buffer.getData();
  39281. if (totalVertices != null) {
  39282. this._totalVertices = totalVertices;
  39283. }
  39284. else {
  39285. if (data != null) {
  39286. this._totalVertices = data.length / (buffer.byteStride / 4);
  39287. }
  39288. }
  39289. this._updateExtend(data);
  39290. this._resetPointsArrayCache();
  39291. var meshes = this._meshes;
  39292. var numOfMeshes = meshes.length;
  39293. for (var index = 0; index < numOfMeshes; index++) {
  39294. var mesh = meshes[index];
  39295. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39296. mesh._createGlobalSubMesh(false);
  39297. mesh.computeWorldMatrix(true);
  39298. }
  39299. }
  39300. this.notifyUpdate(kind);
  39301. if (this._vertexArrayObjects) {
  39302. this._disposeVertexArrayObjects();
  39303. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39304. }
  39305. };
  39306. /**
  39307. * Update a specific vertex buffer
  39308. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39309. * It will do nothing if the buffer is not updatable
  39310. * @param kind defines the data kind (Position, normal, etc...)
  39311. * @param data defines the data to use
  39312. * @param offset defines the offset in the target buffer where to store the data
  39313. * @param useBytes set to true if the offset is in bytes
  39314. */
  39315. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39316. if (useBytes === void 0) { useBytes = false; }
  39317. var vertexBuffer = this.getVertexBuffer(kind);
  39318. if (!vertexBuffer) {
  39319. return;
  39320. }
  39321. vertexBuffer.updateDirectly(data, offset, useBytes);
  39322. this.notifyUpdate(kind);
  39323. };
  39324. /**
  39325. * Update a specific vertex buffer
  39326. * This function will create a new buffer if the current one is not updatable
  39327. * @param kind defines the data kind (Position, normal, etc...)
  39328. * @param data defines the data to use
  39329. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39330. */
  39331. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39332. if (updateExtends === void 0) { updateExtends = false; }
  39333. var vertexBuffer = this.getVertexBuffer(kind);
  39334. if (!vertexBuffer) {
  39335. return;
  39336. }
  39337. vertexBuffer.update(data);
  39338. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39339. this._updateBoundingInfo(updateExtends, data);
  39340. }
  39341. this.notifyUpdate(kind);
  39342. };
  39343. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39344. if (updateExtends) {
  39345. this._updateExtend(data);
  39346. }
  39347. var meshes = this._meshes;
  39348. var numOfMeshes = meshes.length;
  39349. this._resetPointsArrayCache();
  39350. for (var index = 0; index < numOfMeshes; index++) {
  39351. var mesh = meshes[index];
  39352. if (updateExtends) {
  39353. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39354. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39355. var subMesh = mesh.subMeshes[subIndex];
  39356. subMesh.refreshBoundingInfo();
  39357. }
  39358. }
  39359. }
  39360. };
  39361. /** @hidden */
  39362. Geometry.prototype._bind = function (effect, indexToBind) {
  39363. if (!effect) {
  39364. return;
  39365. }
  39366. if (indexToBind === undefined) {
  39367. indexToBind = this._indexBuffer;
  39368. }
  39369. var vbs = this.getVertexBuffers();
  39370. if (!vbs) {
  39371. return;
  39372. }
  39373. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39374. this._engine.bindBuffers(vbs, indexToBind, effect);
  39375. return;
  39376. }
  39377. // Using VAO
  39378. if (!this._vertexArrayObjects[effect.key]) {
  39379. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39380. }
  39381. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39382. };
  39383. /**
  39384. * Gets total number of vertices
  39385. * @returns the total number of vertices
  39386. */
  39387. Geometry.prototype.getTotalVertices = function () {
  39388. if (!this.isReady()) {
  39389. return 0;
  39390. }
  39391. return this._totalVertices;
  39392. };
  39393. /**
  39394. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39395. * @param kind defines the data kind (Position, normal, etc...)
  39396. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39397. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39398. * @returns a float array containing vertex data
  39399. */
  39400. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39401. var vertexBuffer = this.getVertexBuffer(kind);
  39402. if (!vertexBuffer) {
  39403. return null;
  39404. }
  39405. var data = vertexBuffer.getData();
  39406. if (!data) {
  39407. return null;
  39408. }
  39409. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39410. var count = this._totalVertices * vertexBuffer.getSize();
  39411. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39412. var copy_1 = new Array(count);
  39413. vertexBuffer.forEach(count, function (value, index) {
  39414. copy_1[index] = value;
  39415. });
  39416. return copy_1;
  39417. }
  39418. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39419. if (data instanceof Array) {
  39420. var offset = vertexBuffer.byteOffset / 4;
  39421. return BABYLON.Tools.Slice(data, offset, offset + count);
  39422. }
  39423. else if (data instanceof ArrayBuffer) {
  39424. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39425. }
  39426. else {
  39427. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39428. }
  39429. }
  39430. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39431. return BABYLON.Tools.Slice(data);
  39432. }
  39433. return data;
  39434. };
  39435. /**
  39436. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39437. * @param kind defines the data kind (Position, normal, etc...)
  39438. * @returns true if the vertex buffer with the specified kind is updatable
  39439. */
  39440. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39441. var vb = this._vertexBuffers[kind];
  39442. if (!vb) {
  39443. return false;
  39444. }
  39445. return vb.isUpdatable();
  39446. };
  39447. /**
  39448. * Gets a specific vertex buffer
  39449. * @param kind defines the data kind (Position, normal, etc...)
  39450. * @returns a {BABYLON.VertexBuffer}
  39451. */
  39452. Geometry.prototype.getVertexBuffer = function (kind) {
  39453. if (!this.isReady()) {
  39454. return null;
  39455. }
  39456. return this._vertexBuffers[kind];
  39457. };
  39458. /**
  39459. * Returns all vertex buffers
  39460. * @return an object holding all vertex buffers indexed by kind
  39461. */
  39462. Geometry.prototype.getVertexBuffers = function () {
  39463. if (!this.isReady()) {
  39464. return null;
  39465. }
  39466. return this._vertexBuffers;
  39467. };
  39468. /**
  39469. * Gets a boolean indicating if specific vertex buffer is present
  39470. * @param kind defines the data kind (Position, normal, etc...)
  39471. * @returns true if data is present
  39472. */
  39473. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39474. if (!this._vertexBuffers) {
  39475. if (this._delayInfo) {
  39476. return this._delayInfo.indexOf(kind) !== -1;
  39477. }
  39478. return false;
  39479. }
  39480. return this._vertexBuffers[kind] !== undefined;
  39481. };
  39482. /**
  39483. * Gets a list of all attached data kinds (Position, normal, etc...)
  39484. * @returns a list of string containing all kinds
  39485. */
  39486. Geometry.prototype.getVerticesDataKinds = function () {
  39487. var result = [];
  39488. var kind;
  39489. if (!this._vertexBuffers && this._delayInfo) {
  39490. for (kind in this._delayInfo) {
  39491. result.push(kind);
  39492. }
  39493. }
  39494. else {
  39495. for (kind in this._vertexBuffers) {
  39496. result.push(kind);
  39497. }
  39498. }
  39499. return result;
  39500. };
  39501. /**
  39502. * Update index buffer
  39503. * @param indices defines the indices to store in the index buffer
  39504. * @param offset defines the offset in the target buffer where to store the data
  39505. */
  39506. Geometry.prototype.updateIndices = function (indices, offset) {
  39507. if (!this._indexBuffer) {
  39508. return;
  39509. }
  39510. if (!this._indexBufferIsUpdatable) {
  39511. this.setIndices(indices, null, true);
  39512. }
  39513. else {
  39514. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39515. }
  39516. };
  39517. /**
  39518. * Creates a new index buffer
  39519. * @param indices defines the indices to store in the index buffer
  39520. * @param totalVertices defines the total number of vertices (could be null)
  39521. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39522. */
  39523. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39524. if (totalVertices === void 0) { totalVertices = null; }
  39525. if (updatable === void 0) { updatable = false; }
  39526. if (this._indexBuffer) {
  39527. this._engine._releaseBuffer(this._indexBuffer);
  39528. }
  39529. this._disposeVertexArrayObjects();
  39530. this._indices = indices;
  39531. this._indexBufferIsUpdatable = updatable;
  39532. if (this._meshes.length !== 0 && this._indices) {
  39533. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39534. }
  39535. if (totalVertices != undefined) { // including null and undefined
  39536. this._totalVertices = totalVertices;
  39537. }
  39538. var meshes = this._meshes;
  39539. var numOfMeshes = meshes.length;
  39540. for (var index = 0; index < numOfMeshes; index++) {
  39541. meshes[index]._createGlobalSubMesh(true);
  39542. }
  39543. this.notifyUpdate();
  39544. };
  39545. /**
  39546. * Return the total number of indices
  39547. * @returns the total number of indices
  39548. */
  39549. Geometry.prototype.getTotalIndices = function () {
  39550. if (!this.isReady()) {
  39551. return 0;
  39552. }
  39553. return this._indices.length;
  39554. };
  39555. /**
  39556. * Gets the index buffer array
  39557. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39558. * @returns the index buffer array
  39559. */
  39560. Geometry.prototype.getIndices = function (copyWhenShared) {
  39561. if (!this.isReady()) {
  39562. return null;
  39563. }
  39564. var orig = this._indices;
  39565. if (!copyWhenShared || this._meshes.length === 1) {
  39566. return orig;
  39567. }
  39568. else {
  39569. var len = orig.length;
  39570. var copy = [];
  39571. for (var i = 0; i < len; i++) {
  39572. copy.push(orig[i]);
  39573. }
  39574. return copy;
  39575. }
  39576. };
  39577. /**
  39578. * Gets the index buffer
  39579. * @return the index buffer
  39580. */
  39581. Geometry.prototype.getIndexBuffer = function () {
  39582. if (!this.isReady()) {
  39583. return null;
  39584. }
  39585. return this._indexBuffer;
  39586. };
  39587. /** @hidden */
  39588. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39589. if (effect === void 0) { effect = null; }
  39590. if (!effect || !this._vertexArrayObjects) {
  39591. return;
  39592. }
  39593. if (this._vertexArrayObjects[effect.key]) {
  39594. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39595. delete this._vertexArrayObjects[effect.key];
  39596. }
  39597. };
  39598. /**
  39599. * Release the associated resources for a specific mesh
  39600. * @param mesh defines the source mesh
  39601. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39602. */
  39603. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39604. var meshes = this._meshes;
  39605. var index = meshes.indexOf(mesh);
  39606. if (index === -1) {
  39607. return;
  39608. }
  39609. meshes.splice(index, 1);
  39610. mesh._geometry = null;
  39611. if (meshes.length === 0 && shouldDispose) {
  39612. this.dispose();
  39613. }
  39614. };
  39615. /**
  39616. * Apply current geometry to a given mesh
  39617. * @param mesh defines the mesh to apply geometry to
  39618. */
  39619. Geometry.prototype.applyToMesh = function (mesh) {
  39620. if (mesh._geometry === this) {
  39621. return;
  39622. }
  39623. var previousGeometry = mesh._geometry;
  39624. if (previousGeometry) {
  39625. previousGeometry.releaseForMesh(mesh);
  39626. }
  39627. var meshes = this._meshes;
  39628. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39629. mesh._geometry = this;
  39630. this._scene.pushGeometry(this);
  39631. meshes.push(mesh);
  39632. if (this.isReady()) {
  39633. this._applyToMesh(mesh);
  39634. }
  39635. else {
  39636. mesh._boundingInfo = this._boundingInfo;
  39637. }
  39638. };
  39639. Geometry.prototype._updateExtend = function (data) {
  39640. if (data === void 0) { data = null; }
  39641. if (!data) {
  39642. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39643. }
  39644. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39645. };
  39646. Geometry.prototype._applyToMesh = function (mesh) {
  39647. var numOfMeshes = this._meshes.length;
  39648. // vertexBuffers
  39649. for (var kind in this._vertexBuffers) {
  39650. if (numOfMeshes === 1) {
  39651. this._vertexBuffers[kind].create();
  39652. }
  39653. var buffer = this._vertexBuffers[kind].getBuffer();
  39654. if (buffer)
  39655. buffer.references = numOfMeshes;
  39656. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39657. if (!this._extend) {
  39658. this._updateExtend();
  39659. }
  39660. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39661. mesh._createGlobalSubMesh(false);
  39662. //bounding info was just created again, world matrix should be applied again.
  39663. mesh._updateBoundingInfo();
  39664. }
  39665. }
  39666. // indexBuffer
  39667. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39668. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39669. }
  39670. if (this._indexBuffer) {
  39671. this._indexBuffer.references = numOfMeshes;
  39672. }
  39673. };
  39674. Geometry.prototype.notifyUpdate = function (kind) {
  39675. if (this.onGeometryUpdated) {
  39676. this.onGeometryUpdated(this, kind);
  39677. }
  39678. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39679. var mesh = _a[_i];
  39680. mesh._markSubMeshesAsAttributesDirty();
  39681. }
  39682. };
  39683. /**
  39684. * Load the geometry if it was flagged as delay loaded
  39685. * @param scene defines the hosting scene
  39686. * @param onLoaded defines a callback called when the geometry is loaded
  39687. */
  39688. Geometry.prototype.load = function (scene, onLoaded) {
  39689. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39690. return;
  39691. }
  39692. if (this.isReady()) {
  39693. if (onLoaded) {
  39694. onLoaded();
  39695. }
  39696. return;
  39697. }
  39698. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39699. this._queueLoad(scene, onLoaded);
  39700. };
  39701. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39702. var _this = this;
  39703. if (!this.delayLoadingFile) {
  39704. return;
  39705. }
  39706. scene._addPendingData(this);
  39707. scene._loadFile(this.delayLoadingFile, function (data) {
  39708. if (!_this._delayLoadingFunction) {
  39709. return;
  39710. }
  39711. _this._delayLoadingFunction(JSON.parse(data), _this);
  39712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39713. _this._delayInfo = [];
  39714. scene._removePendingData(_this);
  39715. var meshes = _this._meshes;
  39716. var numOfMeshes = meshes.length;
  39717. for (var index = 0; index < numOfMeshes; index++) {
  39718. _this._applyToMesh(meshes[index]);
  39719. }
  39720. if (onLoaded) {
  39721. onLoaded();
  39722. }
  39723. }, undefined, true);
  39724. };
  39725. /**
  39726. * Invert the geometry to move from a right handed system to a left handed one.
  39727. */
  39728. Geometry.prototype.toLeftHanded = function () {
  39729. // Flip faces
  39730. var tIndices = this.getIndices(false);
  39731. if (tIndices != null && tIndices.length > 0) {
  39732. for (var i = 0; i < tIndices.length; i += 3) {
  39733. var tTemp = tIndices[i + 0];
  39734. tIndices[i + 0] = tIndices[i + 2];
  39735. tIndices[i + 2] = tTemp;
  39736. }
  39737. this.setIndices(tIndices);
  39738. }
  39739. // Negate position.z
  39740. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39741. if (tPositions != null && tPositions.length > 0) {
  39742. for (var i = 0; i < tPositions.length; i += 3) {
  39743. tPositions[i + 2] = -tPositions[i + 2];
  39744. }
  39745. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39746. }
  39747. // Negate normal.z
  39748. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39749. if (tNormals != null && tNormals.length > 0) {
  39750. for (var i = 0; i < tNormals.length; i += 3) {
  39751. tNormals[i + 2] = -tNormals[i + 2];
  39752. }
  39753. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39754. }
  39755. };
  39756. // Cache
  39757. /** @hidden */
  39758. Geometry.prototype._resetPointsArrayCache = function () {
  39759. this._positions = null;
  39760. };
  39761. /** @hidden */
  39762. Geometry.prototype._generatePointsArray = function () {
  39763. if (this._positions)
  39764. return true;
  39765. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39766. if (!data || data.length === 0) {
  39767. return false;
  39768. }
  39769. this._positions = [];
  39770. for (var index = 0; index < data.length; index += 3) {
  39771. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39772. }
  39773. return true;
  39774. };
  39775. /**
  39776. * Gets a value indicating if the geometry is disposed
  39777. * @returns true if the geometry was disposed
  39778. */
  39779. Geometry.prototype.isDisposed = function () {
  39780. return this._isDisposed;
  39781. };
  39782. Geometry.prototype._disposeVertexArrayObjects = function () {
  39783. if (this._vertexArrayObjects) {
  39784. for (var kind in this._vertexArrayObjects) {
  39785. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39786. }
  39787. this._vertexArrayObjects = {};
  39788. }
  39789. };
  39790. /**
  39791. * Free all associated resources
  39792. */
  39793. Geometry.prototype.dispose = function () {
  39794. var meshes = this._meshes;
  39795. var numOfMeshes = meshes.length;
  39796. var index;
  39797. for (index = 0; index < numOfMeshes; index++) {
  39798. this.releaseForMesh(meshes[index]);
  39799. }
  39800. this._meshes = [];
  39801. this._disposeVertexArrayObjects();
  39802. for (var kind in this._vertexBuffers) {
  39803. this._vertexBuffers[kind].dispose();
  39804. }
  39805. this._vertexBuffers = {};
  39806. this._totalVertices = 0;
  39807. if (this._indexBuffer) {
  39808. this._engine._releaseBuffer(this._indexBuffer);
  39809. }
  39810. this._indexBuffer = null;
  39811. this._indices = [];
  39812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39813. this.delayLoadingFile = null;
  39814. this._delayLoadingFunction = null;
  39815. this._delayInfo = [];
  39816. this._boundingInfo = null;
  39817. this._scene.removeGeometry(this);
  39818. this._isDisposed = true;
  39819. };
  39820. /**
  39821. * Clone the current geometry into a new geometry
  39822. * @param id defines the unique ID of the new geometry
  39823. * @returns a new geometry object
  39824. */
  39825. Geometry.prototype.copy = function (id) {
  39826. var vertexData = new BABYLON.VertexData();
  39827. vertexData.indices = [];
  39828. var indices = this.getIndices();
  39829. if (indices) {
  39830. for (var index = 0; index < indices.length; index++) {
  39831. vertexData.indices.push(indices[index]);
  39832. }
  39833. }
  39834. var updatable = false;
  39835. var stopChecking = false;
  39836. var kind;
  39837. for (kind in this._vertexBuffers) {
  39838. // using slice() to make a copy of the array and not just reference it
  39839. var data = this.getVerticesData(kind);
  39840. if (data instanceof Float32Array) {
  39841. vertexData.set(new Float32Array(data), kind);
  39842. }
  39843. else {
  39844. vertexData.set(data.slice(0), kind);
  39845. }
  39846. if (!stopChecking) {
  39847. var vb = this.getVertexBuffer(kind);
  39848. if (vb) {
  39849. updatable = vb.isUpdatable();
  39850. stopChecking = !updatable;
  39851. }
  39852. }
  39853. }
  39854. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39855. geometry.delayLoadState = this.delayLoadState;
  39856. geometry.delayLoadingFile = this.delayLoadingFile;
  39857. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39858. for (kind in this._delayInfo) {
  39859. geometry._delayInfo = geometry._delayInfo || [];
  39860. geometry._delayInfo.push(kind);
  39861. }
  39862. // Bounding info
  39863. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39864. return geometry;
  39865. };
  39866. /**
  39867. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39868. * @return a JSON representation of the current geometry data (without the vertices data)
  39869. */
  39870. Geometry.prototype.serialize = function () {
  39871. var serializationObject = {};
  39872. serializationObject.id = this.id;
  39873. serializationObject.updatable = this._updatable;
  39874. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39875. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39876. }
  39877. return serializationObject;
  39878. };
  39879. Geometry.prototype.toNumberArray = function (origin) {
  39880. if (Array.isArray(origin)) {
  39881. return origin;
  39882. }
  39883. else {
  39884. return Array.prototype.slice.call(origin);
  39885. }
  39886. };
  39887. /**
  39888. * Serialize all vertices data into a JSON oject
  39889. * @returns a JSON representation of the current geometry data
  39890. */
  39891. Geometry.prototype.serializeVerticeData = function () {
  39892. var serializationObject = this.serialize();
  39893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39894. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39895. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39896. serializationObject.positions._updatable = true;
  39897. }
  39898. }
  39899. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39900. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39901. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39902. serializationObject.normals._updatable = true;
  39903. }
  39904. }
  39905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39906. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39907. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39908. serializationObject.tangets._updatable = true;
  39909. }
  39910. }
  39911. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39912. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39913. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39914. serializationObject.uvs._updatable = true;
  39915. }
  39916. }
  39917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39918. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39919. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39920. serializationObject.uv2s._updatable = true;
  39921. }
  39922. }
  39923. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39924. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39925. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39926. serializationObject.uv3s._updatable = true;
  39927. }
  39928. }
  39929. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39930. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39931. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39932. serializationObject.uv4s._updatable = true;
  39933. }
  39934. }
  39935. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39936. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39937. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39938. serializationObject.uv5s._updatable = true;
  39939. }
  39940. }
  39941. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39942. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39943. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39944. serializationObject.uv6s._updatable = true;
  39945. }
  39946. }
  39947. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39948. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39949. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39950. serializationObject.colors._updatable = true;
  39951. }
  39952. }
  39953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39954. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39955. serializationObject.matricesIndices._isExpanded = true;
  39956. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39957. serializationObject.matricesIndices._updatable = true;
  39958. }
  39959. }
  39960. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39961. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39962. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39963. serializationObject.matricesWeights._updatable = true;
  39964. }
  39965. }
  39966. serializationObject.indices = this.toNumberArray(this.getIndices());
  39967. return serializationObject;
  39968. };
  39969. // Statics
  39970. /**
  39971. * Extracts a clone of a mesh geometry
  39972. * @param mesh defines the source mesh
  39973. * @param id defines the unique ID of the new geometry object
  39974. * @returns the new geometry object
  39975. */
  39976. Geometry.ExtractFromMesh = function (mesh, id) {
  39977. var geometry = mesh._geometry;
  39978. if (!geometry) {
  39979. return null;
  39980. }
  39981. return geometry.copy(id);
  39982. };
  39983. /**
  39984. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39985. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39986. * Be aware Math.random() could cause collisions, but:
  39987. * "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"
  39988. * @returns a string containing a new GUID
  39989. */
  39990. Geometry.RandomId = function () {
  39991. return BABYLON.Tools.RandomId();
  39992. };
  39993. /** @hidden */
  39994. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39995. var scene = mesh.getScene();
  39996. // Geometry
  39997. var geometryId = parsedGeometry.geometryId;
  39998. if (geometryId) {
  39999. var geometry = scene.getGeometryByID(geometryId);
  40000. if (geometry) {
  40001. geometry.applyToMesh(mesh);
  40002. }
  40003. }
  40004. else if (parsedGeometry instanceof ArrayBuffer) {
  40005. var binaryInfo = mesh._binaryInfo;
  40006. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40007. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40008. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40009. }
  40010. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40011. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40012. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40013. }
  40014. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40015. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40016. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40017. }
  40018. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40019. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40021. }
  40022. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40023. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40024. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40025. }
  40026. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40027. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40029. }
  40030. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40031. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40033. }
  40034. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40035. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40036. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40037. }
  40038. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40039. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40040. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40041. }
  40042. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40043. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40044. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40045. }
  40046. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40047. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40048. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40049. }
  40050. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40051. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40052. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40053. }
  40054. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40055. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40056. mesh.setIndices(indicesData, null);
  40057. }
  40058. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40059. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40060. mesh.subMeshes = [];
  40061. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40062. var materialIndex = subMeshesData[(i * 5) + 0];
  40063. var verticesStart = subMeshesData[(i * 5) + 1];
  40064. var verticesCount = subMeshesData[(i * 5) + 2];
  40065. var indexStart = subMeshesData[(i * 5) + 3];
  40066. var indexCount = subMeshesData[(i * 5) + 4];
  40067. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40068. }
  40069. }
  40070. }
  40071. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40072. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40073. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40074. if (parsedGeometry.tangents) {
  40075. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40076. }
  40077. if (parsedGeometry.uvs) {
  40078. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40079. }
  40080. if (parsedGeometry.uvs2) {
  40081. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40082. }
  40083. if (parsedGeometry.uvs3) {
  40084. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40085. }
  40086. if (parsedGeometry.uvs4) {
  40087. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40088. }
  40089. if (parsedGeometry.uvs5) {
  40090. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40091. }
  40092. if (parsedGeometry.uvs6) {
  40093. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40094. }
  40095. if (parsedGeometry.colors) {
  40096. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40097. }
  40098. if (parsedGeometry.matricesIndices) {
  40099. if (!parsedGeometry.matricesIndices._isExpanded) {
  40100. var floatIndices = [];
  40101. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40102. var matricesIndex = parsedGeometry.matricesIndices[i];
  40103. floatIndices.push(matricesIndex & 0x000000FF);
  40104. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40105. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40106. floatIndices.push(matricesIndex >> 24);
  40107. }
  40108. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40109. }
  40110. else {
  40111. delete parsedGeometry.matricesIndices._isExpanded;
  40112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40113. }
  40114. }
  40115. if (parsedGeometry.matricesIndicesExtra) {
  40116. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40117. var floatIndices = [];
  40118. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40119. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40120. floatIndices.push(matricesIndex & 0x000000FF);
  40121. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40122. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40123. floatIndices.push(matricesIndex >> 24);
  40124. }
  40125. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40126. }
  40127. else {
  40128. delete parsedGeometry.matricesIndices._isExpanded;
  40129. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40130. }
  40131. }
  40132. if (parsedGeometry.matricesWeights) {
  40133. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40134. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40135. }
  40136. if (parsedGeometry.matricesWeightsExtra) {
  40137. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40138. }
  40139. mesh.setIndices(parsedGeometry.indices, null);
  40140. }
  40141. // SubMeshes
  40142. if (parsedGeometry.subMeshes) {
  40143. mesh.subMeshes = [];
  40144. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40145. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40146. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40147. }
  40148. }
  40149. // Flat shading
  40150. if (mesh._shouldGenerateFlatShading) {
  40151. mesh.convertToFlatShadedMesh();
  40152. delete mesh._shouldGenerateFlatShading;
  40153. }
  40154. // Update
  40155. mesh.computeWorldMatrix(true);
  40156. // Octree
  40157. var sceneOctree = scene.selectionOctree;
  40158. if (sceneOctree !== undefined && sceneOctree !== null) {
  40159. sceneOctree.addMesh(mesh);
  40160. }
  40161. };
  40162. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40163. var epsilon = 1e-3;
  40164. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40165. return;
  40166. }
  40167. var noInfluenceBoneIndex = 0.0;
  40168. if (parsedGeometry.skeletonId > -1) {
  40169. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40170. if (!skeleton) {
  40171. return;
  40172. }
  40173. noInfluenceBoneIndex = skeleton.bones.length;
  40174. }
  40175. else {
  40176. return;
  40177. }
  40178. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40179. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40180. var matricesWeights = parsedGeometry.matricesWeights;
  40181. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40182. var influencers = parsedGeometry.numBoneInfluencer;
  40183. var size = matricesWeights.length;
  40184. for (var i = 0; i < size; i += 4) {
  40185. var weight = 0.0;
  40186. var firstZeroWeight = -1;
  40187. for (var j = 0; j < 4; j++) {
  40188. var w = matricesWeights[i + j];
  40189. weight += w;
  40190. if (w < epsilon && firstZeroWeight < 0) {
  40191. firstZeroWeight = j;
  40192. }
  40193. }
  40194. if (matricesWeightsExtra) {
  40195. for (var j = 0; j < 4; j++) {
  40196. var w = matricesWeightsExtra[i + j];
  40197. weight += w;
  40198. if (w < epsilon && firstZeroWeight < 0) {
  40199. firstZeroWeight = j + 4;
  40200. }
  40201. }
  40202. }
  40203. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40204. firstZeroWeight = influencers - 1;
  40205. }
  40206. if (weight > epsilon) {
  40207. var mweight = 1.0 / weight;
  40208. for (var j = 0; j < 4; j++) {
  40209. matricesWeights[i + j] *= mweight;
  40210. }
  40211. if (matricesWeightsExtra) {
  40212. for (var j = 0; j < 4; j++) {
  40213. matricesWeightsExtra[i + j] *= mweight;
  40214. }
  40215. }
  40216. }
  40217. else {
  40218. if (firstZeroWeight >= 4) {
  40219. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40220. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40221. }
  40222. else {
  40223. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40224. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40225. }
  40226. }
  40227. }
  40228. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40229. if (parsedGeometry.matricesWeightsExtra) {
  40230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40231. }
  40232. };
  40233. /**
  40234. * Create a new geometry from persisted data (Using .babylon file format)
  40235. * @param parsedVertexData defines the persisted data
  40236. * @param scene defines the hosting scene
  40237. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40238. * @returns the new geometry object
  40239. */
  40240. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40241. if (scene.getGeometryByID(parsedVertexData.id)) {
  40242. return null; // null since geometry could be something else than a box...
  40243. }
  40244. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40245. if (BABYLON.Tags) {
  40246. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40247. }
  40248. if (parsedVertexData.delayLoadingFile) {
  40249. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40250. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40251. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40252. geometry._delayInfo = [];
  40253. if (parsedVertexData.hasUVs) {
  40254. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40255. }
  40256. if (parsedVertexData.hasUVs2) {
  40257. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40258. }
  40259. if (parsedVertexData.hasUVs3) {
  40260. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40261. }
  40262. if (parsedVertexData.hasUVs4) {
  40263. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40264. }
  40265. if (parsedVertexData.hasUVs5) {
  40266. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40267. }
  40268. if (parsedVertexData.hasUVs6) {
  40269. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40270. }
  40271. if (parsedVertexData.hasColors) {
  40272. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40273. }
  40274. if (parsedVertexData.hasMatricesIndices) {
  40275. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40276. }
  40277. if (parsedVertexData.hasMatricesWeights) {
  40278. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40279. }
  40280. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40281. }
  40282. else {
  40283. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40284. }
  40285. scene.pushGeometry(geometry, true);
  40286. return geometry;
  40287. };
  40288. return Geometry;
  40289. }());
  40290. BABYLON.Geometry = Geometry;
  40291. // Primitives
  40292. /// Abstract class
  40293. /**
  40294. * Abstract class used to provide common services for all typed geometries
  40295. * @hidden
  40296. */
  40297. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40298. __extends(_PrimitiveGeometry, _super);
  40299. /**
  40300. * Creates a new typed geometry
  40301. * @param id defines the unique ID of the geometry
  40302. * @param scene defines the hosting scene
  40303. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40304. * @param mesh defines the hosting mesh (can be null)
  40305. */
  40306. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40307. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40308. if (mesh === void 0) { mesh = null; }
  40309. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40310. _this._canBeRegenerated = _canBeRegenerated;
  40311. _this._beingRegenerated = true;
  40312. _this.regenerate();
  40313. _this._beingRegenerated = false;
  40314. return _this;
  40315. }
  40316. /**
  40317. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40318. * @returns true if the geometry can be regenerated
  40319. */
  40320. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40321. return this._canBeRegenerated;
  40322. };
  40323. /**
  40324. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40325. */
  40326. _PrimitiveGeometry.prototype.regenerate = function () {
  40327. if (!this._canBeRegenerated) {
  40328. return;
  40329. }
  40330. this._beingRegenerated = true;
  40331. this.setAllVerticesData(this._regenerateVertexData(), false);
  40332. this._beingRegenerated = false;
  40333. };
  40334. /**
  40335. * Clone the geometry
  40336. * @param id defines the unique ID of the new geometry
  40337. * @returns the new geometry
  40338. */
  40339. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40340. return _super.prototype.copy.call(this, id);
  40341. };
  40342. // overrides
  40343. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40344. if (!this._beingRegenerated) {
  40345. return;
  40346. }
  40347. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40348. };
  40349. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40350. if (!this._beingRegenerated) {
  40351. return;
  40352. }
  40353. _super.prototype.setVerticesData.call(this, kind, data, false);
  40354. };
  40355. // to override
  40356. /** @hidden */
  40357. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40358. throw new Error("Abstract method");
  40359. };
  40360. _PrimitiveGeometry.prototype.copy = function (id) {
  40361. throw new Error("Must be overriden in sub-classes.");
  40362. };
  40363. _PrimitiveGeometry.prototype.serialize = function () {
  40364. var serializationObject = _super.prototype.serialize.call(this);
  40365. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40366. return serializationObject;
  40367. };
  40368. return _PrimitiveGeometry;
  40369. }(Geometry));
  40370. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40371. /**
  40372. * Creates a ribbon geometry
  40373. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40374. */
  40375. var RibbonGeometry = /** @class */ (function (_super) {
  40376. __extends(RibbonGeometry, _super);
  40377. /**
  40378. * Creates a ribbon geometry
  40379. * @param id defines the unique ID of the geometry
  40380. * @param scene defines the hosting scene
  40381. * @param pathArray defines the array of paths to use
  40382. * @param closeArray defines if the last path and the first path must be joined
  40383. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40384. * @param offset defines the offset between points
  40385. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40386. * @param mesh defines the hosting mesh (can be null)
  40387. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40388. */
  40389. function RibbonGeometry(id, scene,
  40390. /**
  40391. * Defines the array of paths to use
  40392. */
  40393. pathArray,
  40394. /**
  40395. * Defines if the last and first points of each path in your pathArray must be joined
  40396. */
  40397. closeArray,
  40398. /**
  40399. * Defines if the last and first points of each path in your pathArray must be joined
  40400. */
  40401. closePath,
  40402. /**
  40403. * Defines the offset between points
  40404. */
  40405. offset, canBeRegenerated, mesh,
  40406. /**
  40407. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40408. */
  40409. side) {
  40410. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40412. _this.pathArray = pathArray;
  40413. _this.closeArray = closeArray;
  40414. _this.closePath = closePath;
  40415. _this.offset = offset;
  40416. _this.side = side;
  40417. return _this;
  40418. }
  40419. /** @hidden */
  40420. RibbonGeometry.prototype._regenerateVertexData = function () {
  40421. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40422. };
  40423. RibbonGeometry.prototype.copy = function (id) {
  40424. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40425. };
  40426. return RibbonGeometry;
  40427. }(_PrimitiveGeometry));
  40428. BABYLON.RibbonGeometry = RibbonGeometry;
  40429. /**
  40430. * Creates a box geometry
  40431. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40432. */
  40433. var BoxGeometry = /** @class */ (function (_super) {
  40434. __extends(BoxGeometry, _super);
  40435. /**
  40436. * Creates a box geometry
  40437. * @param id defines the unique ID of the geometry
  40438. * @param scene defines the hosting scene
  40439. * @param size defines the zise of the box (width, height and depth are the same)
  40440. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40441. * @param mesh defines the hosting mesh (can be null)
  40442. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40443. */
  40444. function BoxGeometry(id, scene,
  40445. /**
  40446. * Defines the zise of the box (width, height and depth are the same)
  40447. */
  40448. size, canBeRegenerated, mesh,
  40449. /**
  40450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. side) {
  40453. if (mesh === void 0) { mesh = null; }
  40454. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40456. _this.size = size;
  40457. _this.side = side;
  40458. return _this;
  40459. }
  40460. BoxGeometry.prototype._regenerateVertexData = function () {
  40461. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40462. };
  40463. BoxGeometry.prototype.copy = function (id) {
  40464. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40465. };
  40466. BoxGeometry.prototype.serialize = function () {
  40467. var serializationObject = _super.prototype.serialize.call(this);
  40468. serializationObject.size = this.size;
  40469. return serializationObject;
  40470. };
  40471. BoxGeometry.Parse = function (parsedBox, scene) {
  40472. if (scene.getGeometryByID(parsedBox.id)) {
  40473. return null; // null since geometry could be something else than a box...
  40474. }
  40475. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40476. if (BABYLON.Tags) {
  40477. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40478. }
  40479. scene.pushGeometry(box, true);
  40480. return box;
  40481. };
  40482. return BoxGeometry;
  40483. }(_PrimitiveGeometry));
  40484. BABYLON.BoxGeometry = BoxGeometry;
  40485. /**
  40486. * Creates a sphere geometry
  40487. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40488. */
  40489. var SphereGeometry = /** @class */ (function (_super) {
  40490. __extends(SphereGeometry, _super);
  40491. /**
  40492. * Create a new sphere geometry
  40493. * @param id defines the unique ID of the geometry
  40494. * @param scene defines the hosting scene
  40495. * @param segments defines the number of segments to use to create the sphere
  40496. * @param diameter defines the diameter of the sphere
  40497. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40498. * @param mesh defines the hosting mesh (can be null)
  40499. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40500. */
  40501. function SphereGeometry(id, scene,
  40502. /**
  40503. * Defines the number of segments to use to create the sphere
  40504. */
  40505. segments,
  40506. /**
  40507. * Defines the diameter of the sphere
  40508. */
  40509. diameter, canBeRegenerated, mesh,
  40510. /**
  40511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40512. */
  40513. side) {
  40514. if (mesh === void 0) { mesh = null; }
  40515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40517. _this.segments = segments;
  40518. _this.diameter = diameter;
  40519. _this.side = side;
  40520. return _this;
  40521. }
  40522. SphereGeometry.prototype._regenerateVertexData = function () {
  40523. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40524. };
  40525. SphereGeometry.prototype.copy = function (id) {
  40526. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40527. };
  40528. SphereGeometry.prototype.serialize = function () {
  40529. var serializationObject = _super.prototype.serialize.call(this);
  40530. serializationObject.segments = this.segments;
  40531. serializationObject.diameter = this.diameter;
  40532. return serializationObject;
  40533. };
  40534. SphereGeometry.Parse = function (parsedSphere, scene) {
  40535. if (scene.getGeometryByID(parsedSphere.id)) {
  40536. return null; // null since geometry could be something else than a sphere...
  40537. }
  40538. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40539. if (BABYLON.Tags) {
  40540. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40541. }
  40542. scene.pushGeometry(sphere, true);
  40543. return sphere;
  40544. };
  40545. return SphereGeometry;
  40546. }(_PrimitiveGeometry));
  40547. BABYLON.SphereGeometry = SphereGeometry;
  40548. /**
  40549. * Creates a disc geometry
  40550. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40551. */
  40552. var DiscGeometry = /** @class */ (function (_super) {
  40553. __extends(DiscGeometry, _super);
  40554. /**
  40555. * Creates a new disc geometry
  40556. * @param id defines the unique ID of the geometry
  40557. * @param scene defines the hosting scene
  40558. * @param radius defines the radius of the disc
  40559. * @param tessellation defines the tesselation factor to apply to the disc
  40560. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40561. * @param mesh defines the hosting mesh (can be null)
  40562. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40563. */
  40564. function DiscGeometry(id, scene,
  40565. /**
  40566. * Defines the radius of the disc
  40567. */
  40568. radius,
  40569. /**
  40570. * Defines the tesselation factor to apply to the disc
  40571. */
  40572. tessellation, canBeRegenerated, mesh,
  40573. /**
  40574. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40575. */
  40576. side) {
  40577. if (mesh === void 0) { mesh = null; }
  40578. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40579. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40580. _this.radius = radius;
  40581. _this.tessellation = tessellation;
  40582. _this.side = side;
  40583. return _this;
  40584. }
  40585. DiscGeometry.prototype._regenerateVertexData = function () {
  40586. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40587. };
  40588. DiscGeometry.prototype.copy = function (id) {
  40589. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40590. };
  40591. return DiscGeometry;
  40592. }(_PrimitiveGeometry));
  40593. BABYLON.DiscGeometry = DiscGeometry;
  40594. /**
  40595. * Creates a new cylinder geometry
  40596. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40597. */
  40598. var CylinderGeometry = /** @class */ (function (_super) {
  40599. __extends(CylinderGeometry, _super);
  40600. /**
  40601. * Creates a new cylinder geometry
  40602. * @param id defines the unique ID of the geometry
  40603. * @param scene defines the hosting scene
  40604. * @param height defines the height of the cylinder
  40605. * @param diameterTop defines the diameter of the cylinder's top cap
  40606. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40607. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40608. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40609. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40610. * @param mesh defines the hosting mesh (can be null)
  40611. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40612. */
  40613. function CylinderGeometry(id, scene,
  40614. /**
  40615. * Defines the height of the cylinder
  40616. */
  40617. height,
  40618. /**
  40619. * Defines the diameter of the cylinder's top cap
  40620. */
  40621. diameterTop,
  40622. /**
  40623. * Defines the diameter of the cylinder's bottom cap
  40624. */
  40625. diameterBottom,
  40626. /**
  40627. * Defines the tessellation factor to apply to the cylinder
  40628. */
  40629. tessellation,
  40630. /**
  40631. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40632. */
  40633. subdivisions, canBeRegenerated, mesh,
  40634. /**
  40635. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40636. */
  40637. side) {
  40638. if (subdivisions === void 0) { subdivisions = 1; }
  40639. if (mesh === void 0) { mesh = null; }
  40640. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40641. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40642. _this.height = height;
  40643. _this.diameterTop = diameterTop;
  40644. _this.diameterBottom = diameterBottom;
  40645. _this.tessellation = tessellation;
  40646. _this.subdivisions = subdivisions;
  40647. _this.side = side;
  40648. return _this;
  40649. }
  40650. CylinderGeometry.prototype._regenerateVertexData = function () {
  40651. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40652. };
  40653. CylinderGeometry.prototype.copy = function (id) {
  40654. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40655. };
  40656. CylinderGeometry.prototype.serialize = function () {
  40657. var serializationObject = _super.prototype.serialize.call(this);
  40658. serializationObject.height = this.height;
  40659. serializationObject.diameterTop = this.diameterTop;
  40660. serializationObject.diameterBottom = this.diameterBottom;
  40661. serializationObject.tessellation = this.tessellation;
  40662. return serializationObject;
  40663. };
  40664. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40665. if (scene.getGeometryByID(parsedCylinder.id)) {
  40666. return null; // null since geometry could be something else than a cylinder...
  40667. }
  40668. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40669. if (BABYLON.Tags) {
  40670. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40671. }
  40672. scene.pushGeometry(cylinder, true);
  40673. return cylinder;
  40674. };
  40675. return CylinderGeometry;
  40676. }(_PrimitiveGeometry));
  40677. BABYLON.CylinderGeometry = CylinderGeometry;
  40678. /**
  40679. * Creates a new torus geometry
  40680. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40681. */
  40682. var TorusGeometry = /** @class */ (function (_super) {
  40683. __extends(TorusGeometry, _super);
  40684. /**
  40685. * Creates a new torus geometry
  40686. * @param id defines the unique ID of the geometry
  40687. * @param scene defines the hosting scene
  40688. * @param diameter defines the diameter of the torus
  40689. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40690. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40691. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40692. * @param mesh defines the hosting mesh (can be null)
  40693. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40694. */
  40695. function TorusGeometry(id, scene,
  40696. /**
  40697. * Defines the diameter of the torus
  40698. */
  40699. diameter,
  40700. /**
  40701. * Defines the thickness of the torus (ie. internal diameter)
  40702. */
  40703. thickness,
  40704. /**
  40705. * Defines the tesselation factor to apply to the torus
  40706. */
  40707. tessellation, canBeRegenerated, mesh,
  40708. /**
  40709. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40710. */
  40711. side) {
  40712. if (mesh === void 0) { mesh = null; }
  40713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40714. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40715. _this.diameter = diameter;
  40716. _this.thickness = thickness;
  40717. _this.tessellation = tessellation;
  40718. _this.side = side;
  40719. return _this;
  40720. }
  40721. TorusGeometry.prototype._regenerateVertexData = function () {
  40722. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40723. };
  40724. TorusGeometry.prototype.copy = function (id) {
  40725. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40726. };
  40727. TorusGeometry.prototype.serialize = function () {
  40728. var serializationObject = _super.prototype.serialize.call(this);
  40729. serializationObject.diameter = this.diameter;
  40730. serializationObject.thickness = this.thickness;
  40731. serializationObject.tessellation = this.tessellation;
  40732. return serializationObject;
  40733. };
  40734. TorusGeometry.Parse = function (parsedTorus, scene) {
  40735. if (scene.getGeometryByID(parsedTorus.id)) {
  40736. return null; // null since geometry could be something else than a torus...
  40737. }
  40738. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40739. if (BABYLON.Tags) {
  40740. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40741. }
  40742. scene.pushGeometry(torus, true);
  40743. return torus;
  40744. };
  40745. return TorusGeometry;
  40746. }(_PrimitiveGeometry));
  40747. BABYLON.TorusGeometry = TorusGeometry;
  40748. /**
  40749. * Creates a new ground geometry
  40750. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40751. */
  40752. var GroundGeometry = /** @class */ (function (_super) {
  40753. __extends(GroundGeometry, _super);
  40754. /**
  40755. * Creates a new ground geometry
  40756. * @param id defines the unique ID of the geometry
  40757. * @param scene defines the hosting scene
  40758. * @param width defines the width of the ground
  40759. * @param height defines the height of the ground
  40760. * @param subdivisions defines the subdivisions to apply to the ground
  40761. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40762. * @param mesh defines the hosting mesh (can be null)
  40763. */
  40764. function GroundGeometry(id, scene,
  40765. /**
  40766. * Defines the width of the ground
  40767. */
  40768. width,
  40769. /**
  40770. * Defines the height of the ground
  40771. */
  40772. height,
  40773. /**
  40774. * Defines the subdivisions to apply to the ground
  40775. */
  40776. subdivisions, canBeRegenerated, mesh) {
  40777. if (mesh === void 0) { mesh = null; }
  40778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40779. _this.width = width;
  40780. _this.height = height;
  40781. _this.subdivisions = subdivisions;
  40782. return _this;
  40783. }
  40784. GroundGeometry.prototype._regenerateVertexData = function () {
  40785. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40786. };
  40787. GroundGeometry.prototype.copy = function (id) {
  40788. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40789. };
  40790. GroundGeometry.prototype.serialize = function () {
  40791. var serializationObject = _super.prototype.serialize.call(this);
  40792. serializationObject.width = this.width;
  40793. serializationObject.height = this.height;
  40794. serializationObject.subdivisions = this.subdivisions;
  40795. return serializationObject;
  40796. };
  40797. GroundGeometry.Parse = function (parsedGround, scene) {
  40798. if (scene.getGeometryByID(parsedGround.id)) {
  40799. return null; // null since geometry could be something else than a ground...
  40800. }
  40801. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40802. if (BABYLON.Tags) {
  40803. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40804. }
  40805. scene.pushGeometry(ground, true);
  40806. return ground;
  40807. };
  40808. return GroundGeometry;
  40809. }(_PrimitiveGeometry));
  40810. BABYLON.GroundGeometry = GroundGeometry;
  40811. /**
  40812. * Creates a tiled ground geometry
  40813. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40814. */
  40815. var TiledGroundGeometry = /** @class */ (function (_super) {
  40816. __extends(TiledGroundGeometry, _super);
  40817. /**
  40818. * Creates a tiled ground geometry
  40819. * @param id defines the unique ID of the geometry
  40820. * @param scene defines the hosting scene
  40821. * @param xmin defines the minimum value on X axis
  40822. * @param zmin defines the minimum value on Z axis
  40823. * @param xmax defines the maximum value on X axis
  40824. * @param zmax defines the maximum value on Z axis
  40825. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40826. * @param precision defines the precision to use when computing the tiles
  40827. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40828. * @param mesh defines the hosting mesh (can be null)
  40829. */
  40830. function TiledGroundGeometry(id, scene,
  40831. /**
  40832. * Defines the minimum value on X axis
  40833. */
  40834. xmin,
  40835. /**
  40836. * Defines the minimum value on Z axis
  40837. */
  40838. zmin,
  40839. /**
  40840. * Defines the maximum value on X axis
  40841. */
  40842. xmax,
  40843. /**
  40844. * Defines the maximum value on Z axis
  40845. */
  40846. zmax,
  40847. /**
  40848. * Defines the subdivisions to apply to the ground
  40849. */
  40850. subdivisions,
  40851. /**
  40852. * Defines the precision to use when computing the tiles
  40853. */
  40854. precision, canBeRegenerated, mesh) {
  40855. if (mesh === void 0) { mesh = null; }
  40856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40857. _this.xmin = xmin;
  40858. _this.zmin = zmin;
  40859. _this.xmax = xmax;
  40860. _this.zmax = zmax;
  40861. _this.subdivisions = subdivisions;
  40862. _this.precision = precision;
  40863. return _this;
  40864. }
  40865. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40866. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40867. };
  40868. TiledGroundGeometry.prototype.copy = function (id) {
  40869. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40870. };
  40871. return TiledGroundGeometry;
  40872. }(_PrimitiveGeometry));
  40873. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40874. /**
  40875. * Creates a plane geometry
  40876. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40877. */
  40878. var PlaneGeometry = /** @class */ (function (_super) {
  40879. __extends(PlaneGeometry, _super);
  40880. /**
  40881. * Creates a plane geometry
  40882. * @param id defines the unique ID of the geometry
  40883. * @param scene defines the hosting scene
  40884. * @param size defines the size of the plane (width === height)
  40885. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40886. * @param mesh defines the hosting mesh (can be null)
  40887. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40888. */
  40889. function PlaneGeometry(id, scene,
  40890. /**
  40891. * Defines the size of the plane (width === height)
  40892. */
  40893. size, canBeRegenerated, mesh,
  40894. /**
  40895. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40896. */
  40897. side) {
  40898. if (mesh === void 0) { mesh = null; }
  40899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40900. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40901. _this.size = size;
  40902. _this.side = side;
  40903. return _this;
  40904. }
  40905. PlaneGeometry.prototype._regenerateVertexData = function () {
  40906. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40907. };
  40908. PlaneGeometry.prototype.copy = function (id) {
  40909. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40910. };
  40911. PlaneGeometry.prototype.serialize = function () {
  40912. var serializationObject = _super.prototype.serialize.call(this);
  40913. serializationObject.size = this.size;
  40914. return serializationObject;
  40915. };
  40916. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40917. if (scene.getGeometryByID(parsedPlane.id)) {
  40918. return null; // null since geometry could be something else than a ground...
  40919. }
  40920. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40921. if (BABYLON.Tags) {
  40922. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40923. }
  40924. scene.pushGeometry(plane, true);
  40925. return plane;
  40926. };
  40927. return PlaneGeometry;
  40928. }(_PrimitiveGeometry));
  40929. BABYLON.PlaneGeometry = PlaneGeometry;
  40930. /**
  40931. * Creates a torus knot geometry
  40932. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40933. */
  40934. var TorusKnotGeometry = /** @class */ (function (_super) {
  40935. __extends(TorusKnotGeometry, _super);
  40936. /**
  40937. * Creates a torus knot geometry
  40938. * @param id defines the unique ID of the geometry
  40939. * @param scene defines the hosting scene
  40940. * @param radius defines the radius of the torus knot
  40941. * @param tube defines the thickness of the torus knot tube
  40942. * @param radialSegments defines the number of radial segments
  40943. * @param tubularSegments defines the number of tubular segments
  40944. * @param p defines the first number of windings
  40945. * @param q defines the second number of windings
  40946. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40947. * @param mesh defines the hosting mesh (can be null)
  40948. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40949. */
  40950. function TorusKnotGeometry(id, scene,
  40951. /**
  40952. * Defines the radius of the torus knot
  40953. */
  40954. radius,
  40955. /**
  40956. * Defines the thickness of the torus knot tube
  40957. */
  40958. tube,
  40959. /**
  40960. * Defines the number of radial segments
  40961. */
  40962. radialSegments,
  40963. /**
  40964. * Defines the number of tubular segments
  40965. */
  40966. tubularSegments,
  40967. /**
  40968. * Defines the first number of windings
  40969. */
  40970. p,
  40971. /**
  40972. * Defines the second number of windings
  40973. */
  40974. q, canBeRegenerated, mesh,
  40975. /**
  40976. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40977. */
  40978. side) {
  40979. if (mesh === void 0) { mesh = null; }
  40980. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40981. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40982. _this.radius = radius;
  40983. _this.tube = tube;
  40984. _this.radialSegments = radialSegments;
  40985. _this.tubularSegments = tubularSegments;
  40986. _this.p = p;
  40987. _this.q = q;
  40988. _this.side = side;
  40989. return _this;
  40990. }
  40991. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40992. 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 });
  40993. };
  40994. TorusKnotGeometry.prototype.copy = function (id) {
  40995. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40996. };
  40997. TorusKnotGeometry.prototype.serialize = function () {
  40998. var serializationObject = _super.prototype.serialize.call(this);
  40999. serializationObject.radius = this.radius;
  41000. serializationObject.tube = this.tube;
  41001. serializationObject.radialSegments = this.radialSegments;
  41002. serializationObject.tubularSegments = this.tubularSegments;
  41003. serializationObject.p = this.p;
  41004. serializationObject.q = this.q;
  41005. return serializationObject;
  41006. };
  41007. ;
  41008. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41009. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41010. return null; // null since geometry could be something else than a ground...
  41011. }
  41012. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41013. if (BABYLON.Tags) {
  41014. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41015. }
  41016. scene.pushGeometry(torusKnot, true);
  41017. return torusKnot;
  41018. };
  41019. return TorusKnotGeometry;
  41020. }(_PrimitiveGeometry));
  41021. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41022. //}
  41023. })(BABYLON || (BABYLON = {}));
  41024. //# sourceMappingURL=babylon.geometry.js.map
  41025. var BABYLON;
  41026. (function (BABYLON) {
  41027. /**
  41028. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41029. */
  41030. var PerformanceMonitor = /** @class */ (function () {
  41031. /**
  41032. * constructor
  41033. * @param frameSampleSize The number of samples required to saturate the sliding window
  41034. */
  41035. function PerformanceMonitor(frameSampleSize) {
  41036. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41037. this._enabled = true;
  41038. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41039. }
  41040. /**
  41041. * Samples current frame
  41042. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41043. */
  41044. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41045. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41046. if (!this._enabled)
  41047. return;
  41048. if (this._lastFrameTimeMs != null) {
  41049. var dt = timeMs - this._lastFrameTimeMs;
  41050. this._rollingFrameTime.add(dt);
  41051. }
  41052. this._lastFrameTimeMs = timeMs;
  41053. };
  41054. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41055. /**
  41056. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41057. * @return Average frame time in milliseconds
  41058. */
  41059. get: function () {
  41060. return this._rollingFrameTime.average;
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41066. /**
  41067. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41068. * @return Frame time variance in milliseconds squared
  41069. */
  41070. get: function () {
  41071. return this._rollingFrameTime.variance;
  41072. },
  41073. enumerable: true,
  41074. configurable: true
  41075. });
  41076. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41077. /**
  41078. * Returns the frame time of the most recent frame
  41079. * @return Frame time in milliseconds
  41080. */
  41081. get: function () {
  41082. return this._rollingFrameTime.history(0);
  41083. },
  41084. enumerable: true,
  41085. configurable: true
  41086. });
  41087. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41088. /**
  41089. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41090. * @return Framerate in frames per second
  41091. */
  41092. get: function () {
  41093. return 1000.0 / this._rollingFrameTime.average;
  41094. },
  41095. enumerable: true,
  41096. configurable: true
  41097. });
  41098. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41099. /**
  41100. * Returns the average framerate in frames per second using the most recent frame time
  41101. * @return Framerate in frames per second
  41102. */
  41103. get: function () {
  41104. var history = this._rollingFrameTime.history(0);
  41105. if (history === 0) {
  41106. return 0;
  41107. }
  41108. return 1000.0 / history;
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41114. /**
  41115. * Returns true if enough samples have been taken to completely fill the sliding window
  41116. * @return true if saturated
  41117. */
  41118. get: function () {
  41119. return this._rollingFrameTime.isSaturated();
  41120. },
  41121. enumerable: true,
  41122. configurable: true
  41123. });
  41124. /**
  41125. * Enables contributions to the sliding window sample set
  41126. */
  41127. PerformanceMonitor.prototype.enable = function () {
  41128. this._enabled = true;
  41129. };
  41130. /**
  41131. * Disables contributions to the sliding window sample set
  41132. * Samples will not be interpolated over the disabled period
  41133. */
  41134. PerformanceMonitor.prototype.disable = function () {
  41135. this._enabled = false;
  41136. //clear last sample to avoid interpolating over the disabled period when next enabled
  41137. this._lastFrameTimeMs = null;
  41138. };
  41139. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41140. /**
  41141. * Returns true if sampling is enabled
  41142. * @return true if enabled
  41143. */
  41144. get: function () {
  41145. return this._enabled;
  41146. },
  41147. enumerable: true,
  41148. configurable: true
  41149. });
  41150. /**
  41151. * Resets performance monitor
  41152. */
  41153. PerformanceMonitor.prototype.reset = function () {
  41154. //clear last sample to avoid interpolating over the disabled period when next enabled
  41155. this._lastFrameTimeMs = null;
  41156. //wipe record
  41157. this._rollingFrameTime.reset();
  41158. };
  41159. return PerformanceMonitor;
  41160. }());
  41161. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41162. /**
  41163. * RollingAverage
  41164. *
  41165. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41166. */
  41167. var RollingAverage = /** @class */ (function () {
  41168. /**
  41169. * constructor
  41170. * @param length The number of samples required to saturate the sliding window
  41171. */
  41172. function RollingAverage(length) {
  41173. this._samples = new Array(length);
  41174. this.reset();
  41175. }
  41176. /**
  41177. * Adds a sample to the sample set
  41178. * @param v The sample value
  41179. */
  41180. RollingAverage.prototype.add = function (v) {
  41181. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41182. var delta;
  41183. //we need to check if we've already wrapped round
  41184. if (this.isSaturated()) {
  41185. //remove bottom of stack from mean
  41186. var bottomValue = this._samples[this._pos];
  41187. delta = bottomValue - this.average;
  41188. this.average -= delta / (this._sampleCount - 1);
  41189. this._m2 -= delta * (bottomValue - this.average);
  41190. }
  41191. else {
  41192. this._sampleCount++;
  41193. }
  41194. //add new value to mean
  41195. delta = v - this.average;
  41196. this.average += delta / (this._sampleCount);
  41197. this._m2 += delta * (v - this.average);
  41198. //set the new variance
  41199. this.variance = this._m2 / (this._sampleCount - 1);
  41200. this._samples[this._pos] = v;
  41201. this._pos++;
  41202. this._pos %= this._samples.length; //positive wrap around
  41203. };
  41204. /**
  41205. * Returns previously added values or null if outside of history or outside the sliding window domain
  41206. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41207. * @return Value previously recorded with add() or null if outside of range
  41208. */
  41209. RollingAverage.prototype.history = function (i) {
  41210. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41211. return 0;
  41212. }
  41213. var i0 = this._wrapPosition(this._pos - 1.0);
  41214. return this._samples[this._wrapPosition(i0 - i)];
  41215. };
  41216. /**
  41217. * Returns true if enough samples have been taken to completely fill the sliding window
  41218. * @return true if sample-set saturated
  41219. */
  41220. RollingAverage.prototype.isSaturated = function () {
  41221. return this._sampleCount >= this._samples.length;
  41222. };
  41223. /**
  41224. * Resets the rolling average (equivalent to 0 samples taken so far)
  41225. */
  41226. RollingAverage.prototype.reset = function () {
  41227. this.average = 0;
  41228. this.variance = 0;
  41229. this._sampleCount = 0;
  41230. this._pos = 0;
  41231. this._m2 = 0;
  41232. };
  41233. /**
  41234. * Wraps a value around the sample range boundaries
  41235. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41236. * @return Wrapped position in sample range
  41237. */
  41238. RollingAverage.prototype._wrapPosition = function (i) {
  41239. var max = this._samples.length;
  41240. return ((i % max) + max) % max;
  41241. };
  41242. return RollingAverage;
  41243. }());
  41244. BABYLON.RollingAverage = RollingAverage;
  41245. })(BABYLON || (BABYLON = {}));
  41246. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41247. var BABYLON;
  41248. (function (BABYLON) {
  41249. /**
  41250. * "Static Class" containing the most commonly used helper while dealing with material for
  41251. * rendering purpose.
  41252. *
  41253. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41254. *
  41255. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41256. */
  41257. var MaterialHelper = /** @class */ (function () {
  41258. function MaterialHelper() {
  41259. }
  41260. /**
  41261. * Bind the current view position to an effect.
  41262. * @param effect The effect to be bound
  41263. * @param scene The scene the eyes position is used from
  41264. */
  41265. MaterialHelper.BindEyePosition = function (effect, scene) {
  41266. if (scene._forcedViewPosition) {
  41267. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41268. return;
  41269. }
  41270. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41271. };
  41272. /**
  41273. * Helps preparing the defines values about the UVs in used in the effect.
  41274. * UVs are shared as much as we can accross chanels in the shaders.
  41275. * @param texture The texture we are preparing the UVs for
  41276. * @param defines The defines to update
  41277. * @param key The chanel key "diffuse", "specular"... used in the shader
  41278. */
  41279. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41280. defines._needUVs = true;
  41281. defines[key] = true;
  41282. if (texture.getTextureMatrix().isIdentity(true)) {
  41283. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41284. if (texture.coordinatesIndex === 0) {
  41285. defines["MAINUV1"] = true;
  41286. }
  41287. else {
  41288. defines["MAINUV2"] = true;
  41289. }
  41290. }
  41291. else {
  41292. defines[key + "DIRECTUV"] = 0;
  41293. }
  41294. };
  41295. /**
  41296. * Binds a texture matrix value to its corrsponding uniform
  41297. * @param texture The texture to bind the matrix for
  41298. * @param uniformBuffer The uniform buffer receivin the data
  41299. * @param key The chanel key "diffuse", "specular"... used in the shader
  41300. */
  41301. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41302. var matrix = texture.getTextureMatrix();
  41303. if (!matrix.isIdentity(true)) {
  41304. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41305. }
  41306. };
  41307. /**
  41308. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41309. * @param mesh defines the current mesh
  41310. * @param scene defines the current scene
  41311. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41312. * @param pointsCloud defines if point cloud rendering has to be turned on
  41313. * @param fogEnabled defines if fog has to be turned on
  41314. * @param alphaTest defines if alpha testing has to be turned on
  41315. * @param defines defines the current list of defines
  41316. */
  41317. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41318. if (defines._areMiscDirty) {
  41319. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41320. defines["POINTSIZE"] = pointsCloud;
  41321. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41322. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41323. defines["ALPHATEST"] = alphaTest;
  41324. }
  41325. };
  41326. /**
  41327. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41328. * @param scene defines the current scene
  41329. * @param engine defines the current engine
  41330. * @param defines specifies the list of active defines
  41331. * @param useInstances defines if instances have to be turned on
  41332. * @param useClipPlane defines if clip plane have to be turned on
  41333. */
  41334. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41335. if (useClipPlane === void 0) { useClipPlane = null; }
  41336. var changed = false;
  41337. if (useClipPlane == null) {
  41338. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41339. }
  41340. if (defines["CLIPPLANE"] !== useClipPlane) {
  41341. defines["CLIPPLANE"] = useClipPlane;
  41342. changed = true;
  41343. }
  41344. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41345. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41346. changed = true;
  41347. }
  41348. if (defines["INSTANCES"] !== useInstances) {
  41349. defines["INSTANCES"] = useInstances;
  41350. changed = true;
  41351. }
  41352. if (changed) {
  41353. defines.markAsUnprocessed();
  41354. }
  41355. };
  41356. /**
  41357. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41358. * @param mesh The mesh containing the geometry data we will draw
  41359. * @param defines The defines to update
  41360. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41361. * @param useBones Precise whether bones should be used or not (override mesh info)
  41362. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41363. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41364. * @returns false if defines are considered not dirty and have not been checked
  41365. */
  41366. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41367. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41368. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41369. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41370. return false;
  41371. }
  41372. defines._normals = defines._needNormals;
  41373. defines._uvs = defines._needUVs;
  41374. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41375. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41376. defines["TANGENT"] = true;
  41377. }
  41378. if (defines._needUVs) {
  41379. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41380. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41381. }
  41382. else {
  41383. defines["UV1"] = false;
  41384. defines["UV2"] = false;
  41385. }
  41386. if (useVertexColor) {
  41387. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41388. defines["VERTEXCOLOR"] = hasVertexColors;
  41389. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41390. }
  41391. if (useBones) {
  41392. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41393. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41394. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41395. }
  41396. else {
  41397. defines["NUM_BONE_INFLUENCERS"] = 0;
  41398. defines["BonesPerMesh"] = 0;
  41399. }
  41400. }
  41401. if (useMorphTargets) {
  41402. var manager = mesh.morphTargetManager;
  41403. if (manager) {
  41404. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41405. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41406. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41407. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41408. }
  41409. else {
  41410. defines["MORPHTARGETS_TANGENT"] = false;
  41411. defines["MORPHTARGETS_NORMAL"] = false;
  41412. defines["MORPHTARGETS"] = false;
  41413. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41414. }
  41415. }
  41416. return true;
  41417. };
  41418. /**
  41419. * Prepares the defines related to the light information passed in parameter
  41420. * @param scene The scene we are intending to draw
  41421. * @param mesh The mesh the effect is compiling for
  41422. * @param defines The defines to update
  41423. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41424. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41425. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41426. * @returns true if normals will be required for the rest of the effect
  41427. */
  41428. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41429. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41430. if (disableLighting === void 0) { disableLighting = false; }
  41431. if (!defines._areLightsDirty) {
  41432. return defines._needNormals;
  41433. }
  41434. var lightIndex = 0;
  41435. var needNormals = false;
  41436. var needRebuild = false;
  41437. var lightmapMode = false;
  41438. var shadowEnabled = false;
  41439. var specularEnabled = false;
  41440. if (scene.lightsEnabled && !disableLighting) {
  41441. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41442. var light = _a[_i];
  41443. needNormals = true;
  41444. if (defines["LIGHT" + lightIndex] === undefined) {
  41445. needRebuild = true;
  41446. }
  41447. defines["LIGHT" + lightIndex] = true;
  41448. defines["SPOTLIGHT" + lightIndex] = false;
  41449. defines["HEMILIGHT" + lightIndex] = false;
  41450. defines["POINTLIGHT" + lightIndex] = false;
  41451. defines["DIRLIGHT" + lightIndex] = false;
  41452. var type;
  41453. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41454. type = "SPOTLIGHT" + lightIndex;
  41455. var spotLight = light;
  41456. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41457. }
  41458. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41459. type = "HEMILIGHT" + lightIndex;
  41460. }
  41461. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41462. type = "POINTLIGHT" + lightIndex;
  41463. }
  41464. else {
  41465. type = "DIRLIGHT" + lightIndex;
  41466. }
  41467. defines[type] = true;
  41468. // Specular
  41469. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41470. specularEnabled = true;
  41471. }
  41472. // Shadows
  41473. defines["SHADOW" + lightIndex] = false;
  41474. defines["SHADOWPCF" + lightIndex] = false;
  41475. defines["SHADOWPCSS" + lightIndex] = false;
  41476. defines["SHADOWPOISSON" + lightIndex] = false;
  41477. defines["SHADOWESM" + lightIndex] = false;
  41478. defines["SHADOWCUBE" + lightIndex] = false;
  41479. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41480. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41481. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41482. var shadowGenerator = light.getShadowGenerator();
  41483. if (shadowGenerator) {
  41484. shadowEnabled = true;
  41485. shadowGenerator.prepareDefines(defines, lightIndex);
  41486. }
  41487. }
  41488. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41489. lightmapMode = true;
  41490. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41491. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41492. }
  41493. else {
  41494. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41495. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41496. }
  41497. lightIndex++;
  41498. if (lightIndex === maxSimultaneousLights)
  41499. break;
  41500. }
  41501. }
  41502. defines["SPECULARTERM"] = specularEnabled;
  41503. defines["SHADOWS"] = shadowEnabled;
  41504. // Resetting all other lights if any
  41505. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41506. if (defines["LIGHT" + index] !== undefined) {
  41507. defines["LIGHT" + index] = false;
  41508. defines["HEMILIGHT" + lightIndex] = false;
  41509. defines["POINTLIGHT" + lightIndex] = false;
  41510. defines["DIRLIGHT" + lightIndex] = false;
  41511. defines["SPOTLIGHT" + lightIndex] = false;
  41512. defines["SHADOW" + lightIndex] = false;
  41513. }
  41514. }
  41515. var caps = scene.getEngine().getCaps();
  41516. if (defines["SHADOWFLOAT"] === undefined) {
  41517. needRebuild = true;
  41518. }
  41519. defines["SHADOWFLOAT"] = shadowEnabled &&
  41520. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41521. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41522. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41523. if (needRebuild) {
  41524. defines.rebuild();
  41525. }
  41526. return needNormals;
  41527. };
  41528. /**
  41529. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41530. * that won t be acctive due to defines being turned off.
  41531. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41532. * @param samplersList The samplers list
  41533. * @param defines The defines helping in the list generation
  41534. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41535. */
  41536. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41537. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41538. var uniformsList;
  41539. var uniformBuffersList = null;
  41540. if (uniformsListOrOptions.uniformsNames) {
  41541. var options = uniformsListOrOptions;
  41542. uniformsList = options.uniformsNames;
  41543. uniformBuffersList = options.uniformBuffersNames;
  41544. samplersList = options.samplers;
  41545. defines = options.defines;
  41546. maxSimultaneousLights = options.maxSimultaneousLights;
  41547. }
  41548. else {
  41549. uniformsList = uniformsListOrOptions;
  41550. if (!samplersList) {
  41551. samplersList = [];
  41552. }
  41553. }
  41554. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41555. if (!defines["LIGHT" + lightIndex]) {
  41556. break;
  41557. }
  41558. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41559. if (uniformBuffersList) {
  41560. uniformBuffersList.push("Light" + lightIndex);
  41561. }
  41562. samplersList.push("shadowSampler" + lightIndex);
  41563. samplersList.push("depthSampler" + lightIndex);
  41564. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41565. samplersList.push("projectionLightSampler" + lightIndex);
  41566. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41567. }
  41568. }
  41569. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41570. uniformsList.push("morphTargetInfluences");
  41571. }
  41572. };
  41573. /**
  41574. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41575. * @param defines The defines to update while falling back
  41576. * @param fallbacks The authorized effect fallbacks
  41577. * @param maxSimultaneousLights The maximum number of lights allowed
  41578. * @param rank the current rank of the Effect
  41579. * @returns The newly affected rank
  41580. */
  41581. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41582. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41583. if (rank === void 0) { rank = 0; }
  41584. var lightFallbackRank = 0;
  41585. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41586. if (!defines["LIGHT" + lightIndex]) {
  41587. break;
  41588. }
  41589. if (lightIndex > 0) {
  41590. lightFallbackRank = rank + lightIndex;
  41591. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41592. }
  41593. if (!defines["SHADOWS"]) {
  41594. if (defines["SHADOW" + lightIndex]) {
  41595. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41596. }
  41597. if (defines["SHADOWPCF" + lightIndex]) {
  41598. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41599. }
  41600. if (defines["SHADOWPCSS" + lightIndex]) {
  41601. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41602. }
  41603. if (defines["SHADOWPOISSON" + lightIndex]) {
  41604. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41605. }
  41606. if (defines["SHADOWESM" + lightIndex]) {
  41607. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41608. }
  41609. }
  41610. }
  41611. return lightFallbackRank++;
  41612. };
  41613. /**
  41614. * Prepares the list of attributes required for morph targets according to the effect defines.
  41615. * @param attribs The current list of supported attribs
  41616. * @param mesh The mesh to prepare the morph targets attributes for
  41617. * @param defines The current Defines of the effect
  41618. */
  41619. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41620. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41621. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41622. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41623. var manager = mesh.morphTargetManager;
  41624. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41625. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41626. for (var index = 0; index < influencers; index++) {
  41627. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41628. if (normal) {
  41629. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41630. }
  41631. if (tangent) {
  41632. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41633. }
  41634. if (attribs.length > maxAttributesCount) {
  41635. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41636. }
  41637. }
  41638. }
  41639. };
  41640. /**
  41641. * Prepares the list of attributes required for bones according to the effect defines.
  41642. * @param attribs The current list of supported attribs
  41643. * @param mesh The mesh to prepare the bones attributes for
  41644. * @param defines The current Defines of the effect
  41645. * @param fallbacks The current efffect fallback strategy
  41646. */
  41647. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41648. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41649. fallbacks.addCPUSkinningFallback(0, mesh);
  41650. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41651. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41652. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41655. }
  41656. }
  41657. };
  41658. /**
  41659. * Prepares the list of attributes required for instances according to the effect defines.
  41660. * @param attribs The current list of supported attribs
  41661. * @param defines The current Defines of the effect
  41662. */
  41663. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41664. if (defines["INSTANCES"]) {
  41665. attribs.push("world0");
  41666. attribs.push("world1");
  41667. attribs.push("world2");
  41668. attribs.push("world3");
  41669. }
  41670. };
  41671. /**
  41672. * Binds the light shadow information to the effect for the given mesh.
  41673. * @param light The light containing the generator
  41674. * @param scene The scene the lights belongs to
  41675. * @param mesh The mesh we are binding the information to render
  41676. * @param lightIndex The light index in the effect used to render the mesh
  41677. * @param effect The effect we are binding the data to
  41678. */
  41679. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41680. if (light.shadowEnabled && mesh.receiveShadows) {
  41681. var shadowGenerator = light.getShadowGenerator();
  41682. if (shadowGenerator) {
  41683. shadowGenerator.bindShadowLight(lightIndex, effect);
  41684. }
  41685. }
  41686. };
  41687. /**
  41688. * Binds the light information to the effect.
  41689. * @param light The light containing the generator
  41690. * @param effect The effect we are binding the data to
  41691. * @param lightIndex The light index in the effect used to render
  41692. */
  41693. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41694. light.transferToEffect(effect, lightIndex + "");
  41695. };
  41696. /**
  41697. * Binds the lights information from the scene to the effect for the given mesh.
  41698. * @param scene The scene the lights belongs to
  41699. * @param mesh The mesh we are binding the information to render
  41700. * @param effect The effect we are binding the data to
  41701. * @param defines The generated defines for the effect
  41702. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41703. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41704. */
  41705. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41706. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41707. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41708. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41709. for (var i = 0; i < len; i++) {
  41710. var light = mesh._lightSources[i];
  41711. var iAsString = i.toString();
  41712. var scaledIntensity = light.getScaledIntensity();
  41713. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41714. MaterialHelper.BindLightProperties(light, effect, i);
  41715. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41716. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41717. if (defines["SPECULARTERM"]) {
  41718. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41719. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41720. }
  41721. // Shadows
  41722. if (scene.shadowsEnabled) {
  41723. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41724. }
  41725. light._uniformBuffer.update();
  41726. }
  41727. };
  41728. /**
  41729. * Binds the fog information from the scene to the effect for the given mesh.
  41730. * @param scene The scene the lights belongs to
  41731. * @param mesh The mesh we are binding the information to render
  41732. * @param effect The effect we are binding the data to
  41733. */
  41734. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41735. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41736. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41737. effect.setColor3("vFogColor", scene.fogColor);
  41738. }
  41739. };
  41740. /**
  41741. * Binds the bones information from the mesh to the effect.
  41742. * @param mesh The mesh we are binding the information to render
  41743. * @param effect The effect we are binding the data to
  41744. */
  41745. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41746. if (!effect || !mesh) {
  41747. return;
  41748. }
  41749. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41750. mesh.computeBonesUsingShaders = false;
  41751. }
  41752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41753. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41754. if (matrices) {
  41755. effect.setMatrices("mBones", matrices);
  41756. }
  41757. }
  41758. };
  41759. /**
  41760. * Binds the morph targets information from the mesh to the effect.
  41761. * @param abstractMesh The mesh we are binding the information to render
  41762. * @param effect The effect we are binding the data to
  41763. */
  41764. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41765. var manager = abstractMesh.morphTargetManager;
  41766. if (!abstractMesh || !manager) {
  41767. return;
  41768. }
  41769. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41770. };
  41771. /**
  41772. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41773. * @param defines The generated defines used in the effect
  41774. * @param effect The effect we are binding the data to
  41775. * @param scene The scene we are willing to render with logarithmic scale for
  41776. */
  41777. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41778. if (defines["LOGARITHMICDEPTH"]) {
  41779. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41780. }
  41781. };
  41782. /**
  41783. * Binds the clip plane information from the scene to the effect.
  41784. * @param scene The scene the clip plane information are extracted from
  41785. * @param effect The effect we are binding the data to
  41786. */
  41787. MaterialHelper.BindClipPlane = function (effect, scene) {
  41788. if (scene.clipPlane) {
  41789. var clipPlane = scene.clipPlane;
  41790. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41791. }
  41792. };
  41793. return MaterialHelper;
  41794. }());
  41795. BABYLON.MaterialHelper = MaterialHelper;
  41796. })(BABYLON || (BABYLON = {}));
  41797. //# sourceMappingURL=babylon.materialHelper.js.map
  41798. var BABYLON;
  41799. (function (BABYLON) {
  41800. var PushMaterial = /** @class */ (function (_super) {
  41801. __extends(PushMaterial, _super);
  41802. function PushMaterial(name, scene) {
  41803. var _this = _super.call(this, name, scene) || this;
  41804. _this._normalMatrix = new BABYLON.Matrix();
  41805. _this.storeEffectOnSubMeshes = true;
  41806. return _this;
  41807. }
  41808. PushMaterial.prototype.getEffect = function () {
  41809. return this._activeEffect;
  41810. };
  41811. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41812. if (!mesh) {
  41813. return false;
  41814. }
  41815. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41816. return true;
  41817. }
  41818. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41819. };
  41820. /**
  41821. * Binds the given world matrix to the active effect
  41822. *
  41823. * @param world the matrix to bind
  41824. */
  41825. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41826. this._activeEffect.setMatrix("world", world);
  41827. };
  41828. /**
  41829. * Binds the given normal matrix to the active effect
  41830. *
  41831. * @param normalMatrix the matrix to bind
  41832. */
  41833. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41834. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41835. };
  41836. PushMaterial.prototype.bind = function (world, mesh) {
  41837. if (!mesh) {
  41838. return;
  41839. }
  41840. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41841. };
  41842. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41843. if (effect === void 0) { effect = null; }
  41844. _super.prototype._afterBind.call(this, mesh);
  41845. this.getScene()._cachedEffect = effect;
  41846. };
  41847. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41848. if (visibility === void 0) { visibility = 1; }
  41849. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41850. };
  41851. return PushMaterial;
  41852. }(BABYLON.Material));
  41853. BABYLON.PushMaterial = PushMaterial;
  41854. })(BABYLON || (BABYLON = {}));
  41855. //# sourceMappingURL=babylon.pushMaterial.js.map
  41856. var BABYLON;
  41857. (function (BABYLON) {
  41858. /** @hidden */
  41859. var StandardMaterialDefines = /** @class */ (function (_super) {
  41860. __extends(StandardMaterialDefines, _super);
  41861. function StandardMaterialDefines() {
  41862. var _this = _super.call(this) || this;
  41863. _this.MAINUV1 = false;
  41864. _this.MAINUV2 = false;
  41865. _this.DIFFUSE = false;
  41866. _this.DIFFUSEDIRECTUV = 0;
  41867. _this.AMBIENT = false;
  41868. _this.AMBIENTDIRECTUV = 0;
  41869. _this.OPACITY = false;
  41870. _this.OPACITYDIRECTUV = 0;
  41871. _this.OPACITYRGB = false;
  41872. _this.REFLECTION = false;
  41873. _this.EMISSIVE = false;
  41874. _this.EMISSIVEDIRECTUV = 0;
  41875. _this.SPECULAR = false;
  41876. _this.SPECULARDIRECTUV = 0;
  41877. _this.BUMP = false;
  41878. _this.BUMPDIRECTUV = 0;
  41879. _this.PARALLAX = false;
  41880. _this.PARALLAXOCCLUSION = false;
  41881. _this.SPECULAROVERALPHA = false;
  41882. _this.CLIPPLANE = false;
  41883. _this.ALPHATEST = false;
  41884. _this.DEPTHPREPASS = false;
  41885. _this.ALPHAFROMDIFFUSE = false;
  41886. _this.POINTSIZE = false;
  41887. _this.FOG = false;
  41888. _this.SPECULARTERM = false;
  41889. _this.DIFFUSEFRESNEL = false;
  41890. _this.OPACITYFRESNEL = false;
  41891. _this.REFLECTIONFRESNEL = false;
  41892. _this.REFRACTIONFRESNEL = false;
  41893. _this.EMISSIVEFRESNEL = false;
  41894. _this.FRESNEL = false;
  41895. _this.NORMAL = false;
  41896. _this.UV1 = false;
  41897. _this.UV2 = false;
  41898. _this.VERTEXCOLOR = false;
  41899. _this.VERTEXALPHA = false;
  41900. _this.NUM_BONE_INFLUENCERS = 0;
  41901. _this.BonesPerMesh = 0;
  41902. _this.INSTANCES = false;
  41903. _this.GLOSSINESS = false;
  41904. _this.ROUGHNESS = false;
  41905. _this.EMISSIVEASILLUMINATION = false;
  41906. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41907. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41908. _this.LIGHTMAP = false;
  41909. _this.LIGHTMAPDIRECTUV = 0;
  41910. _this.OBJECTSPACE_NORMALMAP = false;
  41911. _this.USELIGHTMAPASSHADOWMAP = false;
  41912. _this.REFLECTIONMAP_3D = false;
  41913. _this.REFLECTIONMAP_SPHERICAL = false;
  41914. _this.REFLECTIONMAP_PLANAR = false;
  41915. _this.REFLECTIONMAP_CUBIC = false;
  41916. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41917. _this.REFLECTIONMAP_PROJECTION = false;
  41918. _this.REFLECTIONMAP_SKYBOX = false;
  41919. _this.REFLECTIONMAP_EXPLICIT = false;
  41920. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41921. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41922. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41923. _this.INVERTCUBICMAP = false;
  41924. _this.LOGARITHMICDEPTH = false;
  41925. _this.REFRACTION = false;
  41926. _this.REFRACTIONMAP_3D = false;
  41927. _this.REFLECTIONOVERALPHA = false;
  41928. _this.TWOSIDEDLIGHTING = false;
  41929. _this.SHADOWFLOAT = false;
  41930. _this.MORPHTARGETS = false;
  41931. _this.MORPHTARGETS_NORMAL = false;
  41932. _this.MORPHTARGETS_TANGENT = false;
  41933. _this.NUM_MORPH_INFLUENCERS = 0;
  41934. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41935. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41936. _this.IMAGEPROCESSING = false;
  41937. _this.VIGNETTE = false;
  41938. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41939. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41940. _this.TONEMAPPING = false;
  41941. _this.CONTRAST = false;
  41942. _this.COLORCURVES = false;
  41943. _this.COLORGRADING = false;
  41944. _this.COLORGRADING3D = false;
  41945. _this.SAMPLER3DGREENDEPTH = false;
  41946. _this.SAMPLER3DBGRMAP = false;
  41947. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41948. /**
  41949. * If the reflection texture on this material is in linear color space
  41950. * @hidden
  41951. */
  41952. _this.IS_REFLECTION_LINEAR = false;
  41953. /**
  41954. * If the refraction texture on this material is in linear color space
  41955. * @hidden
  41956. */
  41957. _this.IS_REFRACTION_LINEAR = false;
  41958. _this.EXPOSURE = false;
  41959. _this.rebuild();
  41960. return _this;
  41961. }
  41962. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41963. var modes = [
  41964. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41965. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41966. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41967. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41968. ];
  41969. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41970. var mode = modes_1[_i];
  41971. this[mode] = (mode === modeToEnable);
  41972. }
  41973. };
  41974. return StandardMaterialDefines;
  41975. }(BABYLON.MaterialDefines));
  41976. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41977. var StandardMaterial = /** @class */ (function (_super) {
  41978. __extends(StandardMaterial, _super);
  41979. function StandardMaterial(name, scene) {
  41980. var _this = _super.call(this, name, scene) || this;
  41981. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41982. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41983. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41984. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41985. _this.specularPower = 64;
  41986. _this._useAlphaFromDiffuseTexture = false;
  41987. _this._useEmissiveAsIllumination = false;
  41988. _this._linkEmissiveWithDiffuse = false;
  41989. _this._useSpecularOverAlpha = false;
  41990. _this._useReflectionOverAlpha = false;
  41991. _this._disableLighting = false;
  41992. _this._useObjectSpaceNormalMap = false;
  41993. _this._useParallax = false;
  41994. _this._useParallaxOcclusion = false;
  41995. _this.parallaxScaleBias = 0.05;
  41996. _this._roughness = 0;
  41997. _this.indexOfRefraction = 0.98;
  41998. _this.invertRefractionY = true;
  41999. /**
  42000. * Defines the alpha limits in alpha test mode
  42001. */
  42002. _this.alphaCutOff = 0.4;
  42003. _this._useLightmapAsShadowmap = false;
  42004. _this._useReflectionFresnelFromSpecular = false;
  42005. _this._useGlossinessFromSpecularMapAlpha = false;
  42006. _this._maxSimultaneousLights = 4;
  42007. /**
  42008. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42009. */
  42010. _this._invertNormalMapX = false;
  42011. /**
  42012. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42013. */
  42014. _this._invertNormalMapY = false;
  42015. /**
  42016. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42017. */
  42018. _this._twoSidedLighting = false;
  42019. _this._renderTargets = new BABYLON.SmartArray(16);
  42020. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42021. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42022. // Setup the default processing configuration to the scene.
  42023. _this._attachImageProcessingConfiguration(null);
  42024. _this.getRenderTargetTextures = function () {
  42025. _this._renderTargets.reset();
  42026. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42027. _this._renderTargets.push(_this._reflectionTexture);
  42028. }
  42029. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42030. _this._renderTargets.push(_this._refractionTexture);
  42031. }
  42032. return _this._renderTargets;
  42033. };
  42034. return _this;
  42035. }
  42036. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42037. /**
  42038. * Gets the image processing configuration used either in this material.
  42039. */
  42040. get: function () {
  42041. return this._imageProcessingConfiguration;
  42042. },
  42043. /**
  42044. * Sets the Default image processing configuration used either in the this material.
  42045. *
  42046. * If sets to null, the scene one is in use.
  42047. */
  42048. set: function (value) {
  42049. this._attachImageProcessingConfiguration(value);
  42050. // Ensure the effect will be rebuilt.
  42051. this._markAllSubMeshesAsTexturesDirty();
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. /**
  42057. * Attaches a new image processing configuration to the Standard Material.
  42058. * @param configuration
  42059. */
  42060. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42061. var _this = this;
  42062. if (configuration === this._imageProcessingConfiguration) {
  42063. return;
  42064. }
  42065. // Detaches observer.
  42066. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42067. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42068. }
  42069. // Pick the scene configuration if needed.
  42070. if (!configuration) {
  42071. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42072. }
  42073. else {
  42074. this._imageProcessingConfiguration = configuration;
  42075. }
  42076. // Attaches observer.
  42077. if (this._imageProcessingConfiguration) {
  42078. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42079. _this._markAllSubMeshesAsImageProcessingDirty();
  42080. });
  42081. }
  42082. };
  42083. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42084. /**
  42085. * Gets wether the color curves effect is enabled.
  42086. */
  42087. get: function () {
  42088. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42089. },
  42090. /**
  42091. * Sets wether the color curves effect is enabled.
  42092. */
  42093. set: function (value) {
  42094. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42095. },
  42096. enumerable: true,
  42097. configurable: true
  42098. });
  42099. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42100. /**
  42101. * Gets wether the color grading effect is enabled.
  42102. */
  42103. get: function () {
  42104. return this.imageProcessingConfiguration.colorGradingEnabled;
  42105. },
  42106. /**
  42107. * Gets wether the color grading effect is enabled.
  42108. */
  42109. set: function (value) {
  42110. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42111. },
  42112. enumerable: true,
  42113. configurable: true
  42114. });
  42115. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42116. /**
  42117. * Gets wether tonemapping is enabled or not.
  42118. */
  42119. get: function () {
  42120. return this._imageProcessingConfiguration.toneMappingEnabled;
  42121. },
  42122. /**
  42123. * Sets wether tonemapping is enabled or not
  42124. */
  42125. set: function (value) {
  42126. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42127. },
  42128. enumerable: true,
  42129. configurable: true
  42130. });
  42131. ;
  42132. ;
  42133. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42134. /**
  42135. * The camera exposure used on this material.
  42136. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42137. * This corresponds to a photographic exposure.
  42138. */
  42139. get: function () {
  42140. return this._imageProcessingConfiguration.exposure;
  42141. },
  42142. /**
  42143. * The camera exposure used on this material.
  42144. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42145. * This corresponds to a photographic exposure.
  42146. */
  42147. set: function (value) {
  42148. this._imageProcessingConfiguration.exposure = value;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. ;
  42154. ;
  42155. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42156. /**
  42157. * Gets The camera contrast used on this material.
  42158. */
  42159. get: function () {
  42160. return this._imageProcessingConfiguration.contrast;
  42161. },
  42162. /**
  42163. * Sets The camera contrast used on this material.
  42164. */
  42165. set: function (value) {
  42166. this._imageProcessingConfiguration.contrast = value;
  42167. },
  42168. enumerable: true,
  42169. configurable: true
  42170. });
  42171. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42172. /**
  42173. * Gets the Color Grading 2D Lookup Texture.
  42174. */
  42175. get: function () {
  42176. return this._imageProcessingConfiguration.colorGradingTexture;
  42177. },
  42178. /**
  42179. * Sets the Color Grading 2D Lookup Texture.
  42180. */
  42181. set: function (value) {
  42182. this._imageProcessingConfiguration.colorGradingTexture = value;
  42183. },
  42184. enumerable: true,
  42185. configurable: true
  42186. });
  42187. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42188. /**
  42189. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42190. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42191. * 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;
  42192. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42193. */
  42194. get: function () {
  42195. return this._imageProcessingConfiguration.colorCurves;
  42196. },
  42197. /**
  42198. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42199. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42200. * 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;
  42201. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42202. */
  42203. set: function (value) {
  42204. this._imageProcessingConfiguration.colorCurves = value;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. StandardMaterial.prototype.getClassName = function () {
  42210. return "StandardMaterial";
  42211. };
  42212. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42213. get: function () {
  42214. return this._useLogarithmicDepth;
  42215. },
  42216. set: function (value) {
  42217. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42218. this._markAllSubMeshesAsMiscDirty();
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. StandardMaterial.prototype.needAlphaBlending = function () {
  42224. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42225. };
  42226. StandardMaterial.prototype.needAlphaTesting = function () {
  42227. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42228. };
  42229. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42230. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42231. };
  42232. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42233. return this._diffuseTexture;
  42234. };
  42235. /**
  42236. * Child classes can use it to update shaders
  42237. */
  42238. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42239. if (useInstances === void 0) { useInstances = false; }
  42240. if (subMesh.effect && this.isFrozen) {
  42241. if (this._wasPreviouslyReady && subMesh.effect) {
  42242. return true;
  42243. }
  42244. }
  42245. if (!subMesh._materialDefines) {
  42246. subMesh._materialDefines = new StandardMaterialDefines();
  42247. }
  42248. var scene = this.getScene();
  42249. var defines = subMesh._materialDefines;
  42250. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42251. if (defines._renderId === scene.getRenderId()) {
  42252. return true;
  42253. }
  42254. }
  42255. var engine = scene.getEngine();
  42256. // Lights
  42257. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42258. // Textures
  42259. if (defines._areTexturesDirty) {
  42260. defines._needUVs = false;
  42261. defines.MAINUV1 = false;
  42262. defines.MAINUV2 = false;
  42263. if (scene.texturesEnabled) {
  42264. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42265. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42266. return false;
  42267. }
  42268. else {
  42269. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42270. }
  42271. }
  42272. else {
  42273. defines.DIFFUSE = false;
  42274. }
  42275. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42276. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42277. return false;
  42278. }
  42279. else {
  42280. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42281. }
  42282. }
  42283. else {
  42284. defines.AMBIENT = false;
  42285. }
  42286. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42287. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42288. return false;
  42289. }
  42290. else {
  42291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42292. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42293. }
  42294. }
  42295. else {
  42296. defines.OPACITY = false;
  42297. }
  42298. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42299. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42300. return false;
  42301. }
  42302. else {
  42303. defines._needNormals = true;
  42304. defines.REFLECTION = true;
  42305. defines.ROUGHNESS = (this._roughness > 0);
  42306. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42307. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42308. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42309. switch (this._reflectionTexture.coordinatesMode) {
  42310. case BABYLON.Texture.EXPLICIT_MODE:
  42311. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42312. break;
  42313. case BABYLON.Texture.PLANAR_MODE:
  42314. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42315. break;
  42316. case BABYLON.Texture.PROJECTION_MODE:
  42317. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42318. break;
  42319. case BABYLON.Texture.SKYBOX_MODE:
  42320. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42321. break;
  42322. case BABYLON.Texture.SPHERICAL_MODE:
  42323. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42324. break;
  42325. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42326. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42327. break;
  42328. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42329. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42330. break;
  42331. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42332. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42333. break;
  42334. case BABYLON.Texture.CUBIC_MODE:
  42335. case BABYLON.Texture.INVCUBIC_MODE:
  42336. default:
  42337. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42338. break;
  42339. }
  42340. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42341. }
  42342. }
  42343. else {
  42344. defines.REFLECTION = false;
  42345. }
  42346. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42347. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42348. return false;
  42349. }
  42350. else {
  42351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42352. }
  42353. }
  42354. else {
  42355. defines.EMISSIVE = false;
  42356. }
  42357. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42358. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42359. return false;
  42360. }
  42361. else {
  42362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42363. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42364. }
  42365. }
  42366. else {
  42367. defines.LIGHTMAP = false;
  42368. }
  42369. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42370. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42371. return false;
  42372. }
  42373. else {
  42374. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42375. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42376. }
  42377. }
  42378. else {
  42379. defines.SPECULAR = false;
  42380. }
  42381. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42382. // Bump texure can not be not blocking.
  42383. if (!this._bumpTexture.isReady()) {
  42384. return false;
  42385. }
  42386. else {
  42387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42388. defines.PARALLAX = this._useParallax;
  42389. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42390. }
  42391. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42392. }
  42393. else {
  42394. defines.BUMP = false;
  42395. }
  42396. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42397. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42398. return false;
  42399. }
  42400. else {
  42401. defines._needUVs = true;
  42402. defines.REFRACTION = true;
  42403. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42404. }
  42405. }
  42406. else {
  42407. defines.REFRACTION = false;
  42408. }
  42409. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42410. }
  42411. else {
  42412. defines.DIFFUSE = false;
  42413. defines.AMBIENT = false;
  42414. defines.OPACITY = false;
  42415. defines.REFLECTION = false;
  42416. defines.EMISSIVE = false;
  42417. defines.LIGHTMAP = false;
  42418. defines.BUMP = false;
  42419. defines.REFRACTION = false;
  42420. }
  42421. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42422. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42423. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42424. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42425. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42426. }
  42427. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42428. if (!this._imageProcessingConfiguration.isReady()) {
  42429. return false;
  42430. }
  42431. this._imageProcessingConfiguration.prepareDefines(defines);
  42432. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42433. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42434. }
  42435. if (defines._areFresnelDirty) {
  42436. if (StandardMaterial.FresnelEnabled) {
  42437. // Fresnel
  42438. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42439. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42440. this._reflectionFresnelParameters) {
  42441. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42442. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42443. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42444. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42445. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42446. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42447. defines._needNormals = true;
  42448. defines.FRESNEL = true;
  42449. }
  42450. }
  42451. else {
  42452. defines.FRESNEL = false;
  42453. }
  42454. }
  42455. // Misc.
  42456. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42457. // Attribs
  42458. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42459. // Values that need to be evaluated on every frame
  42460. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42461. // Get correct effect
  42462. if (defines.isDirty) {
  42463. defines.markAsProcessed();
  42464. scene.resetCachedMaterial();
  42465. // Fallbacks
  42466. var fallbacks = new BABYLON.EffectFallbacks();
  42467. if (defines.REFLECTION) {
  42468. fallbacks.addFallback(0, "REFLECTION");
  42469. }
  42470. if (defines.SPECULAR) {
  42471. fallbacks.addFallback(0, "SPECULAR");
  42472. }
  42473. if (defines.BUMP) {
  42474. fallbacks.addFallback(0, "BUMP");
  42475. }
  42476. if (defines.PARALLAX) {
  42477. fallbacks.addFallback(1, "PARALLAX");
  42478. }
  42479. if (defines.PARALLAXOCCLUSION) {
  42480. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42481. }
  42482. if (defines.SPECULAROVERALPHA) {
  42483. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42484. }
  42485. if (defines.FOG) {
  42486. fallbacks.addFallback(1, "FOG");
  42487. }
  42488. if (defines.POINTSIZE) {
  42489. fallbacks.addFallback(0, "POINTSIZE");
  42490. }
  42491. if (defines.LOGARITHMICDEPTH) {
  42492. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42493. }
  42494. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42495. if (defines.SPECULARTERM) {
  42496. fallbacks.addFallback(0, "SPECULARTERM");
  42497. }
  42498. if (defines.DIFFUSEFRESNEL) {
  42499. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42500. }
  42501. if (defines.OPACITYFRESNEL) {
  42502. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42503. }
  42504. if (defines.REFLECTIONFRESNEL) {
  42505. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42506. }
  42507. if (defines.EMISSIVEFRESNEL) {
  42508. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42509. }
  42510. if (defines.FRESNEL) {
  42511. fallbacks.addFallback(4, "FRESNEL");
  42512. }
  42513. //Attributes
  42514. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42515. if (defines.NORMAL) {
  42516. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42517. }
  42518. if (defines.UV1) {
  42519. attribs.push(BABYLON.VertexBuffer.UVKind);
  42520. }
  42521. if (defines.UV2) {
  42522. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42523. }
  42524. if (defines.VERTEXCOLOR) {
  42525. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42526. }
  42527. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42528. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42529. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42530. var shaderName = "default";
  42531. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42532. "vFogInfos", "vFogColor", "pointSize",
  42533. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42534. "mBones",
  42535. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42536. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42537. "vReflectionPosition", "vReflectionSize",
  42538. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42539. ];
  42540. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42541. var uniformBuffers = ["Material", "Scene"];
  42542. if (BABYLON.ImageProcessingConfiguration) {
  42543. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42544. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42545. }
  42546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42547. uniformsNames: uniforms,
  42548. uniformBuffersNames: uniformBuffers,
  42549. samplers: samplers,
  42550. defines: defines,
  42551. maxSimultaneousLights: this._maxSimultaneousLights
  42552. });
  42553. if (this.customShaderNameResolve) {
  42554. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42555. }
  42556. var join = defines.toString();
  42557. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42558. attributes: attribs,
  42559. uniformsNames: uniforms,
  42560. uniformBuffersNames: uniformBuffers,
  42561. samplers: samplers,
  42562. defines: join,
  42563. fallbacks: fallbacks,
  42564. onCompiled: this.onCompiled,
  42565. onError: this.onError,
  42566. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42567. }, engine), defines);
  42568. this.buildUniformLayout();
  42569. }
  42570. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42571. return false;
  42572. }
  42573. defines._renderId = scene.getRenderId();
  42574. this._wasPreviouslyReady = true;
  42575. return true;
  42576. };
  42577. StandardMaterial.prototype.buildUniformLayout = function () {
  42578. // Order is important !
  42579. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42580. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42581. this._uniformBuffer.addUniform("opacityParts", 4);
  42582. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42583. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42584. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42585. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42586. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42587. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42588. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42589. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42590. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42591. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42592. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42593. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42594. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42595. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42596. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42597. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42598. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42599. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42600. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42601. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42602. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42603. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42604. this._uniformBuffer.addUniform("specularMatrix", 16);
  42605. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42606. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42607. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42608. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42609. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42610. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42611. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42612. this._uniformBuffer.addUniform("pointSize", 1);
  42613. this._uniformBuffer.create();
  42614. };
  42615. StandardMaterial.prototype.unbind = function () {
  42616. if (this._activeEffect) {
  42617. var needFlag = false;
  42618. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42619. this._activeEffect.setTexture("reflection2DSampler", null);
  42620. needFlag = true;
  42621. }
  42622. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42623. this._activeEffect.setTexture("refraction2DSampler", null);
  42624. needFlag = true;
  42625. }
  42626. if (needFlag) {
  42627. this._markAllSubMeshesAsTexturesDirty();
  42628. }
  42629. }
  42630. _super.prototype.unbind.call(this);
  42631. };
  42632. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42633. var scene = this.getScene();
  42634. var defines = subMesh._materialDefines;
  42635. if (!defines) {
  42636. return;
  42637. }
  42638. var effect = subMesh.effect;
  42639. if (!effect) {
  42640. return;
  42641. }
  42642. this._activeEffect = effect;
  42643. // Matrices
  42644. this.bindOnlyWorldMatrix(world);
  42645. // Normal Matrix
  42646. if (defines.OBJECTSPACE_NORMALMAP) {
  42647. world.toNormalMatrix(this._normalMatrix);
  42648. this.bindOnlyNormalMatrix(this._normalMatrix);
  42649. }
  42650. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42651. // Bones
  42652. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42653. if (mustRebind) {
  42654. this._uniformBuffer.bindToEffect(effect, "Material");
  42655. this.bindViewProjection(effect);
  42656. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42657. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42658. // Fresnel
  42659. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42660. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42661. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42662. }
  42663. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42664. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42665. }
  42666. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42667. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42668. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42669. }
  42670. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42671. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42672. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42673. }
  42674. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42675. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42676. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42677. }
  42678. }
  42679. // Textures
  42680. if (scene.texturesEnabled) {
  42681. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42682. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42683. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42684. if (this._diffuseTexture.hasAlpha) {
  42685. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42686. }
  42687. }
  42688. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42689. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42690. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42691. }
  42692. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42693. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42694. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42695. }
  42696. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42697. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42698. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42699. if (this._reflectionTexture.boundingBoxSize) {
  42700. var cubeTexture = this._reflectionTexture;
  42701. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42702. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42703. }
  42704. }
  42705. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42706. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42707. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42708. }
  42709. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42710. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42711. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42712. }
  42713. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42714. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42715. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42716. }
  42717. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42718. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42719. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42720. if (scene._mirroredCameraPosition) {
  42721. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42722. }
  42723. else {
  42724. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42725. }
  42726. }
  42727. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42728. var depth = 1.0;
  42729. if (!this._refractionTexture.isCube) {
  42730. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42731. if (this._refractionTexture.depth) {
  42732. depth = this._refractionTexture.depth;
  42733. }
  42734. }
  42735. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42736. }
  42737. }
  42738. // Point size
  42739. if (this.pointsCloud) {
  42740. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42741. }
  42742. if (defines.SPECULARTERM) {
  42743. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42744. }
  42745. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42746. // Diffuse
  42747. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42748. }
  42749. // Textures
  42750. if (scene.texturesEnabled) {
  42751. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42752. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42753. }
  42754. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42755. effect.setTexture("ambientSampler", this._ambientTexture);
  42756. }
  42757. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42758. effect.setTexture("opacitySampler", this._opacityTexture);
  42759. }
  42760. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42761. if (this._reflectionTexture.isCube) {
  42762. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42763. }
  42764. else {
  42765. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42766. }
  42767. }
  42768. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42769. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42770. }
  42771. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42772. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42773. }
  42774. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42775. effect.setTexture("specularSampler", this._specularTexture);
  42776. }
  42777. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42778. effect.setTexture("bumpSampler", this._bumpTexture);
  42779. }
  42780. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42781. var depth = 1.0;
  42782. if (this._refractionTexture.isCube) {
  42783. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42784. }
  42785. else {
  42786. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42787. }
  42788. }
  42789. }
  42790. // Clip plane
  42791. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42792. // Colors
  42793. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42794. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42795. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42796. }
  42797. if (mustRebind || !this.isFrozen) {
  42798. // Lights
  42799. if (scene.lightsEnabled && !this._disableLighting) {
  42800. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42801. }
  42802. // View
  42803. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42804. this.bindView(effect);
  42805. }
  42806. // Fog
  42807. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42808. // Morph targets
  42809. if (defines.NUM_MORPH_INFLUENCERS) {
  42810. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42811. }
  42812. // Log. depth
  42813. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42814. // image processing
  42815. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42816. this._imageProcessingConfiguration.bind(this._activeEffect);
  42817. }
  42818. }
  42819. this._uniformBuffer.update();
  42820. this._afterBind(mesh, this._activeEffect);
  42821. };
  42822. StandardMaterial.prototype.getAnimatables = function () {
  42823. var results = [];
  42824. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42825. results.push(this._diffuseTexture);
  42826. }
  42827. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42828. results.push(this._ambientTexture);
  42829. }
  42830. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42831. results.push(this._opacityTexture);
  42832. }
  42833. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42834. results.push(this._reflectionTexture);
  42835. }
  42836. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42837. results.push(this._emissiveTexture);
  42838. }
  42839. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42840. results.push(this._specularTexture);
  42841. }
  42842. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42843. results.push(this._bumpTexture);
  42844. }
  42845. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42846. results.push(this._lightmapTexture);
  42847. }
  42848. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42849. results.push(this._refractionTexture);
  42850. }
  42851. return results;
  42852. };
  42853. StandardMaterial.prototype.getActiveTextures = function () {
  42854. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42855. if (this._diffuseTexture) {
  42856. activeTextures.push(this._diffuseTexture);
  42857. }
  42858. if (this._ambientTexture) {
  42859. activeTextures.push(this._ambientTexture);
  42860. }
  42861. if (this._opacityTexture) {
  42862. activeTextures.push(this._opacityTexture);
  42863. }
  42864. if (this._reflectionTexture) {
  42865. activeTextures.push(this._reflectionTexture);
  42866. }
  42867. if (this._emissiveTexture) {
  42868. activeTextures.push(this._emissiveTexture);
  42869. }
  42870. if (this._specularTexture) {
  42871. activeTextures.push(this._specularTexture);
  42872. }
  42873. if (this._bumpTexture) {
  42874. activeTextures.push(this._bumpTexture);
  42875. }
  42876. if (this._lightmapTexture) {
  42877. activeTextures.push(this._lightmapTexture);
  42878. }
  42879. if (this._refractionTexture) {
  42880. activeTextures.push(this._refractionTexture);
  42881. }
  42882. return activeTextures;
  42883. };
  42884. StandardMaterial.prototype.hasTexture = function (texture) {
  42885. if (_super.prototype.hasTexture.call(this, texture)) {
  42886. return true;
  42887. }
  42888. if (this._diffuseTexture === texture) {
  42889. return true;
  42890. }
  42891. if (this._ambientTexture === texture) {
  42892. return true;
  42893. }
  42894. if (this._opacityTexture === texture) {
  42895. return true;
  42896. }
  42897. if (this._reflectionTexture === texture) {
  42898. return true;
  42899. }
  42900. if (this._emissiveTexture === texture) {
  42901. return true;
  42902. }
  42903. if (this._specularTexture === texture) {
  42904. return true;
  42905. }
  42906. if (this._bumpTexture === texture) {
  42907. return true;
  42908. }
  42909. if (this._lightmapTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this._refractionTexture === texture) {
  42913. return true;
  42914. }
  42915. return false;
  42916. };
  42917. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42918. if (forceDisposeTextures) {
  42919. if (this._diffuseTexture) {
  42920. this._diffuseTexture.dispose();
  42921. }
  42922. if (this._ambientTexture) {
  42923. this._ambientTexture.dispose();
  42924. }
  42925. if (this._opacityTexture) {
  42926. this._opacityTexture.dispose();
  42927. }
  42928. if (this._reflectionTexture) {
  42929. this._reflectionTexture.dispose();
  42930. }
  42931. if (this._emissiveTexture) {
  42932. this._emissiveTexture.dispose();
  42933. }
  42934. if (this._specularTexture) {
  42935. this._specularTexture.dispose();
  42936. }
  42937. if (this._bumpTexture) {
  42938. this._bumpTexture.dispose();
  42939. }
  42940. if (this._lightmapTexture) {
  42941. this._lightmapTexture.dispose();
  42942. }
  42943. if (this._refractionTexture) {
  42944. this._refractionTexture.dispose();
  42945. }
  42946. }
  42947. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42948. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42949. }
  42950. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42951. };
  42952. StandardMaterial.prototype.clone = function (name) {
  42953. var _this = this;
  42954. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42955. result.name = name;
  42956. result.id = name;
  42957. return result;
  42958. };
  42959. StandardMaterial.prototype.serialize = function () {
  42960. return BABYLON.SerializationHelper.Serialize(this);
  42961. };
  42962. // Statics
  42963. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42964. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42965. };
  42966. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42967. get: function () {
  42968. return StandardMaterial._DiffuseTextureEnabled;
  42969. },
  42970. set: function (value) {
  42971. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42972. return;
  42973. }
  42974. StandardMaterial._DiffuseTextureEnabled = value;
  42975. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42976. },
  42977. enumerable: true,
  42978. configurable: true
  42979. });
  42980. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42981. get: function () {
  42982. return StandardMaterial._AmbientTextureEnabled;
  42983. },
  42984. set: function (value) {
  42985. if (StandardMaterial._AmbientTextureEnabled === value) {
  42986. return;
  42987. }
  42988. StandardMaterial._AmbientTextureEnabled = value;
  42989. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42990. },
  42991. enumerable: true,
  42992. configurable: true
  42993. });
  42994. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42995. get: function () {
  42996. return StandardMaterial._OpacityTextureEnabled;
  42997. },
  42998. set: function (value) {
  42999. if (StandardMaterial._OpacityTextureEnabled === value) {
  43000. return;
  43001. }
  43002. StandardMaterial._OpacityTextureEnabled = value;
  43003. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43004. },
  43005. enumerable: true,
  43006. configurable: true
  43007. });
  43008. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43009. get: function () {
  43010. return StandardMaterial._ReflectionTextureEnabled;
  43011. },
  43012. set: function (value) {
  43013. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43014. return;
  43015. }
  43016. StandardMaterial._ReflectionTextureEnabled = value;
  43017. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43018. },
  43019. enumerable: true,
  43020. configurable: true
  43021. });
  43022. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43023. get: function () {
  43024. return StandardMaterial._EmissiveTextureEnabled;
  43025. },
  43026. set: function (value) {
  43027. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43028. return;
  43029. }
  43030. StandardMaterial._EmissiveTextureEnabled = value;
  43031. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43032. },
  43033. enumerable: true,
  43034. configurable: true
  43035. });
  43036. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43037. get: function () {
  43038. return StandardMaterial._SpecularTextureEnabled;
  43039. },
  43040. set: function (value) {
  43041. if (StandardMaterial._SpecularTextureEnabled === value) {
  43042. return;
  43043. }
  43044. StandardMaterial._SpecularTextureEnabled = value;
  43045. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43046. },
  43047. enumerable: true,
  43048. configurable: true
  43049. });
  43050. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43051. get: function () {
  43052. return StandardMaterial._BumpTextureEnabled;
  43053. },
  43054. set: function (value) {
  43055. if (StandardMaterial._BumpTextureEnabled === value) {
  43056. return;
  43057. }
  43058. StandardMaterial._BumpTextureEnabled = value;
  43059. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43060. },
  43061. enumerable: true,
  43062. configurable: true
  43063. });
  43064. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43065. get: function () {
  43066. return StandardMaterial._LightmapTextureEnabled;
  43067. },
  43068. set: function (value) {
  43069. if (StandardMaterial._LightmapTextureEnabled === value) {
  43070. return;
  43071. }
  43072. StandardMaterial._LightmapTextureEnabled = value;
  43073. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43074. },
  43075. enumerable: true,
  43076. configurable: true
  43077. });
  43078. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43079. get: function () {
  43080. return StandardMaterial._RefractionTextureEnabled;
  43081. },
  43082. set: function (value) {
  43083. if (StandardMaterial._RefractionTextureEnabled === value) {
  43084. return;
  43085. }
  43086. StandardMaterial._RefractionTextureEnabled = value;
  43087. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43093. get: function () {
  43094. return StandardMaterial._ColorGradingTextureEnabled;
  43095. },
  43096. set: function (value) {
  43097. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43098. return;
  43099. }
  43100. StandardMaterial._ColorGradingTextureEnabled = value;
  43101. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43102. },
  43103. enumerable: true,
  43104. configurable: true
  43105. });
  43106. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43107. get: function () {
  43108. return StandardMaterial._FresnelEnabled;
  43109. },
  43110. set: function (value) {
  43111. if (StandardMaterial._FresnelEnabled === value) {
  43112. return;
  43113. }
  43114. StandardMaterial._FresnelEnabled = value;
  43115. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43116. },
  43117. enumerable: true,
  43118. configurable: true
  43119. });
  43120. // Flags used to enable or disable a type of texture for all Standard Materials
  43121. StandardMaterial._DiffuseTextureEnabled = true;
  43122. StandardMaterial._AmbientTextureEnabled = true;
  43123. StandardMaterial._OpacityTextureEnabled = true;
  43124. StandardMaterial._ReflectionTextureEnabled = true;
  43125. StandardMaterial._EmissiveTextureEnabled = true;
  43126. StandardMaterial._SpecularTextureEnabled = true;
  43127. StandardMaterial._BumpTextureEnabled = true;
  43128. StandardMaterial._LightmapTextureEnabled = true;
  43129. StandardMaterial._RefractionTextureEnabled = true;
  43130. StandardMaterial._ColorGradingTextureEnabled = true;
  43131. StandardMaterial._FresnelEnabled = true;
  43132. __decorate([
  43133. BABYLON.serializeAsTexture("diffuseTexture")
  43134. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43137. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43138. __decorate([
  43139. BABYLON.serializeAsTexture("ambientTexture")
  43140. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43144. __decorate([
  43145. BABYLON.serializeAsTexture("opacityTexture")
  43146. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43149. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43150. __decorate([
  43151. BABYLON.serializeAsTexture("reflectionTexture")
  43152. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43155. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43156. __decorate([
  43157. BABYLON.serializeAsTexture("emissiveTexture")
  43158. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43162. __decorate([
  43163. BABYLON.serializeAsTexture("specularTexture")
  43164. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "specularTexture", void 0);
  43168. __decorate([
  43169. BABYLON.serializeAsTexture("bumpTexture")
  43170. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43174. __decorate([
  43175. BABYLON.serializeAsTexture("lightmapTexture")
  43176. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43179. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43180. __decorate([
  43181. BABYLON.serializeAsTexture("refractionTexture")
  43182. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43186. __decorate([
  43187. BABYLON.serializeAsColor3("ambient")
  43188. ], StandardMaterial.prototype, "ambientColor", void 0);
  43189. __decorate([
  43190. BABYLON.serializeAsColor3("diffuse")
  43191. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43192. __decorate([
  43193. BABYLON.serializeAsColor3("specular")
  43194. ], StandardMaterial.prototype, "specularColor", void 0);
  43195. __decorate([
  43196. BABYLON.serializeAsColor3("emissive")
  43197. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43198. __decorate([
  43199. BABYLON.serialize()
  43200. ], StandardMaterial.prototype, "specularPower", void 0);
  43201. __decorate([
  43202. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43203. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43204. __decorate([
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43207. __decorate([
  43208. BABYLON.serialize("useEmissiveAsIllumination")
  43209. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43210. __decorate([
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43213. __decorate([
  43214. BABYLON.serialize("linkEmissiveWithDiffuse")
  43215. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43216. __decorate([
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43219. __decorate([
  43220. BABYLON.serialize("useSpecularOverAlpha")
  43221. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43222. __decorate([
  43223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43224. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43225. __decorate([
  43226. BABYLON.serialize("useReflectionOverAlpha")
  43227. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43228. __decorate([
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43231. __decorate([
  43232. BABYLON.serialize("disableLighting")
  43233. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43234. __decorate([
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43236. ], StandardMaterial.prototype, "disableLighting", void 0);
  43237. __decorate([
  43238. BABYLON.serialize("useObjectSpaceNormalMap")
  43239. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43240. __decorate([
  43241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43242. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43243. __decorate([
  43244. BABYLON.serialize("useParallax")
  43245. ], StandardMaterial.prototype, "_useParallax", void 0);
  43246. __decorate([
  43247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43248. ], StandardMaterial.prototype, "useParallax", void 0);
  43249. __decorate([
  43250. BABYLON.serialize("useParallaxOcclusion")
  43251. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43252. __decorate([
  43253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43254. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43255. __decorate([
  43256. BABYLON.serialize()
  43257. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43258. __decorate([
  43259. BABYLON.serialize("roughness")
  43260. ], StandardMaterial.prototype, "_roughness", void 0);
  43261. __decorate([
  43262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43263. ], StandardMaterial.prototype, "roughness", void 0);
  43264. __decorate([
  43265. BABYLON.serialize()
  43266. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43267. __decorate([
  43268. BABYLON.serialize()
  43269. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43270. __decorate([
  43271. BABYLON.serialize()
  43272. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43273. __decorate([
  43274. BABYLON.serialize("useLightmapAsShadowmap")
  43275. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43276. __decorate([
  43277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43278. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43279. __decorate([
  43280. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43281. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43282. __decorate([
  43283. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43284. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43285. __decorate([
  43286. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43287. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43288. __decorate([
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43290. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43291. __decorate([
  43292. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43293. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43294. __decorate([
  43295. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43296. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43297. __decorate([
  43298. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43299. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43300. __decorate([
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43302. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43303. __decorate([
  43304. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43305. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43306. __decorate([
  43307. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43308. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43309. __decorate([
  43310. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43311. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43312. __decorate([
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43314. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43315. __decorate([
  43316. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43317. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43318. __decorate([
  43319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43320. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43321. __decorate([
  43322. BABYLON.serialize("maxSimultaneousLights")
  43323. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43324. __decorate([
  43325. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43326. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43327. __decorate([
  43328. BABYLON.serialize("invertNormalMapX")
  43329. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43330. __decorate([
  43331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43332. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43333. __decorate([
  43334. BABYLON.serialize("invertNormalMapY")
  43335. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43336. __decorate([
  43337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43338. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43339. __decorate([
  43340. BABYLON.serialize("twoSidedLighting")
  43341. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43342. __decorate([
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43344. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43345. __decorate([
  43346. BABYLON.serialize()
  43347. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43348. return StandardMaterial;
  43349. }(BABYLON.PushMaterial));
  43350. BABYLON.StandardMaterial = StandardMaterial;
  43351. })(BABYLON || (BABYLON = {}));
  43352. //# sourceMappingURL=babylon.standardMaterial.js.map
  43353. var BABYLON;
  43354. (function (BABYLON) {
  43355. /**
  43356. * Manages the defines for the PBR Material.
  43357. * @hiddenChildren
  43358. */
  43359. var PBRMaterialDefines = /** @class */ (function (_super) {
  43360. __extends(PBRMaterialDefines, _super);
  43361. /**
  43362. * Initializes the PBR Material defines.
  43363. */
  43364. function PBRMaterialDefines() {
  43365. var _this = _super.call(this) || this;
  43366. _this.PBR = true;
  43367. _this.MAINUV1 = false;
  43368. _this.MAINUV2 = false;
  43369. _this.UV1 = false;
  43370. _this.UV2 = false;
  43371. _this.ALBEDO = false;
  43372. _this.ALBEDODIRECTUV = 0;
  43373. _this.VERTEXCOLOR = false;
  43374. _this.AMBIENT = false;
  43375. _this.AMBIENTDIRECTUV = 0;
  43376. _this.AMBIENTINGRAYSCALE = false;
  43377. _this.OPACITY = false;
  43378. _this.VERTEXALPHA = false;
  43379. _this.OPACITYDIRECTUV = 0;
  43380. _this.OPACITYRGB = false;
  43381. _this.ALPHATEST = false;
  43382. _this.DEPTHPREPASS = false;
  43383. _this.ALPHABLEND = false;
  43384. _this.ALPHAFROMALBEDO = false;
  43385. _this.ALPHATESTVALUE = "0.5";
  43386. _this.SPECULAROVERALPHA = false;
  43387. _this.RADIANCEOVERALPHA = false;
  43388. _this.ALPHAFRESNEL = false;
  43389. _this.LINEARALPHAFRESNEL = false;
  43390. _this.PREMULTIPLYALPHA = false;
  43391. _this.EMISSIVE = false;
  43392. _this.EMISSIVEDIRECTUV = 0;
  43393. _this.REFLECTIVITY = false;
  43394. _this.REFLECTIVITYDIRECTUV = 0;
  43395. _this.SPECULARTERM = false;
  43396. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43397. _this.MICROSURFACEAUTOMATIC = false;
  43398. _this.LODBASEDMICROSFURACE = false;
  43399. _this.MICROSURFACEMAP = false;
  43400. _this.MICROSURFACEMAPDIRECTUV = 0;
  43401. _this.METALLICWORKFLOW = false;
  43402. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43403. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43404. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43405. _this.AOSTOREINMETALMAPRED = false;
  43406. _this.ENVIRONMENTBRDF = false;
  43407. _this.NORMAL = false;
  43408. _this.TANGENT = false;
  43409. _this.BUMP = false;
  43410. _this.BUMPDIRECTUV = 0;
  43411. _this.OBJECTSPACE_NORMALMAP = false;
  43412. _this.PARALLAX = false;
  43413. _this.PARALLAXOCCLUSION = false;
  43414. _this.NORMALXYSCALE = true;
  43415. _this.LIGHTMAP = false;
  43416. _this.LIGHTMAPDIRECTUV = 0;
  43417. _this.USELIGHTMAPASSHADOWMAP = false;
  43418. _this.GAMMALIGHTMAP = false;
  43419. _this.REFLECTION = false;
  43420. _this.REFLECTIONMAP_3D = false;
  43421. _this.REFLECTIONMAP_SPHERICAL = false;
  43422. _this.REFLECTIONMAP_PLANAR = false;
  43423. _this.REFLECTIONMAP_CUBIC = false;
  43424. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43425. _this.REFLECTIONMAP_PROJECTION = false;
  43426. _this.REFLECTIONMAP_SKYBOX = false;
  43427. _this.REFLECTIONMAP_EXPLICIT = false;
  43428. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43429. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43430. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43431. _this.INVERTCUBICMAP = false;
  43432. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43433. _this.USESPHERICALINVERTEX = false;
  43434. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43435. _this.LODINREFLECTIONALPHA = false;
  43436. _this.GAMMAREFLECTION = false;
  43437. _this.RGBDREFLECTION = false;
  43438. _this.RADIANCEOCCLUSION = false;
  43439. _this.HORIZONOCCLUSION = false;
  43440. _this.REFRACTION = false;
  43441. _this.REFRACTIONMAP_3D = false;
  43442. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43443. _this.LODINREFRACTIONALPHA = false;
  43444. _this.GAMMAREFRACTION = false;
  43445. _this.RGBDREFRACTION = false;
  43446. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43447. _this.INSTANCES = false;
  43448. _this.NUM_BONE_INFLUENCERS = 0;
  43449. _this.BonesPerMesh = 0;
  43450. _this.NONUNIFORMSCALING = false;
  43451. _this.MORPHTARGETS = false;
  43452. _this.MORPHTARGETS_NORMAL = false;
  43453. _this.MORPHTARGETS_TANGENT = false;
  43454. _this.NUM_MORPH_INFLUENCERS = 0;
  43455. _this.IMAGEPROCESSING = false;
  43456. _this.VIGNETTE = false;
  43457. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43458. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43459. _this.TONEMAPPING = false;
  43460. _this.CONTRAST = false;
  43461. _this.COLORCURVES = false;
  43462. _this.COLORGRADING = false;
  43463. _this.COLORGRADING3D = false;
  43464. _this.SAMPLER3DGREENDEPTH = false;
  43465. _this.SAMPLER3DBGRMAP = false;
  43466. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43467. _this.EXPOSURE = false;
  43468. _this.USEPHYSICALLIGHTFALLOFF = false;
  43469. _this.TWOSIDEDLIGHTING = false;
  43470. _this.SHADOWFLOAT = false;
  43471. _this.CLIPPLANE = false;
  43472. _this.POINTSIZE = false;
  43473. _this.FOG = false;
  43474. _this.LOGARITHMICDEPTH = false;
  43475. _this.FORCENORMALFORWARD = false;
  43476. _this.SPECULARAA = false;
  43477. _this.UNLIT = false;
  43478. _this.rebuild();
  43479. return _this;
  43480. }
  43481. /**
  43482. * Resets the PBR Material defines.
  43483. */
  43484. PBRMaterialDefines.prototype.reset = function () {
  43485. _super.prototype.reset.call(this);
  43486. this.ALPHATESTVALUE = "0.5";
  43487. this.PBR = true;
  43488. };
  43489. return PBRMaterialDefines;
  43490. }(BABYLON.MaterialDefines));
  43491. /**
  43492. * The Physically based material base class of BJS.
  43493. *
  43494. * This offers the main features of a standard PBR material.
  43495. * For more information, please refer to the documentation :
  43496. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43497. */
  43498. var PBRBaseMaterial = /** @class */ (function (_super) {
  43499. __extends(PBRBaseMaterial, _super);
  43500. /**
  43501. * Instantiates a new PBRMaterial instance.
  43502. *
  43503. * @param name The material name
  43504. * @param scene The scene the material will be use in.
  43505. */
  43506. function PBRBaseMaterial(name, scene) {
  43507. var _this = _super.call(this, name, scene) || this;
  43508. /**
  43509. * Intensity of the direct lights e.g. the four lights available in your scene.
  43510. * This impacts both the direct diffuse and specular highlights.
  43511. */
  43512. _this._directIntensity = 1.0;
  43513. /**
  43514. * Intensity of the emissive part of the material.
  43515. * This helps controlling the emissive effect without modifying the emissive color.
  43516. */
  43517. _this._emissiveIntensity = 1.0;
  43518. /**
  43519. * Intensity of the environment e.g. how much the environment will light the object
  43520. * either through harmonics for rough material or through the refelction for shiny ones.
  43521. */
  43522. _this._environmentIntensity = 1.0;
  43523. /**
  43524. * This is a special control allowing the reduction of the specular highlights coming from the
  43525. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43526. */
  43527. _this._specularIntensity = 1.0;
  43528. /**
  43529. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43530. */
  43531. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43532. /**
  43533. * Debug Control allowing disabling the bump map on this material.
  43534. */
  43535. _this._disableBumpMap = false;
  43536. /**
  43537. * AKA Occlusion Texture Intensity in other nomenclature.
  43538. */
  43539. _this._ambientTextureStrength = 1.0;
  43540. /**
  43541. * The color of a material in ambient lighting.
  43542. */
  43543. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43544. /**
  43545. * AKA Diffuse Color in other nomenclature.
  43546. */
  43547. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43548. /**
  43549. * AKA Specular Color in other nomenclature.
  43550. */
  43551. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43552. /**
  43553. * The color applied when light is reflected from a material.
  43554. */
  43555. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43556. /**
  43557. * The color applied when light is emitted from a material.
  43558. */
  43559. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43560. /**
  43561. * AKA Glossiness in other nomenclature.
  43562. */
  43563. _this._microSurface = 0.9;
  43564. /**
  43565. * source material index of refraction (IOR)' / 'destination material IOR.
  43566. */
  43567. _this._indexOfRefraction = 0.66;
  43568. /**
  43569. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43570. */
  43571. _this._invertRefractionY = false;
  43572. /**
  43573. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43574. * Materials half opaque for instance using refraction could benefit from this control.
  43575. */
  43576. _this._linkRefractionWithTransparency = false;
  43577. /**
  43578. * Specifies that the material will use the light map as a show map.
  43579. */
  43580. _this._useLightmapAsShadowmap = false;
  43581. /**
  43582. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43583. * makes the reflect vector face the model (under horizon).
  43584. */
  43585. _this._useHorizonOcclusion = true;
  43586. /**
  43587. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43588. * too much the area relying on ambient texture to define their ambient occlusion.
  43589. */
  43590. _this._useRadianceOcclusion = true;
  43591. /**
  43592. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43593. */
  43594. _this._useAlphaFromAlbedoTexture = false;
  43595. /**
  43596. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43597. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43598. */
  43599. _this._useSpecularOverAlpha = true;
  43600. /**
  43601. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43602. */
  43603. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43604. /**
  43605. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43606. */
  43607. _this._useRoughnessFromMetallicTextureAlpha = true;
  43608. /**
  43609. * Specifies if the metallic texture contains the roughness information in its green channel.
  43610. */
  43611. _this._useRoughnessFromMetallicTextureGreen = false;
  43612. /**
  43613. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43614. */
  43615. _this._useMetallnessFromMetallicTextureBlue = false;
  43616. /**
  43617. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43618. */
  43619. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43620. /**
  43621. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43622. */
  43623. _this._useAmbientInGrayScale = false;
  43624. /**
  43625. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43626. * The material will try to infer what glossiness each pixel should be.
  43627. */
  43628. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43629. /**
  43630. * BJS is using an harcoded light falloff based on a manually sets up range.
  43631. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43632. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43633. */
  43634. _this._usePhysicalLightFalloff = true;
  43635. /**
  43636. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43637. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43638. */
  43639. _this._useRadianceOverAlpha = true;
  43640. /**
  43641. * Allows using an object space normal map (instead of tangent space).
  43642. */
  43643. _this._useObjectSpaceNormalMap = false;
  43644. /**
  43645. * Allows using the bump map in parallax mode.
  43646. */
  43647. _this._useParallax = false;
  43648. /**
  43649. * Allows using the bump map in parallax occlusion mode.
  43650. */
  43651. _this._useParallaxOcclusion = false;
  43652. /**
  43653. * Controls the scale bias of the parallax mode.
  43654. */
  43655. _this._parallaxScaleBias = 0.05;
  43656. /**
  43657. * If sets to true, disables all the lights affecting the material.
  43658. */
  43659. _this._disableLighting = false;
  43660. /**
  43661. * Number of Simultaneous lights allowed on the material.
  43662. */
  43663. _this._maxSimultaneousLights = 4;
  43664. /**
  43665. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43666. */
  43667. _this._invertNormalMapX = false;
  43668. /**
  43669. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43670. */
  43671. _this._invertNormalMapY = false;
  43672. /**
  43673. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43674. */
  43675. _this._twoSidedLighting = false;
  43676. /**
  43677. * Defines the alpha limits in alpha test mode.
  43678. */
  43679. _this._alphaCutOff = 0.4;
  43680. /**
  43681. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43682. */
  43683. _this._forceAlphaTest = false;
  43684. /**
  43685. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43686. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43687. */
  43688. _this._useAlphaFresnel = false;
  43689. /**
  43690. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43691. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43692. */
  43693. _this._useLinearAlphaFresnel = false;
  43694. /**
  43695. * The transparency mode of the material.
  43696. */
  43697. _this._transparencyMode = null;
  43698. /**
  43699. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43700. * from cos thetav and roughness:
  43701. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43702. */
  43703. _this._environmentBRDFTexture = null;
  43704. /**
  43705. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43706. */
  43707. _this._forceIrradianceInFragment = false;
  43708. /**
  43709. * Force normal to face away from face.
  43710. */
  43711. _this._forceNormalForward = false;
  43712. /**
  43713. * Enables specular anti aliasing in the PBR shader.
  43714. * It will both interacts on the Geometry for analytical and IBL lighting.
  43715. * It also prefilter the roughness map based on the bump values.
  43716. */
  43717. _this._enableSpecularAntiAliasing = false;
  43718. /**
  43719. * Stores the available render targets.
  43720. */
  43721. _this._renderTargets = new BABYLON.SmartArray(16);
  43722. /**
  43723. * Sets the global ambient color for the material used in lighting calculations.
  43724. */
  43725. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43726. /**
  43727. * If set to true, no lighting calculations will be applied.
  43728. */
  43729. _this._unlit = false;
  43730. // Setup the default processing configuration to the scene.
  43731. _this._attachImageProcessingConfiguration(null);
  43732. _this.getRenderTargetTextures = function () {
  43733. _this._renderTargets.reset();
  43734. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43735. _this._renderTargets.push(_this._reflectionTexture);
  43736. }
  43737. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43738. _this._renderTargets.push(_this._refractionTexture);
  43739. }
  43740. return _this._renderTargets;
  43741. };
  43742. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43743. return _this;
  43744. }
  43745. /**
  43746. * Attaches a new image processing configuration to the PBR Material.
  43747. * @param configuration
  43748. */
  43749. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43750. var _this = this;
  43751. if (configuration === this._imageProcessingConfiguration) {
  43752. return;
  43753. }
  43754. // Detaches observer.
  43755. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43756. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43757. }
  43758. // Pick the scene configuration if needed.
  43759. if (!configuration) {
  43760. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43761. }
  43762. else {
  43763. this._imageProcessingConfiguration = configuration;
  43764. }
  43765. // Attaches observer.
  43766. if (this._imageProcessingConfiguration) {
  43767. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43768. _this._markAllSubMeshesAsImageProcessingDirty();
  43769. });
  43770. }
  43771. };
  43772. /**
  43773. * Gets the name of the material class.
  43774. */
  43775. PBRBaseMaterial.prototype.getClassName = function () {
  43776. return "PBRBaseMaterial";
  43777. };
  43778. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43779. /**
  43780. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43781. */
  43782. get: function () {
  43783. return this._useLogarithmicDepth;
  43784. },
  43785. /**
  43786. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43787. */
  43788. set: function (value) {
  43789. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43790. },
  43791. enumerable: true,
  43792. configurable: true
  43793. });
  43794. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43795. /**
  43796. * Gets the current transparency mode.
  43797. */
  43798. get: function () {
  43799. return this._transparencyMode;
  43800. },
  43801. /**
  43802. * Sets the transparency mode of the material.
  43803. *
  43804. * | Value | Type | Description |
  43805. * | ----- | ----------------------------------- | ----------- |
  43806. * | 0 | OPAQUE | |
  43807. * | 1 | ALPHATEST | |
  43808. * | 2 | ALPHABLEND | |
  43809. * | 3 | ALPHATESTANDBLEND | |
  43810. *
  43811. */
  43812. set: function (value) {
  43813. if (this._transparencyMode === value) {
  43814. return;
  43815. }
  43816. this._transparencyMode = value;
  43817. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43818. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43824. /**
  43825. * Returns true if alpha blending should be disabled.
  43826. */
  43827. get: function () {
  43828. return (this._linkRefractionWithTransparency ||
  43829. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43830. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. /**
  43836. * Specifies whether or not this material should be rendered in alpha blend mode.
  43837. */
  43838. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43839. if (this._disableAlphaBlending) {
  43840. return false;
  43841. }
  43842. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43843. };
  43844. /**
  43845. * Specifies if the mesh will require alpha blending.
  43846. * @param mesh - BJS mesh.
  43847. */
  43848. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43849. if (this._disableAlphaBlending) {
  43850. return false;
  43851. }
  43852. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43853. };
  43854. /**
  43855. * Specifies whether or not this material should be rendered in alpha test mode.
  43856. */
  43857. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43858. if (this._forceAlphaTest) {
  43859. return true;
  43860. }
  43861. if (this._linkRefractionWithTransparency) {
  43862. return false;
  43863. }
  43864. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43865. };
  43866. /**
  43867. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43868. */
  43869. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43870. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43871. };
  43872. /**
  43873. * Gets the texture used for the alpha test.
  43874. */
  43875. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43876. return this._albedoTexture;
  43877. };
  43878. /**
  43879. * Specifies that the submesh is ready to be used.
  43880. * @param mesh - BJS mesh.
  43881. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43882. * @param useInstances - Specifies that instances should be used.
  43883. * @returns - boolean indicating that the submesh is ready or not.
  43884. */
  43885. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43886. if (subMesh.effect && this.isFrozen) {
  43887. if (this._wasPreviouslyReady) {
  43888. return true;
  43889. }
  43890. }
  43891. if (!subMesh._materialDefines) {
  43892. subMesh._materialDefines = new PBRMaterialDefines();
  43893. }
  43894. var defines = subMesh._materialDefines;
  43895. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43896. if (defines._renderId === this.getScene().getRenderId()) {
  43897. return true;
  43898. }
  43899. }
  43900. var scene = this.getScene();
  43901. var engine = scene.getEngine();
  43902. if (defines._areTexturesDirty) {
  43903. if (scene.texturesEnabled) {
  43904. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43905. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43906. return false;
  43907. }
  43908. }
  43909. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43910. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43911. return false;
  43912. }
  43913. }
  43914. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43915. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43916. return false;
  43917. }
  43918. }
  43919. var reflectionTexture = this._getReflectionTexture();
  43920. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43921. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43922. return false;
  43923. }
  43924. }
  43925. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43926. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43927. return false;
  43928. }
  43929. }
  43930. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43931. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43932. return false;
  43933. }
  43934. }
  43935. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43936. if (this._metallicTexture) {
  43937. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43938. return false;
  43939. }
  43940. }
  43941. else if (this._reflectivityTexture) {
  43942. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43943. return false;
  43944. }
  43945. }
  43946. if (this._microSurfaceTexture) {
  43947. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43948. return false;
  43949. }
  43950. }
  43951. }
  43952. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43953. // Bump texture cannot be not blocking.
  43954. if (!this._bumpTexture.isReady()) {
  43955. return false;
  43956. }
  43957. }
  43958. var refractionTexture = this._getRefractionTexture();
  43959. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43960. if (!refractionTexture.isReadyOrNotBlocking()) {
  43961. return false;
  43962. }
  43963. }
  43964. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43965. // This is blocking.
  43966. if (!this._environmentBRDFTexture.isReady()) {
  43967. return false;
  43968. }
  43969. }
  43970. }
  43971. }
  43972. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43973. if (!this._imageProcessingConfiguration.isReady()) {
  43974. return false;
  43975. }
  43976. }
  43977. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43978. mesh.createNormals(true);
  43979. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43980. }
  43981. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43982. if (effect) {
  43983. scene.resetCachedMaterial();
  43984. subMesh.setEffect(effect, defines);
  43985. this.buildUniformLayout();
  43986. }
  43987. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43988. return false;
  43989. }
  43990. defines._renderId = scene.getRenderId();
  43991. this._wasPreviouslyReady = true;
  43992. return true;
  43993. };
  43994. /**
  43995. * Specifies if the material uses metallic roughness workflow.
  43996. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43997. */
  43998. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43999. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44000. return true;
  44001. }
  44002. return false;
  44003. };
  44004. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44005. if (onCompiled === void 0) { onCompiled = null; }
  44006. if (onError === void 0) { onError = null; }
  44007. if (useInstances === void 0) { useInstances = null; }
  44008. if (useClipPlane === void 0) { useClipPlane = null; }
  44009. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44010. if (!defines.isDirty) {
  44011. return null;
  44012. }
  44013. defines.markAsProcessed();
  44014. var scene = this.getScene();
  44015. var engine = scene.getEngine();
  44016. // Fallbacks
  44017. var fallbacks = new BABYLON.EffectFallbacks();
  44018. var fallbackRank = 0;
  44019. if (defines.USESPHERICALINVERTEX) {
  44020. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44021. }
  44022. if (defines.FOG) {
  44023. fallbacks.addFallback(fallbackRank, "FOG");
  44024. }
  44025. if (defines.SPECULARAA) {
  44026. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44027. }
  44028. if (defines.POINTSIZE) {
  44029. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44030. }
  44031. if (defines.LOGARITHMICDEPTH) {
  44032. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44033. }
  44034. if (defines.PARALLAX) {
  44035. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44036. }
  44037. if (defines.PARALLAXOCCLUSION) {
  44038. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44039. }
  44040. if (defines.ENVIRONMENTBRDF) {
  44041. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44042. }
  44043. if (defines.TANGENT) {
  44044. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44045. }
  44046. if (defines.BUMP) {
  44047. fallbacks.addFallback(fallbackRank++, "BUMP");
  44048. }
  44049. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44050. if (defines.SPECULARTERM) {
  44051. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44052. }
  44053. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44054. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44055. }
  44056. if (defines.LIGHTMAP) {
  44057. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44058. }
  44059. if (defines.NORMAL) {
  44060. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44061. }
  44062. if (defines.AMBIENT) {
  44063. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44064. }
  44065. if (defines.EMISSIVE) {
  44066. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44067. }
  44068. if (defines.VERTEXCOLOR) {
  44069. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44070. }
  44071. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44072. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44073. }
  44074. if (defines.MORPHTARGETS) {
  44075. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44076. }
  44077. //Attributes
  44078. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44079. if (defines.NORMAL) {
  44080. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44081. }
  44082. if (defines.TANGENT) {
  44083. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44084. }
  44085. if (defines.UV1) {
  44086. attribs.push(BABYLON.VertexBuffer.UVKind);
  44087. }
  44088. if (defines.UV2) {
  44089. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44090. }
  44091. if (defines.VERTEXCOLOR) {
  44092. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44093. }
  44094. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44095. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44096. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44097. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44098. "vFogInfos", "vFogColor", "pointSize",
  44099. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44100. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44101. "mBones",
  44102. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44103. "vLightingIntensity",
  44104. "logarithmicDepthConstant",
  44105. "vSphericalX", "vSphericalY", "vSphericalZ",
  44106. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44107. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44108. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44109. "vTangentSpaceParams"
  44110. ];
  44111. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44112. "bumpSampler", "lightmapSampler", "opacitySampler",
  44113. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44114. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44115. "microSurfaceSampler", "environmentBrdfSampler"];
  44116. var uniformBuffers = ["Material", "Scene"];
  44117. if (BABYLON.ImageProcessingConfiguration) {
  44118. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44119. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44120. }
  44121. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44122. uniformsNames: uniforms,
  44123. uniformBuffersNames: uniformBuffers,
  44124. samplers: samplers,
  44125. defines: defines,
  44126. maxSimultaneousLights: this._maxSimultaneousLights
  44127. });
  44128. var join = defines.toString();
  44129. return engine.createEffect("pbr", {
  44130. attributes: attribs,
  44131. uniformsNames: uniforms,
  44132. uniformBuffersNames: uniformBuffers,
  44133. samplers: samplers,
  44134. defines: join,
  44135. fallbacks: fallbacks,
  44136. onCompiled: onCompiled,
  44137. onError: onError,
  44138. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44139. }, engine);
  44140. };
  44141. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44142. if (useInstances === void 0) { useInstances = null; }
  44143. if (useClipPlane === void 0) { useClipPlane = null; }
  44144. var scene = this.getScene();
  44145. var engine = scene.getEngine();
  44146. // Lights
  44147. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44148. defines._needNormals = true;
  44149. // Textures
  44150. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44151. if (defines._areTexturesDirty) {
  44152. defines._needUVs = false;
  44153. if (scene.texturesEnabled) {
  44154. if (scene.getEngine().getCaps().textureLOD) {
  44155. defines.LODBASEDMICROSFURACE = true;
  44156. }
  44157. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44158. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44159. }
  44160. else {
  44161. defines.ALBEDO = false;
  44162. }
  44163. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44165. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44166. }
  44167. else {
  44168. defines.AMBIENT = false;
  44169. }
  44170. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44171. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44172. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44173. }
  44174. else {
  44175. defines.OPACITY = false;
  44176. }
  44177. var reflectionTexture = this._getReflectionTexture();
  44178. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44179. defines.REFLECTION = true;
  44180. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44181. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44182. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44183. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44184. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44185. defines.INVERTCUBICMAP = true;
  44186. }
  44187. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44188. switch (reflectionTexture.coordinatesMode) {
  44189. case BABYLON.Texture.EXPLICIT_MODE:
  44190. defines.REFLECTIONMAP_EXPLICIT = true;
  44191. break;
  44192. case BABYLON.Texture.PLANAR_MODE:
  44193. defines.REFLECTIONMAP_PLANAR = true;
  44194. break;
  44195. case BABYLON.Texture.PROJECTION_MODE:
  44196. defines.REFLECTIONMAP_PROJECTION = true;
  44197. break;
  44198. case BABYLON.Texture.SKYBOX_MODE:
  44199. defines.REFLECTIONMAP_SKYBOX = true;
  44200. break;
  44201. case BABYLON.Texture.SPHERICAL_MODE:
  44202. defines.REFLECTIONMAP_SPHERICAL = true;
  44203. break;
  44204. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44205. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44206. break;
  44207. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44208. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44209. break;
  44210. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44211. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44212. break;
  44213. case BABYLON.Texture.CUBIC_MODE:
  44214. case BABYLON.Texture.INVCUBIC_MODE:
  44215. default:
  44216. defines.REFLECTIONMAP_CUBIC = true;
  44217. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44218. break;
  44219. }
  44220. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44221. if (reflectionTexture.sphericalPolynomial) {
  44222. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44223. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44224. defines.USESPHERICALINVERTEX = false;
  44225. }
  44226. else {
  44227. defines.USESPHERICALINVERTEX = true;
  44228. }
  44229. }
  44230. }
  44231. }
  44232. else {
  44233. defines.REFLECTION = false;
  44234. defines.REFLECTIONMAP_3D = false;
  44235. defines.REFLECTIONMAP_SPHERICAL = false;
  44236. defines.REFLECTIONMAP_PLANAR = false;
  44237. defines.REFLECTIONMAP_CUBIC = false;
  44238. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44239. defines.REFLECTIONMAP_PROJECTION = false;
  44240. defines.REFLECTIONMAP_SKYBOX = false;
  44241. defines.REFLECTIONMAP_EXPLICIT = false;
  44242. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44243. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44244. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44245. defines.INVERTCUBICMAP = false;
  44246. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44247. defines.USESPHERICALINVERTEX = false;
  44248. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44249. defines.LODINREFLECTIONALPHA = false;
  44250. defines.GAMMAREFLECTION = false;
  44251. defines.RGBDREFLECTION = false;
  44252. }
  44253. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44254. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44255. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44256. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44257. }
  44258. else {
  44259. defines.LIGHTMAP = false;
  44260. }
  44261. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44263. }
  44264. else {
  44265. defines.EMISSIVE = false;
  44266. }
  44267. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44268. if (this._metallicTexture) {
  44269. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44270. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44271. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44272. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44273. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44274. }
  44275. else if (this._reflectivityTexture) {
  44276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44277. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44278. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44279. }
  44280. else {
  44281. defines.REFLECTIVITY = false;
  44282. }
  44283. if (this._microSurfaceTexture) {
  44284. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44285. }
  44286. else {
  44287. defines.MICROSURFACEMAP = false;
  44288. }
  44289. }
  44290. else {
  44291. defines.REFLECTIVITY = false;
  44292. defines.MICROSURFACEMAP = false;
  44293. }
  44294. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44295. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44296. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44297. defines.PARALLAX = true;
  44298. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44299. }
  44300. else {
  44301. defines.PARALLAX = false;
  44302. }
  44303. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44304. }
  44305. else {
  44306. defines.BUMP = false;
  44307. }
  44308. var refractionTexture = this._getRefractionTexture();
  44309. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44310. defines.REFRACTION = true;
  44311. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44312. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44313. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44314. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44315. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44316. if (this._linkRefractionWithTransparency) {
  44317. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44318. }
  44319. }
  44320. else {
  44321. defines.REFRACTION = false;
  44322. }
  44323. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44324. defines.ENVIRONMENTBRDF = true;
  44325. }
  44326. else {
  44327. defines.ENVIRONMENTBRDF = false;
  44328. }
  44329. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44330. defines.ALPHAFROMALBEDO = true;
  44331. }
  44332. else {
  44333. defines.ALPHAFROMALBEDO = false;
  44334. }
  44335. }
  44336. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44337. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44338. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44339. if (!this.backFaceCulling && this._twoSidedLighting) {
  44340. defines.TWOSIDEDLIGHTING = true;
  44341. }
  44342. else {
  44343. defines.TWOSIDEDLIGHTING = false;
  44344. }
  44345. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44346. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44347. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44348. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44349. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44350. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44351. }
  44352. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44353. this._imageProcessingConfiguration.prepareDefines(defines);
  44354. }
  44355. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44356. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44357. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44358. // Misc.
  44359. if (defines._areMiscDirty) {
  44360. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44361. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44362. }
  44363. // Values that need to be evaluated on every frame
  44364. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44365. // Attribs
  44366. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44367. };
  44368. /**
  44369. * Force shader compilation
  44370. */
  44371. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44372. var _this = this;
  44373. var localOptions = __assign({ clipPlane: false }, options);
  44374. var defines = new PBRMaterialDefines();
  44375. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44376. if (effect.isReady()) {
  44377. if (onCompiled) {
  44378. onCompiled(this);
  44379. }
  44380. }
  44381. else {
  44382. effect.onCompileObservable.add(function () {
  44383. if (onCompiled) {
  44384. onCompiled(_this);
  44385. }
  44386. });
  44387. }
  44388. };
  44389. /**
  44390. * Initializes the uniform buffer layout for the shader.
  44391. */
  44392. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44393. // Order is important !
  44394. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44395. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44396. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44397. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44398. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44399. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44400. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44401. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44402. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44403. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44404. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44405. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44406. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44407. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44408. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44409. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44410. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44411. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44412. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44413. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44414. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44415. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44416. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44417. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44418. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44419. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44420. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44421. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44422. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44423. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44424. this._uniformBuffer.addUniform("pointSize", 1);
  44425. this._uniformBuffer.create();
  44426. };
  44427. /**
  44428. * Unbinds the textures.
  44429. */
  44430. PBRBaseMaterial.prototype.unbind = function () {
  44431. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44432. this._uniformBuffer.setTexture("reflectionSampler", null);
  44433. }
  44434. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44435. this._uniformBuffer.setTexture("refractionSampler", null);
  44436. }
  44437. _super.prototype.unbind.call(this);
  44438. };
  44439. /**
  44440. * Binds the submesh data.
  44441. * @param world - The world matrix.
  44442. * @param mesh - The BJS mesh.
  44443. * @param subMesh - A submesh of the BJS mesh.
  44444. */
  44445. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44446. var scene = this.getScene();
  44447. var defines = subMesh._materialDefines;
  44448. if (!defines) {
  44449. return;
  44450. }
  44451. var effect = subMesh.effect;
  44452. if (!effect) {
  44453. return;
  44454. }
  44455. this._activeEffect = effect;
  44456. // Matrices
  44457. this.bindOnlyWorldMatrix(world);
  44458. // Normal Matrix
  44459. if (defines.OBJECTSPACE_NORMALMAP) {
  44460. world.toNormalMatrix(this._normalMatrix);
  44461. this.bindOnlyNormalMatrix(this._normalMatrix);
  44462. }
  44463. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44464. // Bones
  44465. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44466. var reflectionTexture = null;
  44467. if (mustRebind) {
  44468. this._uniformBuffer.bindToEffect(effect, "Material");
  44469. this.bindViewProjection(effect);
  44470. reflectionTexture = this._getReflectionTexture();
  44471. var refractionTexture = this._getRefractionTexture();
  44472. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44473. // Texture uniforms
  44474. if (scene.texturesEnabled) {
  44475. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44476. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44477. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44478. }
  44479. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44480. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44481. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44482. }
  44483. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44484. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44485. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44486. }
  44487. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44488. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44489. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44490. if (reflectionTexture.boundingBoxSize) {
  44491. var cubeTexture = reflectionTexture;
  44492. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44493. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44494. }
  44495. var polynomials = reflectionTexture.sphericalPolynomial;
  44496. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44497. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44498. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44499. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44500. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44501. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44502. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44503. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44504. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44505. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44506. }
  44507. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44508. }
  44509. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44510. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44511. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44512. }
  44513. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44514. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44515. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44516. }
  44517. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44518. if (this._metallicTexture) {
  44519. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44520. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44521. }
  44522. else if (this._reflectivityTexture) {
  44523. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44524. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44525. }
  44526. if (this._microSurfaceTexture) {
  44527. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44528. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44529. }
  44530. }
  44531. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44532. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44533. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44534. if (scene._mirroredCameraPosition) {
  44535. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44536. }
  44537. else {
  44538. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44539. }
  44540. }
  44541. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44542. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44543. var depth = 1.0;
  44544. if (!refractionTexture.isCube) {
  44545. if (refractionTexture.depth) {
  44546. depth = refractionTexture.depth;
  44547. }
  44548. }
  44549. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44550. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44551. }
  44552. }
  44553. // Point size
  44554. if (this.pointsCloud) {
  44555. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44556. }
  44557. // Colors
  44558. if (defines.METALLICWORKFLOW) {
  44559. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44560. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44561. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44562. }
  44563. else {
  44564. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44565. }
  44566. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44567. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44568. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44569. // Misc
  44570. this._lightingInfos.x = this._directIntensity;
  44571. this._lightingInfos.y = this._emissiveIntensity;
  44572. this._lightingInfos.z = this._environmentIntensity;
  44573. this._lightingInfos.w = this._specularIntensity;
  44574. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44575. }
  44576. // Textures
  44577. if (scene.texturesEnabled) {
  44578. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44579. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44580. }
  44581. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44582. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44583. }
  44584. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44585. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44586. }
  44587. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44588. if (defines.LODBASEDMICROSFURACE) {
  44589. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44590. }
  44591. else {
  44592. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44593. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44594. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44595. }
  44596. }
  44597. if (defines.ENVIRONMENTBRDF) {
  44598. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44599. }
  44600. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44601. if (defines.LODBASEDMICROSFURACE) {
  44602. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44603. }
  44604. else {
  44605. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44606. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44607. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44608. }
  44609. }
  44610. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44611. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44612. }
  44613. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44614. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44615. }
  44616. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44617. if (this._metallicTexture) {
  44618. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44619. }
  44620. else if (this._reflectivityTexture) {
  44621. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44622. }
  44623. if (this._microSurfaceTexture) {
  44624. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44625. }
  44626. }
  44627. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44628. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44629. }
  44630. }
  44631. // Clip plane
  44632. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44633. // Colors
  44634. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44635. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44636. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44637. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44638. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44639. }
  44640. if (mustRebind || !this.isFrozen) {
  44641. // Lights
  44642. if (scene.lightsEnabled && !this._disableLighting) {
  44643. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44644. }
  44645. // View
  44646. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44647. this.bindView(effect);
  44648. }
  44649. // Fog
  44650. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44651. // Morph targets
  44652. if (defines.NUM_MORPH_INFLUENCERS) {
  44653. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44654. }
  44655. // image processing
  44656. this._imageProcessingConfiguration.bind(this._activeEffect);
  44657. // Log. depth
  44658. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44659. }
  44660. this._uniformBuffer.update();
  44661. this._afterBind(mesh, this._activeEffect);
  44662. };
  44663. /**
  44664. * Returns the animatable textures.
  44665. * @returns - Array of animatable textures.
  44666. */
  44667. PBRBaseMaterial.prototype.getAnimatables = function () {
  44668. var results = [];
  44669. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44670. results.push(this._albedoTexture);
  44671. }
  44672. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44673. results.push(this._ambientTexture);
  44674. }
  44675. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44676. results.push(this._opacityTexture);
  44677. }
  44678. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44679. results.push(this._reflectionTexture);
  44680. }
  44681. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44682. results.push(this._emissiveTexture);
  44683. }
  44684. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44685. results.push(this._metallicTexture);
  44686. }
  44687. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44688. results.push(this._reflectivityTexture);
  44689. }
  44690. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44691. results.push(this._bumpTexture);
  44692. }
  44693. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44694. results.push(this._lightmapTexture);
  44695. }
  44696. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44697. results.push(this._refractionTexture);
  44698. }
  44699. return results;
  44700. };
  44701. /**
  44702. * Returns the texture used for reflections.
  44703. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44704. */
  44705. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44706. if (this._reflectionTexture) {
  44707. return this._reflectionTexture;
  44708. }
  44709. return this.getScene().environmentTexture;
  44710. };
  44711. /**
  44712. * Returns the texture used for refraction or null if none is used.
  44713. * @returns - Refection texture if present. If no refraction texture and refraction
  44714. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44715. */
  44716. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44717. if (this._refractionTexture) {
  44718. return this._refractionTexture;
  44719. }
  44720. if (this._linkRefractionWithTransparency) {
  44721. return this.getScene().environmentTexture;
  44722. }
  44723. return null;
  44724. };
  44725. /**
  44726. * Disposes the resources of the material.
  44727. * @param forceDisposeEffect - Forces the disposal of effects.
  44728. * @param forceDisposeTextures - Forces the disposal of all textures.
  44729. */
  44730. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44731. if (forceDisposeTextures) {
  44732. if (this._albedoTexture) {
  44733. this._albedoTexture.dispose();
  44734. }
  44735. if (this._ambientTexture) {
  44736. this._ambientTexture.dispose();
  44737. }
  44738. if (this._opacityTexture) {
  44739. this._opacityTexture.dispose();
  44740. }
  44741. if (this._reflectionTexture) {
  44742. this._reflectionTexture.dispose();
  44743. }
  44744. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44745. this._environmentBRDFTexture.dispose();
  44746. }
  44747. if (this._emissiveTexture) {
  44748. this._emissiveTexture.dispose();
  44749. }
  44750. if (this._metallicTexture) {
  44751. this._metallicTexture.dispose();
  44752. }
  44753. if (this._reflectivityTexture) {
  44754. this._reflectivityTexture.dispose();
  44755. }
  44756. if (this._bumpTexture) {
  44757. this._bumpTexture.dispose();
  44758. }
  44759. if (this._lightmapTexture) {
  44760. this._lightmapTexture.dispose();
  44761. }
  44762. if (this._refractionTexture) {
  44763. this._refractionTexture.dispose();
  44764. }
  44765. }
  44766. this._renderTargets.dispose();
  44767. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44768. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44769. }
  44770. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44771. };
  44772. /**
  44773. * Stores the reflectivity values based on metallic roughness workflow.
  44774. */
  44775. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44776. __decorate([
  44777. BABYLON.serializeAsImageProcessingConfiguration()
  44778. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44779. __decorate([
  44780. BABYLON.serialize()
  44781. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44782. __decorate([
  44783. BABYLON.serialize()
  44784. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44785. return PBRBaseMaterial;
  44786. }(BABYLON.PushMaterial));
  44787. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44788. })(BABYLON || (BABYLON = {}));
  44789. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44790. var BABYLON;
  44791. (function (BABYLON) {
  44792. /**
  44793. * The Physically based simple base material of BJS.
  44794. *
  44795. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44796. * It is used as the base class for both the specGloss and metalRough conventions.
  44797. */
  44798. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44799. __extends(PBRBaseSimpleMaterial, _super);
  44800. /**
  44801. * Instantiates a new PBRMaterial instance.
  44802. *
  44803. * @param name The material name
  44804. * @param scene The scene the material will be use in.
  44805. */
  44806. function PBRBaseSimpleMaterial(name, scene) {
  44807. var _this = _super.call(this, name, scene) || this;
  44808. /**
  44809. * Number of Simultaneous lights allowed on the material.
  44810. */
  44811. _this.maxSimultaneousLights = 4;
  44812. /**
  44813. * If sets to true, disables all the lights affecting the material.
  44814. */
  44815. _this.disableLighting = false;
  44816. /**
  44817. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44818. */
  44819. _this.invertNormalMapX = false;
  44820. /**
  44821. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44822. */
  44823. _this.invertNormalMapY = false;
  44824. /**
  44825. * Emissivie color used to self-illuminate the model.
  44826. */
  44827. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44828. /**
  44829. * Occlusion Channel Strenght.
  44830. */
  44831. _this.occlusionStrength = 1.0;
  44832. _this.useLightmapAsShadowmap = false;
  44833. _this._useAlphaFromAlbedoTexture = true;
  44834. _this._useAmbientInGrayScale = true;
  44835. return _this;
  44836. }
  44837. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44838. /**
  44839. * Gets the current double sided mode.
  44840. */
  44841. get: function () {
  44842. return this._twoSidedLighting;
  44843. },
  44844. /**
  44845. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44846. */
  44847. set: function (value) {
  44848. if (this._twoSidedLighting === value) {
  44849. return;
  44850. }
  44851. this._twoSidedLighting = value;
  44852. this.backFaceCulling = !value;
  44853. this._markAllSubMeshesAsTexturesDirty();
  44854. },
  44855. enumerable: true,
  44856. configurable: true
  44857. });
  44858. /**
  44859. * Return the active textures of the material.
  44860. */
  44861. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44862. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44863. if (this.environmentTexture) {
  44864. activeTextures.push(this.environmentTexture);
  44865. }
  44866. if (this.normalTexture) {
  44867. activeTextures.push(this.normalTexture);
  44868. }
  44869. if (this.emissiveTexture) {
  44870. activeTextures.push(this.emissiveTexture);
  44871. }
  44872. if (this.occlusionTexture) {
  44873. activeTextures.push(this.occlusionTexture);
  44874. }
  44875. if (this.lightmapTexture) {
  44876. activeTextures.push(this.lightmapTexture);
  44877. }
  44878. return activeTextures;
  44879. };
  44880. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44881. if (_super.prototype.hasTexture.call(this, texture)) {
  44882. return true;
  44883. }
  44884. if (this.lightmapTexture === texture) {
  44885. return true;
  44886. }
  44887. return false;
  44888. };
  44889. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44890. return "PBRBaseSimpleMaterial";
  44891. };
  44892. __decorate([
  44893. BABYLON.serialize(),
  44894. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44895. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44896. __decorate([
  44897. BABYLON.serialize(),
  44898. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44899. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44900. __decorate([
  44901. BABYLON.serializeAsTexture(),
  44902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44903. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44904. __decorate([
  44905. BABYLON.serialize(),
  44906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44907. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44908. __decorate([
  44909. BABYLON.serialize(),
  44910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44911. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44912. __decorate([
  44913. BABYLON.serializeAsTexture(),
  44914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44915. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44916. __decorate([
  44917. BABYLON.serializeAsColor3("emissive"),
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44919. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44920. __decorate([
  44921. BABYLON.serializeAsTexture(),
  44922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44923. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44924. __decorate([
  44925. BABYLON.serialize(),
  44926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44927. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44928. __decorate([
  44929. BABYLON.serializeAsTexture(),
  44930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44931. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44932. __decorate([
  44933. BABYLON.serialize(),
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44935. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44936. __decorate([
  44937. BABYLON.serialize()
  44938. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44939. __decorate([
  44940. BABYLON.serializeAsTexture(),
  44941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44942. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44943. __decorate([
  44944. BABYLON.serialize(),
  44945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44946. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44947. return PBRBaseSimpleMaterial;
  44948. }(BABYLON.PBRBaseMaterial));
  44949. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44950. })(BABYLON || (BABYLON = {}));
  44951. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44952. var BABYLON;
  44953. (function (BABYLON) {
  44954. /**
  44955. * The Physically based material of BJS.
  44956. *
  44957. * This offers the main features of a standard PBR material.
  44958. * For more information, please refer to the documentation :
  44959. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44960. */
  44961. var PBRMaterial = /** @class */ (function (_super) {
  44962. __extends(PBRMaterial, _super);
  44963. /**
  44964. * Instantiates a new PBRMaterial instance.
  44965. *
  44966. * @param name The material name
  44967. * @param scene The scene the material will be use in.
  44968. */
  44969. function PBRMaterial(name, scene) {
  44970. var _this = _super.call(this, name, scene) || this;
  44971. /**
  44972. * Intensity of the direct lights e.g. the four lights available in your scene.
  44973. * This impacts both the direct diffuse and specular highlights.
  44974. */
  44975. _this.directIntensity = 1.0;
  44976. /**
  44977. * Intensity of the emissive part of the material.
  44978. * This helps controlling the emissive effect without modifying the emissive color.
  44979. */
  44980. _this.emissiveIntensity = 1.0;
  44981. /**
  44982. * Intensity of the environment e.g. how much the environment will light the object
  44983. * either through harmonics for rough material or through the refelction for shiny ones.
  44984. */
  44985. _this.environmentIntensity = 1.0;
  44986. /**
  44987. * This is a special control allowing the reduction of the specular highlights coming from the
  44988. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44989. */
  44990. _this.specularIntensity = 1.0;
  44991. /**
  44992. * Debug Control allowing disabling the bump map on this material.
  44993. */
  44994. _this.disableBumpMap = false;
  44995. /**
  44996. * AKA Occlusion Texture Intensity in other nomenclature.
  44997. */
  44998. _this.ambientTextureStrength = 1.0;
  44999. /**
  45000. * The color of a material in ambient lighting.
  45001. */
  45002. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45003. /**
  45004. * AKA Diffuse Color in other nomenclature.
  45005. */
  45006. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45007. /**
  45008. * AKA Specular Color in other nomenclature.
  45009. */
  45010. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45011. /**
  45012. * The color reflected from the material.
  45013. */
  45014. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45015. /**
  45016. * The color emitted from the material.
  45017. */
  45018. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45019. /**
  45020. * AKA Glossiness in other nomenclature.
  45021. */
  45022. _this.microSurface = 1.0;
  45023. /**
  45024. * source material index of refraction (IOR)' / 'destination material IOR.
  45025. */
  45026. _this.indexOfRefraction = 0.66;
  45027. /**
  45028. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45029. */
  45030. _this.invertRefractionY = false;
  45031. /**
  45032. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45033. * Materials half opaque for instance using refraction could benefit from this control.
  45034. */
  45035. _this.linkRefractionWithTransparency = false;
  45036. _this.useLightmapAsShadowmap = false;
  45037. /**
  45038. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45039. */
  45040. _this.useAlphaFromAlbedoTexture = false;
  45041. /**
  45042. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45043. */
  45044. _this.forceAlphaTest = false;
  45045. /**
  45046. * Defines the alpha limits in alpha test mode.
  45047. */
  45048. _this.alphaCutOff = 0.4;
  45049. /**
  45050. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45051. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45052. */
  45053. _this.useSpecularOverAlpha = true;
  45054. /**
  45055. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45056. */
  45057. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45058. /**
  45059. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45060. */
  45061. _this.useRoughnessFromMetallicTextureAlpha = true;
  45062. /**
  45063. * Specifies if the metallic texture contains the roughness information in its green channel.
  45064. */
  45065. _this.useRoughnessFromMetallicTextureGreen = false;
  45066. /**
  45067. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45068. */
  45069. _this.useMetallnessFromMetallicTextureBlue = false;
  45070. /**
  45071. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45072. */
  45073. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45074. /**
  45075. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45076. */
  45077. _this.useAmbientInGrayScale = false;
  45078. /**
  45079. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45080. * The material will try to infer what glossiness each pixel should be.
  45081. */
  45082. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45083. /**
  45084. * BJS is using an harcoded light falloff based on a manually sets up range.
  45085. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45086. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45087. */
  45088. _this.usePhysicalLightFalloff = true;
  45089. /**
  45090. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45091. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45092. */
  45093. _this.useRadianceOverAlpha = true;
  45094. /**
  45095. * Allows using an object space normal map (instead of tangent space).
  45096. */
  45097. _this.useObjectSpaceNormalMap = false;
  45098. /**
  45099. * Allows using the bump map in parallax mode.
  45100. */
  45101. _this.useParallax = false;
  45102. /**
  45103. * Allows using the bump map in parallax occlusion mode.
  45104. */
  45105. _this.useParallaxOcclusion = false;
  45106. /**
  45107. * Controls the scale bias of the parallax mode.
  45108. */
  45109. _this.parallaxScaleBias = 0.05;
  45110. /**
  45111. * If sets to true, disables all the lights affecting the material.
  45112. */
  45113. _this.disableLighting = false;
  45114. /**
  45115. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45116. */
  45117. _this.forceIrradianceInFragment = false;
  45118. /**
  45119. * Number of Simultaneous lights allowed on the material.
  45120. */
  45121. _this.maxSimultaneousLights = 4;
  45122. /**
  45123. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45124. */
  45125. _this.invertNormalMapX = false;
  45126. /**
  45127. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45128. */
  45129. _this.invertNormalMapY = false;
  45130. /**
  45131. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45132. */
  45133. _this.twoSidedLighting = false;
  45134. /**
  45135. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45136. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45137. */
  45138. _this.useAlphaFresnel = false;
  45139. /**
  45140. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45141. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45142. */
  45143. _this.useLinearAlphaFresnel = false;
  45144. /**
  45145. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45146. * And/Or occlude the blended part.
  45147. */
  45148. _this.environmentBRDFTexture = null;
  45149. /**
  45150. * Force normal to face away from face.
  45151. */
  45152. _this.forceNormalForward = false;
  45153. /**
  45154. * Enables specular anti aliasing in the PBR shader.
  45155. * It will both interacts on the Geometry for analytical and IBL lighting.
  45156. * It also prefilter the roughness map based on the bump values.
  45157. */
  45158. _this.enableSpecularAntiAliasing = false;
  45159. /**
  45160. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45161. * makes the reflect vector face the model (under horizon).
  45162. */
  45163. _this.useHorizonOcclusion = true;
  45164. /**
  45165. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45166. * too much the area relying on ambient texture to define their ambient occlusion.
  45167. */
  45168. _this.useRadianceOcclusion = true;
  45169. /**
  45170. * If set to true, no lighting calculations will be applied.
  45171. */
  45172. _this.unlit = false;
  45173. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45174. return _this;
  45175. }
  45176. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45177. /**
  45178. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45179. */
  45180. get: function () {
  45181. return this._PBRMATERIAL_OPAQUE;
  45182. },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45187. /**
  45188. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45189. */
  45190. get: function () {
  45191. return this._PBRMATERIAL_ALPHATEST;
  45192. },
  45193. enumerable: true,
  45194. configurable: true
  45195. });
  45196. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45197. /**
  45198. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45199. */
  45200. get: function () {
  45201. return this._PBRMATERIAL_ALPHABLEND;
  45202. },
  45203. enumerable: true,
  45204. configurable: true
  45205. });
  45206. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45207. /**
  45208. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45209. * They are also discarded below the alpha cutoff threshold to improve performances.
  45210. */
  45211. get: function () {
  45212. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45213. },
  45214. enumerable: true,
  45215. configurable: true
  45216. });
  45217. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45218. /**
  45219. * Gets the image processing configuration used either in this material.
  45220. */
  45221. get: function () {
  45222. return this._imageProcessingConfiguration;
  45223. },
  45224. /**
  45225. * Sets the Default image processing configuration used either in the this material.
  45226. *
  45227. * If sets to null, the scene one is in use.
  45228. */
  45229. set: function (value) {
  45230. this._attachImageProcessingConfiguration(value);
  45231. // Ensure the effect will be rebuilt.
  45232. this._markAllSubMeshesAsTexturesDirty();
  45233. },
  45234. enumerable: true,
  45235. configurable: true
  45236. });
  45237. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45238. /**
  45239. * Gets wether the color curves effect is enabled.
  45240. */
  45241. get: function () {
  45242. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45243. },
  45244. /**
  45245. * Sets wether the color curves effect is enabled.
  45246. */
  45247. set: function (value) {
  45248. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45249. },
  45250. enumerable: true,
  45251. configurable: true
  45252. });
  45253. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45254. /**
  45255. * Gets wether the color grading effect is enabled.
  45256. */
  45257. get: function () {
  45258. return this.imageProcessingConfiguration.colorGradingEnabled;
  45259. },
  45260. /**
  45261. * Gets wether the color grading effect is enabled.
  45262. */
  45263. set: function (value) {
  45264. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45270. /**
  45271. * Gets wether tonemapping is enabled or not.
  45272. */
  45273. get: function () {
  45274. return this._imageProcessingConfiguration.toneMappingEnabled;
  45275. },
  45276. /**
  45277. * Sets wether tonemapping is enabled or not
  45278. */
  45279. set: function (value) {
  45280. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. ;
  45286. ;
  45287. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45288. /**
  45289. * The camera exposure used on this material.
  45290. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45291. * This corresponds to a photographic exposure.
  45292. */
  45293. get: function () {
  45294. return this._imageProcessingConfiguration.exposure;
  45295. },
  45296. /**
  45297. * The camera exposure used on this material.
  45298. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45299. * This corresponds to a photographic exposure.
  45300. */
  45301. set: function (value) {
  45302. this._imageProcessingConfiguration.exposure = value;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. ;
  45308. ;
  45309. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45310. /**
  45311. * Gets The camera contrast used on this material.
  45312. */
  45313. get: function () {
  45314. return this._imageProcessingConfiguration.contrast;
  45315. },
  45316. /**
  45317. * Sets The camera contrast used on this material.
  45318. */
  45319. set: function (value) {
  45320. this._imageProcessingConfiguration.contrast = value;
  45321. },
  45322. enumerable: true,
  45323. configurable: true
  45324. });
  45325. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45326. /**
  45327. * Gets the Color Grading 2D Lookup Texture.
  45328. */
  45329. get: function () {
  45330. return this._imageProcessingConfiguration.colorGradingTexture;
  45331. },
  45332. /**
  45333. * Sets the Color Grading 2D Lookup Texture.
  45334. */
  45335. set: function (value) {
  45336. this._imageProcessingConfiguration.colorGradingTexture = value;
  45337. },
  45338. enumerable: true,
  45339. configurable: true
  45340. });
  45341. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45342. /**
  45343. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45344. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45345. * 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;
  45346. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45347. */
  45348. get: function () {
  45349. return this._imageProcessingConfiguration.colorCurves;
  45350. },
  45351. /**
  45352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45354. * 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;
  45355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45356. */
  45357. set: function (value) {
  45358. this._imageProcessingConfiguration.colorCurves = value;
  45359. },
  45360. enumerable: true,
  45361. configurable: true
  45362. });
  45363. /**
  45364. * Returns the name of this material class.
  45365. */
  45366. PBRMaterial.prototype.getClassName = function () {
  45367. return "PBRMaterial";
  45368. };
  45369. /**
  45370. * Returns an array of the actively used textures.
  45371. * @returns - Array of BaseTextures
  45372. */
  45373. PBRMaterial.prototype.getActiveTextures = function () {
  45374. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45375. if (this._albedoTexture) {
  45376. activeTextures.push(this._albedoTexture);
  45377. }
  45378. if (this._ambientTexture) {
  45379. activeTextures.push(this._ambientTexture);
  45380. }
  45381. if (this._opacityTexture) {
  45382. activeTextures.push(this._opacityTexture);
  45383. }
  45384. if (this._reflectionTexture) {
  45385. activeTextures.push(this._reflectionTexture);
  45386. }
  45387. if (this._emissiveTexture) {
  45388. activeTextures.push(this._emissiveTexture);
  45389. }
  45390. if (this._reflectivityTexture) {
  45391. activeTextures.push(this._reflectivityTexture);
  45392. }
  45393. if (this._metallicTexture) {
  45394. activeTextures.push(this._metallicTexture);
  45395. }
  45396. if (this._microSurfaceTexture) {
  45397. activeTextures.push(this._microSurfaceTexture);
  45398. }
  45399. if (this._bumpTexture) {
  45400. activeTextures.push(this._bumpTexture);
  45401. }
  45402. if (this._lightmapTexture) {
  45403. activeTextures.push(this._lightmapTexture);
  45404. }
  45405. if (this._refractionTexture) {
  45406. activeTextures.push(this._refractionTexture);
  45407. }
  45408. return activeTextures;
  45409. };
  45410. /**
  45411. * Checks to see if a texture is used in the material.
  45412. * @param texture - Base texture to use.
  45413. * @returns - Boolean specifying if a texture is used in the material.
  45414. */
  45415. PBRMaterial.prototype.hasTexture = function (texture) {
  45416. if (_super.prototype.hasTexture.call(this, texture)) {
  45417. return true;
  45418. }
  45419. if (this._albedoTexture === texture) {
  45420. return true;
  45421. }
  45422. if (this._ambientTexture === texture) {
  45423. return true;
  45424. }
  45425. if (this._opacityTexture === texture) {
  45426. return true;
  45427. }
  45428. if (this._reflectionTexture === texture) {
  45429. return true;
  45430. }
  45431. if (this._reflectivityTexture === texture) {
  45432. return true;
  45433. }
  45434. if (this._metallicTexture === texture) {
  45435. return true;
  45436. }
  45437. if (this._microSurfaceTexture === texture) {
  45438. return true;
  45439. }
  45440. if (this._bumpTexture === texture) {
  45441. return true;
  45442. }
  45443. if (this._lightmapTexture === texture) {
  45444. return true;
  45445. }
  45446. if (this._refractionTexture === texture) {
  45447. return true;
  45448. }
  45449. return false;
  45450. };
  45451. /**
  45452. * Makes a duplicate of the current material.
  45453. * @param name - name to use for the new material.
  45454. */
  45455. PBRMaterial.prototype.clone = function (name) {
  45456. var _this = this;
  45457. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45458. clone.id = name;
  45459. clone.name = name;
  45460. return clone;
  45461. };
  45462. /**
  45463. * Serializes this PBR Material.
  45464. * @returns - An object with the serialized material.
  45465. */
  45466. PBRMaterial.prototype.serialize = function () {
  45467. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45468. serializationObject.customType = "BABYLON.PBRMaterial";
  45469. return serializationObject;
  45470. };
  45471. // Statics
  45472. /**
  45473. * Parses a PBR Material from a serialized object.
  45474. * @param source - Serialized object.
  45475. * @param scene - BJS scene instance.
  45476. * @param rootUrl - url for the scene object
  45477. * @returns - PBRMaterial
  45478. */
  45479. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45480. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45481. };
  45482. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45483. /**
  45484. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45485. */
  45486. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45487. /**
  45488. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45489. */
  45490. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45491. /**
  45492. * 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.
  45493. * They are also discarded below the alpha cutoff threshold to improve performances.
  45494. */
  45495. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "directIntensity", void 0);
  45500. __decorate([
  45501. BABYLON.serialize(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45512. __decorate([
  45513. BABYLON.serialize(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45515. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45516. __decorate([
  45517. BABYLON.serializeAsTexture(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45520. __decorate([
  45521. BABYLON.serializeAsTexture(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45523. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45524. __decorate([
  45525. BABYLON.serialize(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45527. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45528. __decorate([
  45529. BABYLON.serializeAsTexture(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45531. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45532. __decorate([
  45533. BABYLON.serializeAsTexture(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45536. __decorate([
  45537. BABYLON.serializeAsTexture(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45540. __decorate([
  45541. BABYLON.serializeAsTexture(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45544. __decorate([
  45545. BABYLON.serializeAsTexture(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45548. __decorate([
  45549. BABYLON.serialize(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "metallic", void 0);
  45552. __decorate([
  45553. BABYLON.serialize(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "roughness", void 0);
  45556. __decorate([
  45557. BABYLON.serializeAsTexture(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45560. __decorate([
  45561. BABYLON.serializeAsTexture(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45564. __decorate([
  45565. BABYLON.serializeAsTexture(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45567. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsTexture(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45571. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45572. __decorate([
  45573. BABYLON.serializeAsColor3("ambient"),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "ambientColor", void 0);
  45576. __decorate([
  45577. BABYLON.serializeAsColor3("albedo"),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "albedoColor", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsColor3("reflectivity"),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45583. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45584. __decorate([
  45585. BABYLON.serializeAsColor3("reflection"),
  45586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45587. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45588. __decorate([
  45589. BABYLON.serializeAsColor3("emissive"),
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45591. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45592. __decorate([
  45593. BABYLON.serialize(),
  45594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45595. ], PBRMaterial.prototype, "microSurface", void 0);
  45596. __decorate([
  45597. BABYLON.serialize(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45599. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45600. __decorate([
  45601. BABYLON.serialize(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45603. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45604. __decorate([
  45605. BABYLON.serialize(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45607. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45608. __decorate([
  45609. BABYLON.serialize(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45612. __decorate([
  45613. BABYLON.serialize(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45615. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45616. __decorate([
  45617. BABYLON.serialize(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45619. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45620. __decorate([
  45621. BABYLON.serialize(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45623. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45624. __decorate([
  45625. BABYLON.serialize(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45627. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45628. __decorate([
  45629. BABYLON.serialize(),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45632. __decorate([
  45633. BABYLON.serialize(),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45636. __decorate([
  45637. BABYLON.serialize(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45648. __decorate([
  45649. BABYLON.serialize(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45656. __decorate([
  45657. BABYLON.serialize(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45659. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45660. __decorate([
  45661. BABYLON.serialize(),
  45662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45663. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45664. __decorate([
  45665. BABYLON.serialize(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45667. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45671. ], PBRMaterial.prototype, "useParallax", void 0);
  45672. __decorate([
  45673. BABYLON.serialize(),
  45674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45675. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45676. __decorate([
  45677. BABYLON.serialize(),
  45678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45679. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45680. __decorate([
  45681. BABYLON.serialize(),
  45682. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45683. ], PBRMaterial.prototype, "disableLighting", void 0);
  45684. __decorate([
  45685. BABYLON.serialize(),
  45686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45687. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45688. __decorate([
  45689. BABYLON.serialize(),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45691. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45692. __decorate([
  45693. BABYLON.serialize(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45695. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45696. __decorate([
  45697. BABYLON.serialize(),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45699. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45700. __decorate([
  45701. BABYLON.serialize(),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45703. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45704. __decorate([
  45705. BABYLON.serialize(),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45707. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45708. __decorate([
  45709. BABYLON.serialize(),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45711. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45712. __decorate([
  45713. BABYLON.serializeAsTexture(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45715. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45716. __decorate([
  45717. BABYLON.serialize(),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45719. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45720. __decorate([
  45721. BABYLON.serialize(),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45723. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45727. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45728. __decorate([
  45729. BABYLON.serialize(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45731. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45732. __decorate([
  45733. BABYLON.serialize(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45735. ], PBRMaterial.prototype, "unlit", void 0);
  45736. return PBRMaterial;
  45737. }(BABYLON.PBRBaseMaterial));
  45738. BABYLON.PBRMaterial = PBRMaterial;
  45739. })(BABYLON || (BABYLON = {}));
  45740. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45741. var BABYLON;
  45742. (function (BABYLON) {
  45743. /**
  45744. * The PBR material of BJS following the metal roughness convention.
  45745. *
  45746. * This fits to the PBR convention in the GLTF definition:
  45747. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45748. */
  45749. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45750. __extends(PBRMetallicRoughnessMaterial, _super);
  45751. /**
  45752. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45753. *
  45754. * @param name The material name
  45755. * @param scene The scene the material will be use in.
  45756. */
  45757. function PBRMetallicRoughnessMaterial(name, scene) {
  45758. var _this = _super.call(this, name, scene) || this;
  45759. _this._useRoughnessFromMetallicTextureAlpha = false;
  45760. _this._useRoughnessFromMetallicTextureGreen = true;
  45761. _this._useMetallnessFromMetallicTextureBlue = true;
  45762. _this.metallic = 1.0;
  45763. _this.roughness = 1.0;
  45764. return _this;
  45765. }
  45766. /**
  45767. * Return the currrent class name of the material.
  45768. */
  45769. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45770. return "PBRMetallicRoughnessMaterial";
  45771. };
  45772. /**
  45773. * Return the active textures of the material.
  45774. */
  45775. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45776. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45777. if (this.baseTexture) {
  45778. activeTextures.push(this.baseTexture);
  45779. }
  45780. if (this.metallicRoughnessTexture) {
  45781. activeTextures.push(this.metallicRoughnessTexture);
  45782. }
  45783. return activeTextures;
  45784. };
  45785. /**
  45786. * Checks to see if a texture is used in the material.
  45787. * @param texture - Base texture to use.
  45788. * @returns - Boolean specifying if a texture is used in the material.
  45789. */
  45790. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45791. if (_super.prototype.hasTexture.call(this, texture)) {
  45792. return true;
  45793. }
  45794. if (this.baseTexture === texture) {
  45795. return true;
  45796. }
  45797. if (this.metallicRoughnessTexture === texture) {
  45798. return true;
  45799. }
  45800. return false;
  45801. };
  45802. /**
  45803. * Makes a duplicate of the current material.
  45804. * @param name - name to use for the new material.
  45805. */
  45806. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45807. var _this = this;
  45808. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45809. clone.id = name;
  45810. clone.name = name;
  45811. return clone;
  45812. };
  45813. /**
  45814. * Serialize the material to a parsable JSON object.
  45815. */
  45816. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45817. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45818. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45819. return serializationObject;
  45820. };
  45821. /**
  45822. * Parses a JSON object correponding to the serialize function.
  45823. */
  45824. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45825. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45826. };
  45827. __decorate([
  45828. BABYLON.serializeAsColor3(),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45830. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45831. __decorate([
  45832. BABYLON.serializeAsTexture(),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45834. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45838. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45839. __decorate([
  45840. BABYLON.serialize(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45842. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45843. __decorate([
  45844. BABYLON.serializeAsTexture(),
  45845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45846. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45847. return PBRMetallicRoughnessMaterial;
  45848. }(BABYLON.PBRBaseSimpleMaterial));
  45849. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45850. })(BABYLON || (BABYLON = {}));
  45851. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45852. var BABYLON;
  45853. (function (BABYLON) {
  45854. /**
  45855. * The PBR material of BJS following the specular glossiness convention.
  45856. *
  45857. * This fits to the PBR convention in the GLTF definition:
  45858. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45859. */
  45860. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45861. __extends(PBRSpecularGlossinessMaterial, _super);
  45862. /**
  45863. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45864. *
  45865. * @param name The material name
  45866. * @param scene The scene the material will be use in.
  45867. */
  45868. function PBRSpecularGlossinessMaterial(name, scene) {
  45869. var _this = _super.call(this, name, scene) || this;
  45870. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45871. return _this;
  45872. }
  45873. /**
  45874. * Return the currrent class name of the material.
  45875. */
  45876. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45877. return "PBRSpecularGlossinessMaterial";
  45878. };
  45879. /**
  45880. * Return the active textures of the material.
  45881. */
  45882. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45883. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45884. if (this.diffuseTexture) {
  45885. activeTextures.push(this.diffuseTexture);
  45886. }
  45887. if (this.specularGlossinessTexture) {
  45888. activeTextures.push(this.specularGlossinessTexture);
  45889. }
  45890. return activeTextures;
  45891. };
  45892. /**
  45893. * Checks to see if a texture is used in the material.
  45894. * @param texture - Base texture to use.
  45895. * @returns - Boolean specifying if a texture is used in the material.
  45896. */
  45897. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45898. if (_super.prototype.hasTexture.call(this, texture)) {
  45899. return true;
  45900. }
  45901. if (this.diffuseTexture === texture) {
  45902. return true;
  45903. }
  45904. if (this.specularGlossinessTexture === texture) {
  45905. return true;
  45906. }
  45907. return false;
  45908. };
  45909. /**
  45910. * Makes a duplicate of the current material.
  45911. * @param name - name to use for the new material.
  45912. */
  45913. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45914. var _this = this;
  45915. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45916. clone.id = name;
  45917. clone.name = name;
  45918. return clone;
  45919. };
  45920. /**
  45921. * Serialize the material to a parsable JSON object.
  45922. */
  45923. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45924. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45925. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45926. return serializationObject;
  45927. };
  45928. /**
  45929. * Parses a JSON object correponding to the serialize function.
  45930. */
  45931. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45932. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45933. };
  45934. __decorate([
  45935. BABYLON.serializeAsColor3("diffuse"),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45937. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsTexture(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45941. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45942. __decorate([
  45943. BABYLON.serializeAsColor3("specular"),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45945. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45946. __decorate([
  45947. BABYLON.serialize(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45949. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45950. __decorate([
  45951. BABYLON.serializeAsTexture(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45953. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45954. return PBRSpecularGlossinessMaterial;
  45955. }(BABYLON.PBRBaseSimpleMaterial));
  45956. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45957. })(BABYLON || (BABYLON = {}));
  45958. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45959. var BABYLON;
  45960. (function (BABYLON) {
  45961. BABYLON.CameraInputTypes = {};
  45962. var CameraInputsManager = /** @class */ (function () {
  45963. function CameraInputsManager(camera) {
  45964. this.attached = {};
  45965. this.camera = camera;
  45966. this.checkInputs = function () { };
  45967. }
  45968. /**
  45969. * Add an input method to a camera.
  45970. * builtin inputs example: camera.inputs.addGamepad();
  45971. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45972. * @param input camera input method
  45973. */
  45974. CameraInputsManager.prototype.add = function (input) {
  45975. var type = input.getSimpleName();
  45976. if (this.attached[type]) {
  45977. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45978. return;
  45979. }
  45980. this.attached[type] = input;
  45981. input.camera = this.camera;
  45982. //for checkInputs, we are dynamically creating a function
  45983. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45984. if (input.checkInputs) {
  45985. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45986. }
  45987. if (this.attachedElement) {
  45988. input.attachControl(this.attachedElement);
  45989. }
  45990. };
  45991. /**
  45992. * Remove a specific input method from a camera
  45993. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45994. * @param inputToRemove camera input method
  45995. */
  45996. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45997. for (var cam in this.attached) {
  45998. var input = this.attached[cam];
  45999. if (input === inputToRemove) {
  46000. input.detachControl(this.attachedElement);
  46001. input.camera = null;
  46002. delete this.attached[cam];
  46003. this.rebuildInputCheck();
  46004. }
  46005. }
  46006. };
  46007. CameraInputsManager.prototype.removeByType = function (inputType) {
  46008. for (var cam in this.attached) {
  46009. var input = this.attached[cam];
  46010. if (input.getClassName() === inputType) {
  46011. input.detachControl(this.attachedElement);
  46012. input.camera = null;
  46013. delete this.attached[cam];
  46014. this.rebuildInputCheck();
  46015. }
  46016. }
  46017. };
  46018. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46019. var current = this.checkInputs;
  46020. return function () {
  46021. current();
  46022. fn();
  46023. };
  46024. };
  46025. CameraInputsManager.prototype.attachInput = function (input) {
  46026. if (this.attachedElement) {
  46027. input.attachControl(this.attachedElement, this.noPreventDefault);
  46028. }
  46029. };
  46030. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46031. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46032. if (this.attachedElement) {
  46033. return;
  46034. }
  46035. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46036. this.attachedElement = element;
  46037. this.noPreventDefault = noPreventDefault;
  46038. for (var cam in this.attached) {
  46039. this.attached[cam].attachControl(element, noPreventDefault);
  46040. }
  46041. };
  46042. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46043. if (disconnect === void 0) { disconnect = false; }
  46044. if (this.attachedElement !== element) {
  46045. return;
  46046. }
  46047. for (var cam in this.attached) {
  46048. this.attached[cam].detachControl(element);
  46049. if (disconnect) {
  46050. this.attached[cam].camera = null;
  46051. }
  46052. }
  46053. this.attachedElement = null;
  46054. };
  46055. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46056. this.checkInputs = function () { };
  46057. for (var cam in this.attached) {
  46058. var input = this.attached[cam];
  46059. if (input.checkInputs) {
  46060. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46061. }
  46062. }
  46063. };
  46064. /**
  46065. * Remove all attached input methods from a camera
  46066. */
  46067. CameraInputsManager.prototype.clear = function () {
  46068. if (this.attachedElement) {
  46069. this.detachElement(this.attachedElement, true);
  46070. }
  46071. this.attached = {};
  46072. this.attachedElement = null;
  46073. this.checkInputs = function () { };
  46074. };
  46075. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46076. var inputs = {};
  46077. for (var cam in this.attached) {
  46078. var input = this.attached[cam];
  46079. var res = BABYLON.SerializationHelper.Serialize(input);
  46080. inputs[input.getClassName()] = res;
  46081. }
  46082. serializedCamera.inputsmgr = inputs;
  46083. };
  46084. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46085. var parsedInputs = parsedCamera.inputsmgr;
  46086. if (parsedInputs) {
  46087. this.clear();
  46088. for (var n in parsedInputs) {
  46089. var construct = BABYLON.CameraInputTypes[n];
  46090. if (construct) {
  46091. var parsedinput = parsedInputs[n];
  46092. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46093. this.add(input);
  46094. }
  46095. }
  46096. }
  46097. else {
  46098. //2016-03-08 this part is for managing backward compatibility
  46099. for (var n in this.attached) {
  46100. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46101. if (construct) {
  46102. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46103. this.remove(this.attached[n]);
  46104. this.add(input);
  46105. }
  46106. }
  46107. }
  46108. };
  46109. return CameraInputsManager;
  46110. }());
  46111. BABYLON.CameraInputsManager = CameraInputsManager;
  46112. })(BABYLON || (BABYLON = {}));
  46113. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46114. var BABYLON;
  46115. (function (BABYLON) {
  46116. var TargetCamera = /** @class */ (function (_super) {
  46117. __extends(TargetCamera, _super);
  46118. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46119. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46120. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46121. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46122. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46123. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46124. _this.speed = 2.0;
  46125. _this.noRotationConstraint = false;
  46126. _this.lockedTarget = null;
  46127. _this._currentTarget = BABYLON.Vector3.Zero();
  46128. _this._viewMatrix = BABYLON.Matrix.Zero();
  46129. _this._camMatrix = BABYLON.Matrix.Zero();
  46130. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46131. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46132. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46133. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46134. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46135. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46136. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46137. return _this;
  46138. }
  46139. TargetCamera.prototype.getFrontPosition = function (distance) {
  46140. this.getWorldMatrix();
  46141. var direction = this.getTarget().subtract(this.position);
  46142. direction.normalize();
  46143. direction.scaleInPlace(distance);
  46144. return this.globalPosition.add(direction);
  46145. };
  46146. TargetCamera.prototype._getLockedTargetPosition = function () {
  46147. if (!this.lockedTarget) {
  46148. return null;
  46149. }
  46150. if (this.lockedTarget.absolutePosition) {
  46151. this.lockedTarget.computeWorldMatrix();
  46152. }
  46153. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46154. };
  46155. TargetCamera.prototype.storeState = function () {
  46156. this._storedPosition = this.position.clone();
  46157. this._storedRotation = this.rotation.clone();
  46158. if (this.rotationQuaternion) {
  46159. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46160. }
  46161. return _super.prototype.storeState.call(this);
  46162. };
  46163. /**
  46164. * Restored camera state. You must call storeState() first
  46165. */
  46166. TargetCamera.prototype._restoreStateValues = function () {
  46167. if (!_super.prototype._restoreStateValues.call(this)) {
  46168. return false;
  46169. }
  46170. this.position = this._storedPosition.clone();
  46171. this.rotation = this._storedRotation.clone();
  46172. if (this.rotationQuaternion) {
  46173. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46174. }
  46175. this.cameraDirection.copyFromFloats(0, 0, 0);
  46176. this.cameraRotation.copyFromFloats(0, 0);
  46177. return true;
  46178. };
  46179. // Cache
  46180. TargetCamera.prototype._initCache = function () {
  46181. _super.prototype._initCache.call(this);
  46182. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46183. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46184. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46185. };
  46186. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46187. if (!ignoreParentClass) {
  46188. _super.prototype._updateCache.call(this);
  46189. }
  46190. var lockedTargetPosition = this._getLockedTargetPosition();
  46191. if (!lockedTargetPosition) {
  46192. this._cache.lockedTarget = null;
  46193. }
  46194. else {
  46195. if (!this._cache.lockedTarget) {
  46196. this._cache.lockedTarget = lockedTargetPosition.clone();
  46197. }
  46198. else {
  46199. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46200. }
  46201. }
  46202. this._cache.rotation.copyFrom(this.rotation);
  46203. if (this.rotationQuaternion)
  46204. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46205. };
  46206. // Synchronized
  46207. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46208. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46209. return false;
  46210. }
  46211. var lockedTargetPosition = this._getLockedTargetPosition();
  46212. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46213. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46214. };
  46215. // Methods
  46216. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46217. var engine = this.getEngine();
  46218. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46219. };
  46220. // Target
  46221. TargetCamera.prototype.setTarget = function (target) {
  46222. this.upVector.normalize();
  46223. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46224. this._camMatrix.invert();
  46225. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46226. var vDir = target.subtract(this.position);
  46227. if (vDir.x >= 0.0) {
  46228. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46229. }
  46230. else {
  46231. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46232. }
  46233. this.rotation.z = 0;
  46234. if (isNaN(this.rotation.x)) {
  46235. this.rotation.x = 0;
  46236. }
  46237. if (isNaN(this.rotation.y)) {
  46238. this.rotation.y = 0;
  46239. }
  46240. if (isNaN(this.rotation.z)) {
  46241. this.rotation.z = 0;
  46242. }
  46243. if (this.rotationQuaternion) {
  46244. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46245. }
  46246. };
  46247. /**
  46248. * Return the current target position of the camera. This value is expressed in local space.
  46249. */
  46250. TargetCamera.prototype.getTarget = function () {
  46251. return this._currentTarget;
  46252. };
  46253. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46254. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46255. };
  46256. TargetCamera.prototype._updatePosition = function () {
  46257. if (this.parent) {
  46258. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46259. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46260. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46261. return;
  46262. }
  46263. this.position.addInPlace(this.cameraDirection);
  46264. };
  46265. TargetCamera.prototype._checkInputs = function () {
  46266. var needToMove = this._decideIfNeedsToMove();
  46267. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46268. // Move
  46269. if (needToMove) {
  46270. this._updatePosition();
  46271. }
  46272. // Rotate
  46273. if (needToRotate) {
  46274. this.rotation.x += this.cameraRotation.x;
  46275. this.rotation.y += this.cameraRotation.y;
  46276. //rotate, if quaternion is set and rotation was used
  46277. if (this.rotationQuaternion) {
  46278. var len = this.rotation.lengthSquared();
  46279. if (len) {
  46280. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46281. }
  46282. }
  46283. if (!this.noRotationConstraint) {
  46284. var limit = (Math.PI / 2) * 0.95;
  46285. if (this.rotation.x > limit)
  46286. this.rotation.x = limit;
  46287. if (this.rotation.x < -limit)
  46288. this.rotation.x = -limit;
  46289. }
  46290. }
  46291. // Inertia
  46292. if (needToMove) {
  46293. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46294. this.cameraDirection.x = 0;
  46295. }
  46296. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46297. this.cameraDirection.y = 0;
  46298. }
  46299. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46300. this.cameraDirection.z = 0;
  46301. }
  46302. this.cameraDirection.scaleInPlace(this.inertia);
  46303. }
  46304. if (needToRotate) {
  46305. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46306. this.cameraRotation.x = 0;
  46307. }
  46308. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46309. this.cameraRotation.y = 0;
  46310. }
  46311. this.cameraRotation.scaleInPlace(this.inertia);
  46312. }
  46313. _super.prototype._checkInputs.call(this);
  46314. };
  46315. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46316. if (this.rotationQuaternion) {
  46317. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46318. }
  46319. else {
  46320. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46321. }
  46322. //update the up vector!
  46323. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46324. };
  46325. TargetCamera.prototype._getViewMatrix = function () {
  46326. if (this.lockedTarget) {
  46327. this.setTarget(this._getLockedTargetPosition());
  46328. }
  46329. // Compute
  46330. this._updateCameraRotationMatrix();
  46331. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46332. // Computing target and final matrix
  46333. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46334. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46335. return this._viewMatrix;
  46336. };
  46337. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46338. if (this.parent) {
  46339. var parentWorldMatrix = this.parent.getWorldMatrix();
  46340. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46341. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46342. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46343. this._markSyncedWithParent();
  46344. }
  46345. else {
  46346. this._globalPosition.copyFrom(this.position);
  46347. this._globalCurrentTarget.copyFrom(target);
  46348. this._globalCurrentUpVector.copyFrom(up);
  46349. }
  46350. if (this.getScene().useRightHandedSystem) {
  46351. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46352. }
  46353. else {
  46354. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46355. }
  46356. };
  46357. /**
  46358. * @override
  46359. * Override Camera.createRigCamera
  46360. */
  46361. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46362. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46363. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46364. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46365. if (!this.rotationQuaternion) {
  46366. this.rotationQuaternion = new BABYLON.Quaternion();
  46367. }
  46368. rigCamera._cameraRigParams = {};
  46369. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46370. }
  46371. return rigCamera;
  46372. }
  46373. return null;
  46374. };
  46375. /**
  46376. * @override
  46377. * Override Camera._updateRigCameras
  46378. */
  46379. TargetCamera.prototype._updateRigCameras = function () {
  46380. var camLeft = this._rigCameras[0];
  46381. var camRight = this._rigCameras[1];
  46382. switch (this.cameraRigMode) {
  46383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46386. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46387. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46388. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46389. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46390. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46391. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46392. camLeft.setTarget(this.getTarget());
  46393. camRight.setTarget(this.getTarget());
  46394. break;
  46395. case BABYLON.Camera.RIG_MODE_VR:
  46396. if (camLeft.rotationQuaternion) {
  46397. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46398. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46399. }
  46400. else {
  46401. camLeft.rotation.copyFrom(this.rotation);
  46402. camRight.rotation.copyFrom(this.rotation);
  46403. }
  46404. camLeft.position.copyFrom(this.position);
  46405. camRight.position.copyFrom(this.position);
  46406. break;
  46407. }
  46408. _super.prototype._updateRigCameras.call(this);
  46409. };
  46410. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46411. if (!this._rigCamTransformMatrix) {
  46412. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46413. }
  46414. var target = this.getTarget();
  46415. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46416. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46417. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46418. };
  46419. TargetCamera.prototype.getClassName = function () {
  46420. return "TargetCamera";
  46421. };
  46422. __decorate([
  46423. BABYLON.serializeAsVector3()
  46424. ], TargetCamera.prototype, "rotation", void 0);
  46425. __decorate([
  46426. BABYLON.serialize()
  46427. ], TargetCamera.prototype, "speed", void 0);
  46428. __decorate([
  46429. BABYLON.serializeAsMeshReference("lockedTargetId")
  46430. ], TargetCamera.prototype, "lockedTarget", void 0);
  46431. return TargetCamera;
  46432. }(BABYLON.Camera));
  46433. BABYLON.TargetCamera = TargetCamera;
  46434. })(BABYLON || (BABYLON = {}));
  46435. //# sourceMappingURL=babylon.targetCamera.js.map
  46436. var BABYLON;
  46437. (function (BABYLON) {
  46438. var FreeCameraMouseInput = /** @class */ (function () {
  46439. function FreeCameraMouseInput(touchEnabled) {
  46440. if (touchEnabled === void 0) { touchEnabled = true; }
  46441. this.touchEnabled = touchEnabled;
  46442. this.buttons = [0, 1, 2];
  46443. this.angularSensibility = 2000.0;
  46444. this.previousPosition = null;
  46445. }
  46446. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46447. var _this = this;
  46448. var engine = this.camera.getEngine();
  46449. if (!this._pointerInput) {
  46450. this._pointerInput = function (p, s) {
  46451. var evt = p.event;
  46452. if (engine.isInVRExclusivePointerMode) {
  46453. return;
  46454. }
  46455. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46456. return;
  46457. }
  46458. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46459. return;
  46460. }
  46461. var srcElement = (evt.srcElement || evt.target);
  46462. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46463. try {
  46464. srcElement.setPointerCapture(evt.pointerId);
  46465. }
  46466. catch (e) {
  46467. //Nothing to do with the error. Execution will continue.
  46468. }
  46469. _this.previousPosition = {
  46470. x: evt.clientX,
  46471. y: evt.clientY
  46472. };
  46473. if (!noPreventDefault) {
  46474. evt.preventDefault();
  46475. element.focus();
  46476. }
  46477. }
  46478. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46479. try {
  46480. srcElement.releasePointerCapture(evt.pointerId);
  46481. }
  46482. catch (e) {
  46483. //Nothing to do with the error.
  46484. }
  46485. _this.previousPosition = null;
  46486. if (!noPreventDefault) {
  46487. evt.preventDefault();
  46488. }
  46489. }
  46490. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46491. if (!_this.previousPosition || engine.isPointerLock) {
  46492. return;
  46493. }
  46494. var offsetX = evt.clientX - _this.previousPosition.x;
  46495. if (_this.camera.getScene().useRightHandedSystem)
  46496. offsetX *= -1;
  46497. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46498. offsetX *= -1;
  46499. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46500. var offsetY = evt.clientY - _this.previousPosition.y;
  46501. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46502. _this.previousPosition = {
  46503. x: evt.clientX,
  46504. y: evt.clientY
  46505. };
  46506. if (!noPreventDefault) {
  46507. evt.preventDefault();
  46508. }
  46509. }
  46510. };
  46511. }
  46512. this._onMouseMove = function (evt) {
  46513. if (!engine.isPointerLock) {
  46514. return;
  46515. }
  46516. if (engine.isInVRExclusivePointerMode) {
  46517. return;
  46518. }
  46519. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46520. if (_this.camera.getScene().useRightHandedSystem)
  46521. offsetX *= -1;
  46522. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46523. offsetX *= -1;
  46524. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46525. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46526. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46527. _this.previousPosition = null;
  46528. if (!noPreventDefault) {
  46529. evt.preventDefault();
  46530. }
  46531. };
  46532. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46533. element.addEventListener("mousemove", this._onMouseMove, false);
  46534. };
  46535. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46536. if (this._observer && element) {
  46537. this.camera.getScene().onPointerObservable.remove(this._observer);
  46538. if (this._onMouseMove) {
  46539. element.removeEventListener("mousemove", this._onMouseMove);
  46540. }
  46541. this._observer = null;
  46542. this._onMouseMove = null;
  46543. this.previousPosition = null;
  46544. }
  46545. };
  46546. FreeCameraMouseInput.prototype.getClassName = function () {
  46547. return "FreeCameraMouseInput";
  46548. };
  46549. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46550. return "mouse";
  46551. };
  46552. __decorate([
  46553. BABYLON.serialize()
  46554. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46555. __decorate([
  46556. BABYLON.serialize()
  46557. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46558. return FreeCameraMouseInput;
  46559. }());
  46560. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46561. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46562. })(BABYLON || (BABYLON = {}));
  46563. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46564. var BABYLON;
  46565. (function (BABYLON) {
  46566. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46567. function FreeCameraKeyboardMoveInput() {
  46568. this._keys = new Array();
  46569. this.keysUp = [38];
  46570. this.keysDown = [40];
  46571. this.keysLeft = [37];
  46572. this.keysRight = [39];
  46573. }
  46574. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46575. var _this = this;
  46576. if (this._onCanvasBlurObserver) {
  46577. return;
  46578. }
  46579. this._scene = this.camera.getScene();
  46580. this._engine = this._scene.getEngine();
  46581. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46582. _this._keys = [];
  46583. });
  46584. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46585. var evt = info.event;
  46586. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46587. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46588. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46589. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46590. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46591. var index = _this._keys.indexOf(evt.keyCode);
  46592. if (index === -1) {
  46593. _this._keys.push(evt.keyCode);
  46594. }
  46595. if (!noPreventDefault) {
  46596. evt.preventDefault();
  46597. }
  46598. }
  46599. }
  46600. else {
  46601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46605. var index = _this._keys.indexOf(evt.keyCode);
  46606. if (index >= 0) {
  46607. _this._keys.splice(index, 1);
  46608. }
  46609. if (!noPreventDefault) {
  46610. evt.preventDefault();
  46611. }
  46612. }
  46613. }
  46614. });
  46615. };
  46616. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46617. if (this._scene) {
  46618. if (this._onKeyboardObserver) {
  46619. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46620. }
  46621. if (this._onCanvasBlurObserver) {
  46622. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46623. }
  46624. this._onKeyboardObserver = null;
  46625. this._onCanvasBlurObserver = null;
  46626. }
  46627. this._keys = [];
  46628. };
  46629. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46630. if (this._onKeyboardObserver) {
  46631. var camera = this.camera;
  46632. // Keyboard
  46633. for (var index = 0; index < this._keys.length; index++) {
  46634. var keyCode = this._keys[index];
  46635. var speed = camera._computeLocalCameraSpeed();
  46636. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46637. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46638. }
  46639. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46640. camera._localDirection.copyFromFloats(0, 0, speed);
  46641. }
  46642. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46643. camera._localDirection.copyFromFloats(speed, 0, 0);
  46644. }
  46645. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46646. camera._localDirection.copyFromFloats(0, 0, -speed);
  46647. }
  46648. if (camera.getScene().useRightHandedSystem) {
  46649. camera._localDirection.z *= -1;
  46650. }
  46651. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46652. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46653. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46654. }
  46655. }
  46656. };
  46657. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46658. return "FreeCameraKeyboardMoveInput";
  46659. };
  46660. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46661. this._keys = [];
  46662. };
  46663. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46664. return "keyboard";
  46665. };
  46666. __decorate([
  46667. BABYLON.serialize()
  46668. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46669. __decorate([
  46670. BABYLON.serialize()
  46671. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46672. __decorate([
  46673. BABYLON.serialize()
  46674. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46675. __decorate([
  46676. BABYLON.serialize()
  46677. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46678. return FreeCameraKeyboardMoveInput;
  46679. }());
  46680. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46681. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46682. })(BABYLON || (BABYLON = {}));
  46683. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46684. var BABYLON;
  46685. (function (BABYLON) {
  46686. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46687. __extends(FreeCameraInputsManager, _super);
  46688. function FreeCameraInputsManager(camera) {
  46689. return _super.call(this, camera) || this;
  46690. }
  46691. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46692. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46693. return this;
  46694. };
  46695. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46696. if (touchEnabled === void 0) { touchEnabled = true; }
  46697. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46698. return this;
  46699. };
  46700. FreeCameraInputsManager.prototype.addGamepad = function () {
  46701. this.add(new BABYLON.FreeCameraGamepadInput());
  46702. return this;
  46703. };
  46704. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46705. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46706. return this;
  46707. };
  46708. FreeCameraInputsManager.prototype.addTouch = function () {
  46709. this.add(new BABYLON.FreeCameraTouchInput());
  46710. return this;
  46711. };
  46712. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46713. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46714. return this;
  46715. };
  46716. return FreeCameraInputsManager;
  46717. }(BABYLON.CameraInputsManager));
  46718. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46719. })(BABYLON || (BABYLON = {}));
  46720. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46721. var BABYLON;
  46722. (function (BABYLON) {
  46723. var FreeCamera = /** @class */ (function (_super) {
  46724. __extends(FreeCamera, _super);
  46725. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46726. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46727. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46728. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46729. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46730. _this.checkCollisions = false;
  46731. _this.applyGravity = false;
  46732. _this._needMoveForGravity = false;
  46733. _this._oldPosition = BABYLON.Vector3.Zero();
  46734. _this._diffPosition = BABYLON.Vector3.Zero();
  46735. _this._newPosition = BABYLON.Vector3.Zero();
  46736. // Collisions
  46737. _this._collisionMask = -1;
  46738. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46739. if (collidedMesh === void 0) { collidedMesh = null; }
  46740. //TODO move this to the collision coordinator!
  46741. if (_this.getScene().workerCollisions)
  46742. newPosition.multiplyInPlace(_this._collider._radius);
  46743. var updatePosition = function (newPos) {
  46744. _this._newPosition.copyFrom(newPos);
  46745. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46746. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46747. _this.position.addInPlace(_this._diffPosition);
  46748. if (_this.onCollide && collidedMesh) {
  46749. _this.onCollide(collidedMesh);
  46750. }
  46751. }
  46752. };
  46753. updatePosition(newPosition);
  46754. };
  46755. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46756. _this.inputs.addKeyboard().addMouse();
  46757. return _this;
  46758. }
  46759. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46760. //-- begin properties for backward compatibility for inputs
  46761. /**
  46762. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46763. * Higher values reduce sensitivity.
  46764. */
  46765. get: function () {
  46766. var mouse = this.inputs.attached["mouse"];
  46767. if (mouse)
  46768. return mouse.angularSensibility;
  46769. return 0;
  46770. },
  46771. /**
  46772. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46773. * Higher values reduce sensitivity.
  46774. */
  46775. set: function (value) {
  46776. var mouse = this.inputs.attached["mouse"];
  46777. if (mouse)
  46778. mouse.angularSensibility = value;
  46779. },
  46780. enumerable: true,
  46781. configurable: true
  46782. });
  46783. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46784. get: function () {
  46785. var keyboard = this.inputs.attached["keyboard"];
  46786. if (keyboard)
  46787. return keyboard.keysUp;
  46788. return [];
  46789. },
  46790. set: function (value) {
  46791. var keyboard = this.inputs.attached["keyboard"];
  46792. if (keyboard)
  46793. keyboard.keysUp = value;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46799. get: function () {
  46800. var keyboard = this.inputs.attached["keyboard"];
  46801. if (keyboard)
  46802. return keyboard.keysDown;
  46803. return [];
  46804. },
  46805. set: function (value) {
  46806. var keyboard = this.inputs.attached["keyboard"];
  46807. if (keyboard)
  46808. keyboard.keysDown = value;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46814. get: function () {
  46815. var keyboard = this.inputs.attached["keyboard"];
  46816. if (keyboard)
  46817. return keyboard.keysLeft;
  46818. return [];
  46819. },
  46820. set: function (value) {
  46821. var keyboard = this.inputs.attached["keyboard"];
  46822. if (keyboard)
  46823. keyboard.keysLeft = value;
  46824. },
  46825. enumerable: true,
  46826. configurable: true
  46827. });
  46828. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46829. get: function () {
  46830. var keyboard = this.inputs.attached["keyboard"];
  46831. if (keyboard)
  46832. return keyboard.keysRight;
  46833. return [];
  46834. },
  46835. set: function (value) {
  46836. var keyboard = this.inputs.attached["keyboard"];
  46837. if (keyboard)
  46838. keyboard.keysRight = value;
  46839. },
  46840. enumerable: true,
  46841. configurable: true
  46842. });
  46843. // Controls
  46844. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46845. this.inputs.attachElement(element, noPreventDefault);
  46846. };
  46847. FreeCamera.prototype.detachControl = function (element) {
  46848. this.inputs.detachElement(element);
  46849. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46850. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46851. };
  46852. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46853. get: function () {
  46854. return this._collisionMask;
  46855. },
  46856. set: function (mask) {
  46857. this._collisionMask = !isNaN(mask) ? mask : -1;
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46863. var globalPosition;
  46864. if (this.parent) {
  46865. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46866. }
  46867. else {
  46868. globalPosition = this.position;
  46869. }
  46870. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46871. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46872. if (!this._collider) {
  46873. this._collider = new BABYLON.Collider();
  46874. }
  46875. this._collider._radius = this.ellipsoid;
  46876. this._collider.collisionMask = this._collisionMask;
  46877. //no need for clone, as long as gravity is not on.
  46878. var actualDisplacement = displacement;
  46879. //add gravity to the direction to prevent the dual-collision checking
  46880. if (this.applyGravity) {
  46881. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46882. actualDisplacement = displacement.add(this.getScene().gravity);
  46883. }
  46884. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46885. };
  46886. FreeCamera.prototype._checkInputs = function () {
  46887. if (!this._localDirection) {
  46888. this._localDirection = BABYLON.Vector3.Zero();
  46889. this._transformedDirection = BABYLON.Vector3.Zero();
  46890. }
  46891. this.inputs.checkInputs();
  46892. _super.prototype._checkInputs.call(this);
  46893. };
  46894. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46895. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46896. };
  46897. FreeCamera.prototype._updatePosition = function () {
  46898. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46899. this._collideWithWorld(this.cameraDirection);
  46900. }
  46901. else {
  46902. _super.prototype._updatePosition.call(this);
  46903. }
  46904. };
  46905. FreeCamera.prototype.dispose = function () {
  46906. this.inputs.clear();
  46907. _super.prototype.dispose.call(this);
  46908. };
  46909. FreeCamera.prototype.getClassName = function () {
  46910. return "FreeCamera";
  46911. };
  46912. __decorate([
  46913. BABYLON.serializeAsVector3()
  46914. ], FreeCamera.prototype, "ellipsoid", void 0);
  46915. __decorate([
  46916. BABYLON.serializeAsVector3()
  46917. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46918. __decorate([
  46919. BABYLON.serialize()
  46920. ], FreeCamera.prototype, "checkCollisions", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], FreeCamera.prototype, "applyGravity", void 0);
  46924. return FreeCamera;
  46925. }(BABYLON.TargetCamera));
  46926. BABYLON.FreeCamera = FreeCamera;
  46927. })(BABYLON || (BABYLON = {}));
  46928. //# sourceMappingURL=babylon.freeCamera.js.map
  46929. var BABYLON;
  46930. (function (BABYLON) {
  46931. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46932. function ArcRotateCameraKeyboardMoveInput() {
  46933. this._keys = new Array();
  46934. this.keysUp = [38];
  46935. this.keysDown = [40];
  46936. this.keysLeft = [37];
  46937. this.keysRight = [39];
  46938. this.keysReset = [220];
  46939. this.panningSensibility = 50.0;
  46940. this.zoomingSensibility = 25.0;
  46941. this.useAltToZoom = true;
  46942. }
  46943. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46944. var _this = this;
  46945. if (this._onCanvasBlurObserver) {
  46946. return;
  46947. }
  46948. this._scene = this.camera.getScene();
  46949. this._engine = this._scene.getEngine();
  46950. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46951. _this._keys = [];
  46952. });
  46953. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46954. var evt = info.event;
  46955. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46956. _this._ctrlPressed = evt.ctrlKey;
  46957. _this._altPressed = evt.altKey;
  46958. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46959. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46960. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46961. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46962. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46963. var index = _this._keys.indexOf(evt.keyCode);
  46964. if (index === -1) {
  46965. _this._keys.push(evt.keyCode);
  46966. }
  46967. if (evt.preventDefault) {
  46968. if (!noPreventDefault) {
  46969. evt.preventDefault();
  46970. }
  46971. }
  46972. }
  46973. }
  46974. else {
  46975. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46976. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46977. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46978. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46979. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46980. var index = _this._keys.indexOf(evt.keyCode);
  46981. if (index >= 0) {
  46982. _this._keys.splice(index, 1);
  46983. }
  46984. if (evt.preventDefault) {
  46985. if (!noPreventDefault) {
  46986. evt.preventDefault();
  46987. }
  46988. }
  46989. }
  46990. }
  46991. });
  46992. };
  46993. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46994. if (this._scene) {
  46995. if (this._onKeyboardObserver) {
  46996. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46997. }
  46998. if (this._onCanvasBlurObserver) {
  46999. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47000. }
  47001. this._onKeyboardObserver = null;
  47002. this._onCanvasBlurObserver = null;
  47003. }
  47004. this._keys = [];
  47005. };
  47006. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47007. if (this._onKeyboardObserver) {
  47008. var camera = this.camera;
  47009. for (var index = 0; index < this._keys.length; index++) {
  47010. var keyCode = this._keys[index];
  47011. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47012. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47013. camera.inertialPanningX -= 1 / this.panningSensibility;
  47014. }
  47015. else {
  47016. camera.inertialAlphaOffset -= 0.01;
  47017. }
  47018. }
  47019. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47020. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47021. camera.inertialPanningY += 1 / this.panningSensibility;
  47022. }
  47023. else if (this._altPressed && this.useAltToZoom) {
  47024. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47025. }
  47026. else {
  47027. camera.inertialBetaOffset -= 0.01;
  47028. }
  47029. }
  47030. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47031. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47032. camera.inertialPanningX += 1 / this.panningSensibility;
  47033. }
  47034. else {
  47035. camera.inertialAlphaOffset += 0.01;
  47036. }
  47037. }
  47038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47039. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47040. camera.inertialPanningY -= 1 / this.panningSensibility;
  47041. }
  47042. else if (this._altPressed && this.useAltToZoom) {
  47043. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47044. }
  47045. else {
  47046. camera.inertialBetaOffset += 0.01;
  47047. }
  47048. }
  47049. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47050. camera.restoreState();
  47051. }
  47052. }
  47053. }
  47054. };
  47055. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47056. return "ArcRotateCameraKeyboardMoveInput";
  47057. };
  47058. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47059. return "keyboard";
  47060. };
  47061. __decorate([
  47062. BABYLON.serialize()
  47063. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47064. __decorate([
  47065. BABYLON.serialize()
  47066. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47067. __decorate([
  47068. BABYLON.serialize()
  47069. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47070. __decorate([
  47071. BABYLON.serialize()
  47072. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47073. __decorate([
  47074. BABYLON.serialize()
  47075. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47076. __decorate([
  47077. BABYLON.serialize()
  47078. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47079. __decorate([
  47080. BABYLON.serialize()
  47081. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47082. __decorate([
  47083. BABYLON.serialize()
  47084. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47085. return ArcRotateCameraKeyboardMoveInput;
  47086. }());
  47087. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47088. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47089. })(BABYLON || (BABYLON = {}));
  47090. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47091. var BABYLON;
  47092. (function (BABYLON) {
  47093. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47094. function ArcRotateCameraMouseWheelInput() {
  47095. this.wheelPrecision = 3.0;
  47096. /**
  47097. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47098. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47099. */
  47100. this.wheelDeltaPercentage = 0;
  47101. }
  47102. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47103. var _this = this;
  47104. this._wheel = function (p, s) {
  47105. //sanity check - this should be a PointerWheel event.
  47106. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47107. return;
  47108. var event = p.event;
  47109. var delta = 0;
  47110. if (event.wheelDelta) {
  47111. if (_this.wheelDeltaPercentage) {
  47112. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47113. if (event.wheelDelta > 0) {
  47114. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47115. }
  47116. else {
  47117. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47118. }
  47119. }
  47120. else {
  47121. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47122. }
  47123. }
  47124. else if (event.detail) {
  47125. delta = -event.detail / _this.wheelPrecision;
  47126. }
  47127. if (delta)
  47128. _this.camera.inertialRadiusOffset += delta;
  47129. if (event.preventDefault) {
  47130. if (!noPreventDefault) {
  47131. event.preventDefault();
  47132. }
  47133. }
  47134. };
  47135. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47136. };
  47137. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47138. if (this._observer && element) {
  47139. this.camera.getScene().onPointerObservable.remove(this._observer);
  47140. this._observer = null;
  47141. this._wheel = null;
  47142. }
  47143. };
  47144. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47145. return "ArcRotateCameraMouseWheelInput";
  47146. };
  47147. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47148. return "mousewheel";
  47149. };
  47150. __decorate([
  47151. BABYLON.serialize()
  47152. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47153. __decorate([
  47154. BABYLON.serialize()
  47155. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47156. return ArcRotateCameraMouseWheelInput;
  47157. }());
  47158. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47159. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47160. })(BABYLON || (BABYLON = {}));
  47161. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47162. var BABYLON;
  47163. (function (BABYLON) {
  47164. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47165. function ArcRotateCameraPointersInput() {
  47166. this.buttons = [0, 1, 2];
  47167. this.angularSensibilityX = 1000.0;
  47168. this.angularSensibilityY = 1000.0;
  47169. this.pinchPrecision = 12.0;
  47170. /**
  47171. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47172. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47173. */
  47174. this.pinchDeltaPercentage = 0;
  47175. this.panningSensibility = 1000.0;
  47176. this.multiTouchPanning = true;
  47177. this.multiTouchPanAndZoom = true;
  47178. this._isPanClick = false;
  47179. this.pinchInwards = true;
  47180. }
  47181. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47182. var _this = this;
  47183. var engine = this.camera.getEngine();
  47184. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47185. var pointA = null;
  47186. var pointB = null;
  47187. var previousPinchSquaredDistance = 0;
  47188. var initialDistance = 0;
  47189. var twoFingerActivityCount = 0;
  47190. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47191. this._pointerInput = function (p, s) {
  47192. var evt = p.event;
  47193. var isTouch = p.event.pointerType === "touch";
  47194. if (engine.isInVRExclusivePointerMode) {
  47195. return;
  47196. }
  47197. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47198. return;
  47199. }
  47200. var srcElement = (evt.srcElement || evt.target);
  47201. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47202. try {
  47203. srcElement.setPointerCapture(evt.pointerId);
  47204. }
  47205. catch (e) {
  47206. //Nothing to do with the error. Execution will continue.
  47207. }
  47208. // Manage panning with pan button click
  47209. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47210. // manage pointers
  47211. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47212. if (pointA === null) {
  47213. pointA = cacheSoloPointer;
  47214. }
  47215. else if (pointB === null) {
  47216. pointB = cacheSoloPointer;
  47217. }
  47218. if (!noPreventDefault) {
  47219. evt.preventDefault();
  47220. element.focus();
  47221. }
  47222. }
  47223. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47224. _this.camera.restoreState();
  47225. }
  47226. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47227. try {
  47228. srcElement.releasePointerCapture(evt.pointerId);
  47229. }
  47230. catch (e) {
  47231. //Nothing to do with the error.
  47232. }
  47233. cacheSoloPointer = null;
  47234. previousPinchSquaredDistance = 0;
  47235. previousMultiTouchPanPosition.isPaning = false;
  47236. previousMultiTouchPanPosition.isPinching = false;
  47237. twoFingerActivityCount = 0;
  47238. initialDistance = 0;
  47239. if (!isTouch) {
  47240. pointB = null; // Mouse and pen are mono pointer
  47241. }
  47242. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47243. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47244. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47245. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47246. if (engine._badOS) {
  47247. pointA = pointB = null;
  47248. }
  47249. else {
  47250. //only remove the impacted pointer in case of multitouch allowing on most
  47251. //platforms switching from rotate to zoom and pan seamlessly.
  47252. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47253. pointA = pointB;
  47254. pointB = null;
  47255. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47256. }
  47257. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47258. pointB = null;
  47259. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47260. }
  47261. else {
  47262. pointA = pointB = null;
  47263. }
  47264. }
  47265. if (!noPreventDefault) {
  47266. evt.preventDefault();
  47267. }
  47268. }
  47269. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47270. if (!noPreventDefault) {
  47271. evt.preventDefault();
  47272. }
  47273. // One button down
  47274. if (pointA && pointB === null && cacheSoloPointer) {
  47275. if (_this.panningSensibility !== 0 &&
  47276. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47277. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47278. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47279. }
  47280. else {
  47281. var offsetX = evt.clientX - cacheSoloPointer.x;
  47282. var offsetY = evt.clientY - cacheSoloPointer.y;
  47283. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47284. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47285. }
  47286. cacheSoloPointer.x = evt.clientX;
  47287. cacheSoloPointer.y = evt.clientY;
  47288. }
  47289. // Two buttons down: pinch/pan
  47290. else if (pointA && pointB) {
  47291. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47292. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47293. ed.x = evt.clientX;
  47294. ed.y = evt.clientY;
  47295. var direction = _this.pinchInwards ? 1 : -1;
  47296. var distX = pointA.x - pointB.x;
  47297. var distY = pointA.y - pointB.y;
  47298. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47299. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47300. if (previousPinchSquaredDistance === 0) {
  47301. initialDistance = pinchDistance;
  47302. previousPinchSquaredDistance = pinchSquaredDistance;
  47303. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47304. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47305. return;
  47306. }
  47307. if (_this.multiTouchPanAndZoom) {
  47308. if (_this.pinchDeltaPercentage) {
  47309. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47310. }
  47311. else {
  47312. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47313. (_this.pinchPrecision *
  47314. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47315. direction);
  47316. }
  47317. if (_this.panningSensibility !== 0) {
  47318. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47319. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47320. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47321. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47322. previousMultiTouchPanPosition.x = pointersCenterX;
  47323. previousMultiTouchPanPosition.y = pointersCenterY;
  47324. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47325. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47326. }
  47327. }
  47328. else {
  47329. twoFingerActivityCount++;
  47330. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47331. if (_this.pinchDeltaPercentage) {
  47332. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47333. }
  47334. else {
  47335. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47336. (_this.pinchPrecision *
  47337. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47338. direction);
  47339. }
  47340. previousMultiTouchPanPosition.isPaning = false;
  47341. previousMultiTouchPanPosition.isPinching = true;
  47342. }
  47343. else {
  47344. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47345. if (!previousMultiTouchPanPosition.isPaning) {
  47346. previousMultiTouchPanPosition.isPaning = true;
  47347. previousMultiTouchPanPosition.isPinching = false;
  47348. previousMultiTouchPanPosition.x = ed.x;
  47349. previousMultiTouchPanPosition.y = ed.y;
  47350. return;
  47351. }
  47352. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47353. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47354. }
  47355. }
  47356. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47357. previousMultiTouchPanPosition.x = ed.x;
  47358. previousMultiTouchPanPosition.y = ed.y;
  47359. }
  47360. }
  47361. previousPinchSquaredDistance = pinchSquaredDistance;
  47362. }
  47363. }
  47364. };
  47365. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47366. this._onContextMenu = function (evt) {
  47367. evt.preventDefault();
  47368. };
  47369. if (!this.camera._useCtrlForPanning) {
  47370. element.addEventListener("contextmenu", this._onContextMenu, false);
  47371. }
  47372. this._onLostFocus = function () {
  47373. //this._keys = [];
  47374. pointA = pointB = null;
  47375. previousPinchSquaredDistance = 0;
  47376. previousMultiTouchPanPosition.isPaning = false;
  47377. previousMultiTouchPanPosition.isPinching = false;
  47378. twoFingerActivityCount = 0;
  47379. cacheSoloPointer = null;
  47380. initialDistance = 0;
  47381. };
  47382. this._onMouseMove = function (evt) {
  47383. if (!engine.isPointerLock) {
  47384. return;
  47385. }
  47386. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47387. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47388. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47389. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47390. if (!noPreventDefault) {
  47391. evt.preventDefault();
  47392. }
  47393. };
  47394. this._onGestureStart = function (e) {
  47395. if (window.MSGesture === undefined) {
  47396. return;
  47397. }
  47398. if (!_this._MSGestureHandler) {
  47399. _this._MSGestureHandler = new MSGesture();
  47400. _this._MSGestureHandler.target = element;
  47401. }
  47402. _this._MSGestureHandler.addPointer(e.pointerId);
  47403. };
  47404. this._onGesture = function (e) {
  47405. _this.camera.radius *= e.scale;
  47406. if (e.preventDefault) {
  47407. if (!noPreventDefault) {
  47408. e.stopPropagation();
  47409. e.preventDefault();
  47410. }
  47411. }
  47412. };
  47413. element.addEventListener("mousemove", this._onMouseMove, false);
  47414. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47415. element.addEventListener("MSGestureChange", this._onGesture, false);
  47416. BABYLON.Tools.RegisterTopRootEvents([
  47417. { name: "blur", handler: this._onLostFocus }
  47418. ]);
  47419. };
  47420. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47421. if (this._onLostFocus) {
  47422. BABYLON.Tools.UnregisterTopRootEvents([
  47423. { name: "blur", handler: this._onLostFocus }
  47424. ]);
  47425. }
  47426. if (element && this._observer) {
  47427. this.camera.getScene().onPointerObservable.remove(this._observer);
  47428. this._observer = null;
  47429. if (this._onContextMenu) {
  47430. element.removeEventListener("contextmenu", this._onContextMenu);
  47431. }
  47432. if (this._onMouseMove) {
  47433. element.removeEventListener("mousemove", this._onMouseMove);
  47434. }
  47435. if (this._onGestureStart) {
  47436. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47437. }
  47438. if (this._onGesture) {
  47439. element.removeEventListener("MSGestureChange", this._onGesture);
  47440. }
  47441. this._isPanClick = false;
  47442. this.pinchInwards = true;
  47443. this._onMouseMove = null;
  47444. this._onGestureStart = null;
  47445. this._onGesture = null;
  47446. this._MSGestureHandler = null;
  47447. this._onLostFocus = null;
  47448. this._onContextMenu = null;
  47449. }
  47450. };
  47451. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47452. return "ArcRotateCameraPointersInput";
  47453. };
  47454. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47455. return "pointers";
  47456. };
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47460. __decorate([
  47461. BABYLON.serialize()
  47462. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47463. __decorate([
  47464. BABYLON.serialize()
  47465. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47469. __decorate([
  47470. BABYLON.serialize()
  47471. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47472. __decorate([
  47473. BABYLON.serialize()
  47474. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47478. __decorate([
  47479. BABYLON.serialize()
  47480. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47481. return ArcRotateCameraPointersInput;
  47482. }());
  47483. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47484. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47485. })(BABYLON || (BABYLON = {}));
  47486. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47487. var BABYLON;
  47488. (function (BABYLON) {
  47489. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47490. __extends(ArcRotateCameraInputsManager, _super);
  47491. function ArcRotateCameraInputsManager(camera) {
  47492. return _super.call(this, camera) || this;
  47493. }
  47494. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47495. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47496. return this;
  47497. };
  47498. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47499. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47500. return this;
  47501. };
  47502. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47503. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47504. return this;
  47505. };
  47506. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47507. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47508. return this;
  47509. };
  47510. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47511. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47512. return this;
  47513. };
  47514. return ArcRotateCameraInputsManager;
  47515. }(BABYLON.CameraInputsManager));
  47516. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47517. })(BABYLON || (BABYLON = {}));
  47518. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47519. var BABYLON;
  47520. (function (BABYLON) {
  47521. var ArcRotateCamera = /** @class */ (function (_super) {
  47522. __extends(ArcRotateCamera, _super);
  47523. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47524. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47525. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47526. _this.inertialAlphaOffset = 0;
  47527. _this.inertialBetaOffset = 0;
  47528. _this.inertialRadiusOffset = 0;
  47529. _this.lowerAlphaLimit = null;
  47530. _this.upperAlphaLimit = null;
  47531. _this.lowerBetaLimit = 0.01;
  47532. _this.upperBetaLimit = Math.PI;
  47533. _this.lowerRadiusLimit = null;
  47534. _this.upperRadiusLimit = null;
  47535. _this.inertialPanningX = 0;
  47536. _this.inertialPanningY = 0;
  47537. _this.pinchToPanMaxDistance = 20;
  47538. _this.panningDistanceLimit = null;
  47539. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47540. _this.panningInertia = 0.9;
  47541. //-- end properties for backward compatibility for inputs
  47542. _this.zoomOnFactor = 1;
  47543. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47544. _this.allowUpsideDown = true;
  47545. _this._viewMatrix = new BABYLON.Matrix();
  47546. // Panning
  47547. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47548. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47549. _this.checkCollisions = false;
  47550. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47551. _this._previousPosition = BABYLON.Vector3.Zero();
  47552. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47553. _this._newPosition = BABYLON.Vector3.Zero();
  47554. _this._computationVector = BABYLON.Vector3.Zero();
  47555. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47556. if (collidedMesh === void 0) { collidedMesh = null; }
  47557. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47558. newPosition.multiplyInPlace(_this._collider._radius);
  47559. }
  47560. if (!collidedMesh) {
  47561. _this._previousPosition.copyFrom(_this.position);
  47562. }
  47563. else {
  47564. _this.setPosition(newPosition);
  47565. if (_this.onCollide) {
  47566. _this.onCollide(collidedMesh);
  47567. }
  47568. }
  47569. // Recompute because of constraints
  47570. var cosa = Math.cos(_this.alpha);
  47571. var sina = Math.sin(_this.alpha);
  47572. var cosb = Math.cos(_this.beta);
  47573. var sinb = Math.sin(_this.beta);
  47574. if (sinb === 0) {
  47575. sinb = 0.0001;
  47576. }
  47577. var target = _this._getTargetPosition();
  47578. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47579. target.addToRef(_this._computationVector, _this._newPosition);
  47580. _this.position.copyFrom(_this._newPosition);
  47581. var up = _this.upVector;
  47582. if (_this.allowUpsideDown && _this.beta < 0) {
  47583. up = up.clone();
  47584. up = up.negate();
  47585. }
  47586. _this._computeViewMatrix(_this.position, target, up);
  47587. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47588. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47589. _this._collisionTriggered = false;
  47590. };
  47591. _this._target = BABYLON.Vector3.Zero();
  47592. if (target) {
  47593. _this.setTarget(target);
  47594. }
  47595. _this.alpha = alpha;
  47596. _this.beta = beta;
  47597. _this.radius = radius;
  47598. _this.getViewMatrix();
  47599. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47600. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47601. return _this;
  47602. }
  47603. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47604. get: function () {
  47605. return this._target;
  47606. },
  47607. set: function (value) {
  47608. this.setTarget(value);
  47609. },
  47610. enumerable: true,
  47611. configurable: true
  47612. });
  47613. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47614. //-- begin properties for backward compatibility for inputs
  47615. get: function () {
  47616. var pointers = this.inputs.attached["pointers"];
  47617. if (pointers)
  47618. return pointers.angularSensibilityX;
  47619. return 0;
  47620. },
  47621. set: function (value) {
  47622. var pointers = this.inputs.attached["pointers"];
  47623. if (pointers) {
  47624. pointers.angularSensibilityX = value;
  47625. }
  47626. },
  47627. enumerable: true,
  47628. configurable: true
  47629. });
  47630. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47631. get: function () {
  47632. var pointers = this.inputs.attached["pointers"];
  47633. if (pointers)
  47634. return pointers.angularSensibilityY;
  47635. return 0;
  47636. },
  47637. set: function (value) {
  47638. var pointers = this.inputs.attached["pointers"];
  47639. if (pointers) {
  47640. pointers.angularSensibilityY = value;
  47641. }
  47642. },
  47643. enumerable: true,
  47644. configurable: true
  47645. });
  47646. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47647. get: function () {
  47648. var pointers = this.inputs.attached["pointers"];
  47649. if (pointers)
  47650. return pointers.pinchPrecision;
  47651. return 0;
  47652. },
  47653. set: function (value) {
  47654. var pointers = this.inputs.attached["pointers"];
  47655. if (pointers) {
  47656. pointers.pinchPrecision = value;
  47657. }
  47658. },
  47659. enumerable: true,
  47660. configurable: true
  47661. });
  47662. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47663. get: function () {
  47664. var pointers = this.inputs.attached["pointers"];
  47665. if (pointers)
  47666. return pointers.pinchDeltaPercentage;
  47667. return 0;
  47668. },
  47669. set: function (value) {
  47670. var pointers = this.inputs.attached["pointers"];
  47671. if (pointers) {
  47672. pointers.pinchDeltaPercentage = value;
  47673. }
  47674. },
  47675. enumerable: true,
  47676. configurable: true
  47677. });
  47678. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47679. get: function () {
  47680. var pointers = this.inputs.attached["pointers"];
  47681. if (pointers)
  47682. return pointers.panningSensibility;
  47683. return 0;
  47684. },
  47685. set: function (value) {
  47686. var pointers = this.inputs.attached["pointers"];
  47687. if (pointers) {
  47688. pointers.panningSensibility = value;
  47689. }
  47690. },
  47691. enumerable: true,
  47692. configurable: true
  47693. });
  47694. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47695. get: function () {
  47696. var keyboard = this.inputs.attached["keyboard"];
  47697. if (keyboard)
  47698. return keyboard.keysUp;
  47699. return [];
  47700. },
  47701. set: function (value) {
  47702. var keyboard = this.inputs.attached["keyboard"];
  47703. if (keyboard)
  47704. keyboard.keysUp = value;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47710. get: function () {
  47711. var keyboard = this.inputs.attached["keyboard"];
  47712. if (keyboard)
  47713. return keyboard.keysDown;
  47714. return [];
  47715. },
  47716. set: function (value) {
  47717. var keyboard = this.inputs.attached["keyboard"];
  47718. if (keyboard)
  47719. keyboard.keysDown = value;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47725. get: function () {
  47726. var keyboard = this.inputs.attached["keyboard"];
  47727. if (keyboard)
  47728. return keyboard.keysLeft;
  47729. return [];
  47730. },
  47731. set: function (value) {
  47732. var keyboard = this.inputs.attached["keyboard"];
  47733. if (keyboard)
  47734. keyboard.keysLeft = value;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47740. get: function () {
  47741. var keyboard = this.inputs.attached["keyboard"];
  47742. if (keyboard)
  47743. return keyboard.keysRight;
  47744. return [];
  47745. },
  47746. set: function (value) {
  47747. var keyboard = this.inputs.attached["keyboard"];
  47748. if (keyboard)
  47749. keyboard.keysRight = value;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47755. get: function () {
  47756. var mousewheel = this.inputs.attached["mousewheel"];
  47757. if (mousewheel)
  47758. return mousewheel.wheelPrecision;
  47759. return 0;
  47760. },
  47761. set: function (value) {
  47762. var mousewheel = this.inputs.attached["mousewheel"];
  47763. if (mousewheel)
  47764. mousewheel.wheelPrecision = value;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47770. get: function () {
  47771. var mousewheel = this.inputs.attached["mousewheel"];
  47772. if (mousewheel)
  47773. return mousewheel.wheelDeltaPercentage;
  47774. return 0;
  47775. },
  47776. set: function (value) {
  47777. var mousewheel = this.inputs.attached["mousewheel"];
  47778. if (mousewheel)
  47779. mousewheel.wheelDeltaPercentage = value;
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47785. get: function () {
  47786. return this._bouncingBehavior;
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47792. get: function () {
  47793. return this._bouncingBehavior != null;
  47794. },
  47795. set: function (value) {
  47796. if (value === this.useBouncingBehavior) {
  47797. return;
  47798. }
  47799. if (value) {
  47800. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47801. this.addBehavior(this._bouncingBehavior);
  47802. }
  47803. else if (this._bouncingBehavior) {
  47804. this.removeBehavior(this._bouncingBehavior);
  47805. this._bouncingBehavior = null;
  47806. }
  47807. },
  47808. enumerable: true,
  47809. configurable: true
  47810. });
  47811. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47812. get: function () {
  47813. return this._framingBehavior;
  47814. },
  47815. enumerable: true,
  47816. configurable: true
  47817. });
  47818. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47819. get: function () {
  47820. return this._framingBehavior != null;
  47821. },
  47822. set: function (value) {
  47823. if (value === this.useFramingBehavior) {
  47824. return;
  47825. }
  47826. if (value) {
  47827. this._framingBehavior = new BABYLON.FramingBehavior();
  47828. this.addBehavior(this._framingBehavior);
  47829. }
  47830. else if (this._framingBehavior) {
  47831. this.removeBehavior(this._framingBehavior);
  47832. this._framingBehavior = null;
  47833. }
  47834. },
  47835. enumerable: true,
  47836. configurable: true
  47837. });
  47838. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47839. get: function () {
  47840. return this._autoRotationBehavior;
  47841. },
  47842. enumerable: true,
  47843. configurable: true
  47844. });
  47845. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47846. get: function () {
  47847. return this._autoRotationBehavior != null;
  47848. },
  47849. set: function (value) {
  47850. if (value === this.useAutoRotationBehavior) {
  47851. return;
  47852. }
  47853. if (value) {
  47854. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47855. this.addBehavior(this._autoRotationBehavior);
  47856. }
  47857. else if (this._autoRotationBehavior) {
  47858. this.removeBehavior(this._autoRotationBehavior);
  47859. this._autoRotationBehavior = null;
  47860. }
  47861. },
  47862. enumerable: true,
  47863. configurable: true
  47864. });
  47865. // Cache
  47866. ArcRotateCamera.prototype._initCache = function () {
  47867. _super.prototype._initCache.call(this);
  47868. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47869. this._cache.alpha = undefined;
  47870. this._cache.beta = undefined;
  47871. this._cache.radius = undefined;
  47872. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47873. };
  47874. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47875. if (!ignoreParentClass) {
  47876. _super.prototype._updateCache.call(this);
  47877. }
  47878. this._cache._target.copyFrom(this._getTargetPosition());
  47879. this._cache.alpha = this.alpha;
  47880. this._cache.beta = this.beta;
  47881. this._cache.radius = this.radius;
  47882. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47883. };
  47884. ArcRotateCamera.prototype._getTargetPosition = function () {
  47885. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47886. var pos = this._targetHost.getAbsolutePosition();
  47887. if (this._targetBoundingCenter) {
  47888. pos.addToRef(this._targetBoundingCenter, this._target);
  47889. }
  47890. else {
  47891. this._target.copyFrom(pos);
  47892. }
  47893. }
  47894. var lockedTargetPosition = this._getLockedTargetPosition();
  47895. if (lockedTargetPosition) {
  47896. return lockedTargetPosition;
  47897. }
  47898. return this._target;
  47899. };
  47900. ArcRotateCamera.prototype.storeState = function () {
  47901. this._storedAlpha = this.alpha;
  47902. this._storedBeta = this.beta;
  47903. this._storedRadius = this.radius;
  47904. this._storedTarget = this._getTargetPosition().clone();
  47905. return _super.prototype.storeState.call(this);
  47906. };
  47907. /**
  47908. * Restored camera state. You must call storeState() first
  47909. */
  47910. ArcRotateCamera.prototype._restoreStateValues = function () {
  47911. if (!_super.prototype._restoreStateValues.call(this)) {
  47912. return false;
  47913. }
  47914. this.alpha = this._storedAlpha;
  47915. this.beta = this._storedBeta;
  47916. this.radius = this._storedRadius;
  47917. this.setTarget(this._storedTarget.clone());
  47918. this.inertialAlphaOffset = 0;
  47919. this.inertialBetaOffset = 0;
  47920. this.inertialRadiusOffset = 0;
  47921. this.inertialPanningX = 0;
  47922. this.inertialPanningY = 0;
  47923. return true;
  47924. };
  47925. // Synchronized
  47926. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47927. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47928. return false;
  47929. return this._cache._target.equals(this._getTargetPosition())
  47930. && this._cache.alpha === this.alpha
  47931. && this._cache.beta === this.beta
  47932. && this._cache.radius === this.radius
  47933. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47934. };
  47935. // Methods
  47936. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47937. var _this = this;
  47938. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47939. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47940. this._useCtrlForPanning = useCtrlForPanning;
  47941. this._panningMouseButton = panningMouseButton;
  47942. this.inputs.attachElement(element, noPreventDefault);
  47943. this._reset = function () {
  47944. _this.inertialAlphaOffset = 0;
  47945. _this.inertialBetaOffset = 0;
  47946. _this.inertialRadiusOffset = 0;
  47947. _this.inertialPanningX = 0;
  47948. _this.inertialPanningY = 0;
  47949. };
  47950. };
  47951. ArcRotateCamera.prototype.detachControl = function (element) {
  47952. this.inputs.detachElement(element);
  47953. if (this._reset) {
  47954. this._reset();
  47955. }
  47956. };
  47957. ArcRotateCamera.prototype._checkInputs = function () {
  47958. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47959. if (this._collisionTriggered) {
  47960. return;
  47961. }
  47962. this.inputs.checkInputs();
  47963. // Inertia
  47964. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47965. var inertialAlphaOffset = this.inertialAlphaOffset;
  47966. if (this.beta <= 0)
  47967. inertialAlphaOffset *= -1;
  47968. if (this.getScene().useRightHandedSystem)
  47969. inertialAlphaOffset *= -1;
  47970. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47971. inertialAlphaOffset *= -1;
  47972. this.alpha += inertialAlphaOffset;
  47973. this.beta += this.inertialBetaOffset;
  47974. this.radius -= this.inertialRadiusOffset;
  47975. this.inertialAlphaOffset *= this.inertia;
  47976. this.inertialBetaOffset *= this.inertia;
  47977. this.inertialRadiusOffset *= this.inertia;
  47978. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47979. this.inertialAlphaOffset = 0;
  47980. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47981. this.inertialBetaOffset = 0;
  47982. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47983. this.inertialRadiusOffset = 0;
  47984. }
  47985. // Panning inertia
  47986. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47987. if (!this._localDirection) {
  47988. this._localDirection = BABYLON.Vector3.Zero();
  47989. this._transformedDirection = BABYLON.Vector3.Zero();
  47990. }
  47991. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47992. this._localDirection.multiplyInPlace(this.panningAxis);
  47993. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47994. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47995. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47996. if (!this.panningAxis.y) {
  47997. this._transformedDirection.y = 0;
  47998. }
  47999. if (!this._targetHost) {
  48000. if (this.panningDistanceLimit) {
  48001. this._transformedDirection.addInPlace(this._target);
  48002. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48003. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48004. this._target.copyFrom(this._transformedDirection);
  48005. }
  48006. }
  48007. else {
  48008. this._target.addInPlace(this._transformedDirection);
  48009. }
  48010. }
  48011. this.inertialPanningX *= this.panningInertia;
  48012. this.inertialPanningY *= this.panningInertia;
  48013. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48014. this.inertialPanningX = 0;
  48015. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48016. this.inertialPanningY = 0;
  48017. }
  48018. // Limits
  48019. this._checkLimits();
  48020. _super.prototype._checkInputs.call(this);
  48021. };
  48022. ArcRotateCamera.prototype._checkLimits = function () {
  48023. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48024. if (this.allowUpsideDown && this.beta > Math.PI) {
  48025. this.beta = this.beta - (2 * Math.PI);
  48026. }
  48027. }
  48028. else {
  48029. if (this.beta < this.lowerBetaLimit) {
  48030. this.beta = this.lowerBetaLimit;
  48031. }
  48032. }
  48033. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48034. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48035. this.beta = this.beta + (2 * Math.PI);
  48036. }
  48037. }
  48038. else {
  48039. if (this.beta > this.upperBetaLimit) {
  48040. this.beta = this.upperBetaLimit;
  48041. }
  48042. }
  48043. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48044. this.alpha = this.lowerAlphaLimit;
  48045. }
  48046. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48047. this.alpha = this.upperAlphaLimit;
  48048. }
  48049. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48050. this.radius = this.lowerRadiusLimit;
  48051. }
  48052. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48053. this.radius = this.upperRadiusLimit;
  48054. }
  48055. };
  48056. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48057. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48058. this.radius = this._computationVector.length();
  48059. if (this.radius === 0) {
  48060. this.radius = 0.0001; // Just to avoid division by zero
  48061. }
  48062. // Alpha
  48063. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48064. if (this._computationVector.z < 0) {
  48065. this.alpha = 2 * Math.PI - this.alpha;
  48066. }
  48067. // Beta
  48068. this.beta = Math.acos(this._computationVector.y / this.radius);
  48069. this._checkLimits();
  48070. };
  48071. ArcRotateCamera.prototype.setPosition = function (position) {
  48072. if (this.position.equals(position)) {
  48073. return;
  48074. }
  48075. this.position.copyFrom(position);
  48076. this.rebuildAnglesAndRadius();
  48077. };
  48078. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48079. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48080. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48081. if (target.getBoundingInfo) {
  48082. if (toBoundingCenter) {
  48083. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48084. }
  48085. else {
  48086. this._targetBoundingCenter = null;
  48087. }
  48088. this._targetHost = target;
  48089. this._target = this._getTargetPosition();
  48090. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48091. }
  48092. else {
  48093. var newTarget = target;
  48094. var currentTarget = this._getTargetPosition();
  48095. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48096. return;
  48097. }
  48098. this._targetHost = null;
  48099. this._target = newTarget;
  48100. this._targetBoundingCenter = null;
  48101. this.onMeshTargetChangedObservable.notifyObservers(null);
  48102. }
  48103. this.rebuildAnglesAndRadius();
  48104. };
  48105. ArcRotateCamera.prototype._getViewMatrix = function () {
  48106. // Compute
  48107. var cosa = Math.cos(this.alpha);
  48108. var sina = Math.sin(this.alpha);
  48109. var cosb = Math.cos(this.beta);
  48110. var sinb = Math.sin(this.beta);
  48111. if (sinb === 0) {
  48112. sinb = 0.0001;
  48113. }
  48114. var target = this._getTargetPosition();
  48115. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48116. target.addToRef(this._computationVector, this._newPosition);
  48117. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48118. if (!this._collider) {
  48119. this._collider = new BABYLON.Collider();
  48120. }
  48121. this._collider._radius = this.collisionRadius;
  48122. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48123. this._collisionTriggered = true;
  48124. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48125. }
  48126. else {
  48127. this.position.copyFrom(this._newPosition);
  48128. var up = this.upVector;
  48129. if (this.allowUpsideDown && sinb < 0) {
  48130. up = up.clone();
  48131. up = up.negate();
  48132. }
  48133. this._computeViewMatrix(this.position, target, up);
  48134. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48135. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48136. }
  48137. this._currentTarget = target;
  48138. return this._viewMatrix;
  48139. };
  48140. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48141. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48142. meshes = meshes || this.getScene().meshes;
  48143. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48144. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48145. this.radius = distance * this.zoomOnFactor;
  48146. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48147. };
  48148. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48149. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48150. var meshesOrMinMaxVector;
  48151. var distance;
  48152. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48153. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48154. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48155. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48156. }
  48157. else { //minMaxVector and distance
  48158. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48159. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48160. distance = minMaxVectorAndDistance.distance;
  48161. }
  48162. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48163. if (!doNotUpdateMaxZ) {
  48164. this.maxZ = distance * 2;
  48165. }
  48166. };
  48167. /**
  48168. * @override
  48169. * Override Camera.createRigCamera
  48170. */
  48171. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48172. var alphaShift = 0;
  48173. switch (this.cameraRigMode) {
  48174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48175. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48176. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48177. case BABYLON.Camera.RIG_MODE_VR:
  48178. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48179. break;
  48180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48181. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48182. break;
  48183. }
  48184. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48185. rigCam._cameraRigParams = {};
  48186. return rigCam;
  48187. };
  48188. /**
  48189. * @override
  48190. * Override Camera._updateRigCameras
  48191. */
  48192. ArcRotateCamera.prototype._updateRigCameras = function () {
  48193. var camLeft = this._rigCameras[0];
  48194. var camRight = this._rigCameras[1];
  48195. camLeft.beta = camRight.beta = this.beta;
  48196. camLeft.radius = camRight.radius = this.radius;
  48197. switch (this.cameraRigMode) {
  48198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48199. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48201. case BABYLON.Camera.RIG_MODE_VR:
  48202. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48203. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48204. break;
  48205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48206. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48207. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48208. break;
  48209. }
  48210. _super.prototype._updateRigCameras.call(this);
  48211. };
  48212. ArcRotateCamera.prototype.dispose = function () {
  48213. this.inputs.clear();
  48214. _super.prototype.dispose.call(this);
  48215. };
  48216. ArcRotateCamera.prototype.getClassName = function () {
  48217. return "ArcRotateCamera";
  48218. };
  48219. __decorate([
  48220. BABYLON.serialize()
  48221. ], ArcRotateCamera.prototype, "alpha", void 0);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ArcRotateCamera.prototype, "beta", void 0);
  48225. __decorate([
  48226. BABYLON.serialize()
  48227. ], ArcRotateCamera.prototype, "radius", void 0);
  48228. __decorate([
  48229. BABYLON.serializeAsVector3("target")
  48230. ], ArcRotateCamera.prototype, "_target", void 0);
  48231. __decorate([
  48232. BABYLON.serialize()
  48233. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48234. __decorate([
  48235. BABYLON.serialize()
  48236. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48237. __decorate([
  48238. BABYLON.serialize()
  48239. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48240. __decorate([
  48241. BABYLON.serialize()
  48242. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48243. __decorate([
  48244. BABYLON.serialize()
  48245. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48246. __decorate([
  48247. BABYLON.serialize()
  48248. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48249. __decorate([
  48250. BABYLON.serialize()
  48251. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48252. __decorate([
  48253. BABYLON.serialize()
  48254. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48255. __decorate([
  48256. BABYLON.serialize()
  48257. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48258. __decorate([
  48259. BABYLON.serialize()
  48260. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48261. __decorate([
  48262. BABYLON.serialize()
  48263. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48264. __decorate([
  48265. BABYLON.serialize()
  48266. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48267. __decorate([
  48268. BABYLON.serialize()
  48269. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48270. __decorate([
  48271. BABYLON.serializeAsVector3()
  48272. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48273. __decorate([
  48274. BABYLON.serialize()
  48275. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48276. __decorate([
  48277. BABYLON.serialize()
  48278. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48282. return ArcRotateCamera;
  48283. }(BABYLON.TargetCamera));
  48284. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48285. })(BABYLON || (BABYLON = {}));
  48286. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48287. var BABYLON;
  48288. (function (BABYLON) {
  48289. /**
  48290. * The HemisphericLight simulates the ambient environment light,
  48291. * so the passed direction is the light reflection direction, not the incoming direction.
  48292. */
  48293. var HemisphericLight = /** @class */ (function (_super) {
  48294. __extends(HemisphericLight, _super);
  48295. /**
  48296. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48297. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48298. * The HemisphericLight can't cast shadows.
  48299. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48300. * @param name The friendly name of the light
  48301. * @param direction The direction of the light reflection
  48302. * @param scene The scene the light belongs to
  48303. */
  48304. function HemisphericLight(name, direction, scene) {
  48305. var _this = _super.call(this, name, scene) || this;
  48306. /**
  48307. * The groundColor is the light in the opposite direction to the one specified during creation.
  48308. * 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.
  48309. */
  48310. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48311. _this.direction = direction || BABYLON.Vector3.Up();
  48312. return _this;
  48313. }
  48314. HemisphericLight.prototype._buildUniformLayout = function () {
  48315. this._uniformBuffer.addUniform("vLightData", 4);
  48316. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48317. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48318. this._uniformBuffer.addUniform("vLightGround", 3);
  48319. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48320. this._uniformBuffer.addUniform("depthValues", 2);
  48321. this._uniformBuffer.create();
  48322. };
  48323. /**
  48324. * Returns the string "HemisphericLight".
  48325. * @return The class name
  48326. */
  48327. HemisphericLight.prototype.getClassName = function () {
  48328. return "HemisphericLight";
  48329. };
  48330. /**
  48331. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48332. * Returns the updated direction.
  48333. * @param target The target the direction should point to
  48334. * @return The computed direction
  48335. */
  48336. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48337. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48338. return this.direction;
  48339. };
  48340. /**
  48341. * Returns the shadow generator associated to the light.
  48342. * @returns Always null for hemispheric lights because it does not support shadows.
  48343. */
  48344. HemisphericLight.prototype.getShadowGenerator = function () {
  48345. return null;
  48346. };
  48347. /**
  48348. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48349. * @param effect The effect to update
  48350. * @param lightIndex The index of the light in the effect to update
  48351. * @returns The hemispheric light
  48352. */
  48353. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48354. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48355. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48356. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48357. return this;
  48358. };
  48359. /**
  48360. * @hidden internal use only.
  48361. */
  48362. HemisphericLight.prototype._getWorldMatrix = function () {
  48363. if (!this._worldMatrix) {
  48364. this._worldMatrix = BABYLON.Matrix.Identity();
  48365. }
  48366. return this._worldMatrix;
  48367. };
  48368. /**
  48369. * Returns the integer 3.
  48370. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48371. */
  48372. HemisphericLight.prototype.getTypeID = function () {
  48373. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48374. };
  48375. __decorate([
  48376. BABYLON.serializeAsColor3()
  48377. ], HemisphericLight.prototype, "groundColor", void 0);
  48378. __decorate([
  48379. BABYLON.serializeAsVector3()
  48380. ], HemisphericLight.prototype, "direction", void 0);
  48381. return HemisphericLight;
  48382. }(BABYLON.Light));
  48383. BABYLON.HemisphericLight = HemisphericLight;
  48384. })(BABYLON || (BABYLON = {}));
  48385. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48386. var BABYLON;
  48387. (function (BABYLON) {
  48388. /**
  48389. * Base implementation IShadowLight
  48390. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48391. */
  48392. var ShadowLight = /** @class */ (function (_super) {
  48393. __extends(ShadowLight, _super);
  48394. function ShadowLight() {
  48395. var _this = _super !== null && _super.apply(this, arguments) || this;
  48396. _this._needProjectionMatrixCompute = true;
  48397. return _this;
  48398. }
  48399. ShadowLight.prototype._setPosition = function (value) {
  48400. this._position = value;
  48401. };
  48402. Object.defineProperty(ShadowLight.prototype, "position", {
  48403. /**
  48404. * Sets the position the shadow will be casted from. Also use as the light position for both
  48405. * point and spot lights.
  48406. */
  48407. get: function () {
  48408. return this._position;
  48409. },
  48410. /**
  48411. * Sets the position the shadow will be casted from. Also use as the light position for both
  48412. * point and spot lights.
  48413. */
  48414. set: function (value) {
  48415. this._setPosition(value);
  48416. },
  48417. enumerable: true,
  48418. configurable: true
  48419. });
  48420. ShadowLight.prototype._setDirection = function (value) {
  48421. this._direction = value;
  48422. };
  48423. Object.defineProperty(ShadowLight.prototype, "direction", {
  48424. /**
  48425. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48426. * Also use as the light direction on spot and directional lights.
  48427. */
  48428. get: function () {
  48429. return this._direction;
  48430. },
  48431. /**
  48432. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48433. * Also use as the light direction on spot and directional lights.
  48434. */
  48435. set: function (value) {
  48436. this._setDirection(value);
  48437. },
  48438. enumerable: true,
  48439. configurable: true
  48440. });
  48441. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48442. /**
  48443. * Gets the shadow projection clipping minimum z value.
  48444. */
  48445. get: function () {
  48446. return this._shadowMinZ;
  48447. },
  48448. /**
  48449. * Sets the shadow projection clipping minimum z value.
  48450. */
  48451. set: function (value) {
  48452. this._shadowMinZ = value;
  48453. this.forceProjectionMatrixCompute();
  48454. },
  48455. enumerable: true,
  48456. configurable: true
  48457. });
  48458. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48459. /**
  48460. * Sets the shadow projection clipping maximum z value.
  48461. */
  48462. get: function () {
  48463. return this._shadowMaxZ;
  48464. },
  48465. /**
  48466. * Gets the shadow projection clipping maximum z value.
  48467. */
  48468. set: function (value) {
  48469. this._shadowMaxZ = value;
  48470. this.forceProjectionMatrixCompute();
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. /**
  48476. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48477. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48478. */
  48479. ShadowLight.prototype.computeTransformedInformation = function () {
  48480. if (this.parent && this.parent.getWorldMatrix) {
  48481. if (!this.transformedPosition) {
  48482. this.transformedPosition = BABYLON.Vector3.Zero();
  48483. }
  48484. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48485. // In case the direction is present.
  48486. if (this.direction) {
  48487. if (!this.transformedDirection) {
  48488. this.transformedDirection = BABYLON.Vector3.Zero();
  48489. }
  48490. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48491. }
  48492. return true;
  48493. }
  48494. return false;
  48495. };
  48496. /**
  48497. * Return the depth scale used for the shadow map.
  48498. * @returns the depth scale.
  48499. */
  48500. ShadowLight.prototype.getDepthScale = function () {
  48501. return 50.0;
  48502. };
  48503. /**
  48504. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48505. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48506. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48507. */
  48508. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48509. return this.transformedDirection ? this.transformedDirection : this.direction;
  48510. };
  48511. /**
  48512. * Returns the ShadowLight absolute position in the World.
  48513. * @returns the position vector in world space
  48514. */
  48515. ShadowLight.prototype.getAbsolutePosition = function () {
  48516. return this.transformedPosition ? this.transformedPosition : this.position;
  48517. };
  48518. /**
  48519. * Sets the ShadowLight direction toward the passed target.
  48520. * @param target The point tot target in local space
  48521. * @returns the updated ShadowLight direction
  48522. */
  48523. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48524. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48525. return this.direction;
  48526. };
  48527. /**
  48528. * Returns the light rotation in euler definition.
  48529. * @returns the x y z rotation in local space.
  48530. */
  48531. ShadowLight.prototype.getRotation = function () {
  48532. this.direction.normalize();
  48533. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48534. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48535. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48536. };
  48537. /**
  48538. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48539. * @returns true if a cube texture needs to be use
  48540. */
  48541. ShadowLight.prototype.needCube = function () {
  48542. return false;
  48543. };
  48544. /**
  48545. * Detects if the projection matrix requires to be recomputed this frame.
  48546. * @returns true if it requires to be recomputed otherwise, false.
  48547. */
  48548. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48549. return this._needProjectionMatrixCompute;
  48550. };
  48551. /**
  48552. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48553. */
  48554. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48555. this._needProjectionMatrixCompute = true;
  48556. };
  48557. /**
  48558. * Get the world matrix of the sahdow lights.
  48559. * @hidden Internal Use Only
  48560. */
  48561. ShadowLight.prototype._getWorldMatrix = function () {
  48562. if (!this._worldMatrix) {
  48563. this._worldMatrix = BABYLON.Matrix.Identity();
  48564. }
  48565. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48566. return this._worldMatrix;
  48567. };
  48568. /**
  48569. * Gets the minZ used for shadow according to both the scene and the light.
  48570. * @param activeCamera The camera we are returning the min for
  48571. * @returns the depth min z
  48572. */
  48573. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48574. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48575. };
  48576. /**
  48577. * Gets the maxZ used for shadow according to both the scene and the light.
  48578. * @param activeCamera The camera we are returning the max for
  48579. * @returns the depth max z
  48580. */
  48581. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48582. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48583. };
  48584. /**
  48585. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48586. * @param matrix The materix to updated with the projection information
  48587. * @param viewMatrix The transform matrix of the light
  48588. * @param renderList The list of mesh to render in the map
  48589. * @returns The current light
  48590. */
  48591. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48592. if (this.customProjectionMatrixBuilder) {
  48593. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48594. }
  48595. else {
  48596. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48597. }
  48598. return this;
  48599. };
  48600. __decorate([
  48601. BABYLON.serializeAsVector3()
  48602. ], ShadowLight.prototype, "position", null);
  48603. __decorate([
  48604. BABYLON.serializeAsVector3()
  48605. ], ShadowLight.prototype, "direction", null);
  48606. __decorate([
  48607. BABYLON.serialize()
  48608. ], ShadowLight.prototype, "shadowMinZ", null);
  48609. __decorate([
  48610. BABYLON.serialize()
  48611. ], ShadowLight.prototype, "shadowMaxZ", null);
  48612. return ShadowLight;
  48613. }(BABYLON.Light));
  48614. BABYLON.ShadowLight = ShadowLight;
  48615. })(BABYLON || (BABYLON = {}));
  48616. //# sourceMappingURL=babylon.shadowLight.js.map
  48617. var BABYLON;
  48618. (function (BABYLON) {
  48619. /**
  48620. * A point light is a light defined by an unique point in world space.
  48621. * The light is emitted in every direction from this point.
  48622. * A good example of a point light is a standard light bulb.
  48623. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48624. */
  48625. var PointLight = /** @class */ (function (_super) {
  48626. __extends(PointLight, _super);
  48627. /**
  48628. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48629. * A PointLight emits the light in every direction.
  48630. * It can cast shadows.
  48631. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48632. * ```javascript
  48633. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48634. * ```
  48635. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48636. * @param name The light friendly name
  48637. * @param position The position of the point light in the scene
  48638. * @param scene The scene the lights belongs to
  48639. */
  48640. function PointLight(name, position, scene) {
  48641. var _this = _super.call(this, name, scene) || this;
  48642. _this._shadowAngle = Math.PI / 2;
  48643. _this.position = position;
  48644. return _this;
  48645. }
  48646. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48647. /**
  48648. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48649. * This specifies what angle the shadow will use to be created.
  48650. *
  48651. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48652. */
  48653. get: function () {
  48654. return this._shadowAngle;
  48655. },
  48656. /**
  48657. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48658. * This specifies what angle the shadow will use to be created.
  48659. *
  48660. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48661. */
  48662. set: function (value) {
  48663. this._shadowAngle = value;
  48664. this.forceProjectionMatrixCompute();
  48665. },
  48666. enumerable: true,
  48667. configurable: true
  48668. });
  48669. Object.defineProperty(PointLight.prototype, "direction", {
  48670. /**
  48671. * Gets the direction if it has been set.
  48672. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48673. */
  48674. get: function () {
  48675. return this._direction;
  48676. },
  48677. /**
  48678. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48679. */
  48680. set: function (value) {
  48681. var previousNeedCube = this.needCube();
  48682. this._direction = value;
  48683. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48684. this._shadowGenerator.recreateShadowMap();
  48685. }
  48686. },
  48687. enumerable: true,
  48688. configurable: true
  48689. });
  48690. /**
  48691. * Returns the string "PointLight"
  48692. * @returns the class name
  48693. */
  48694. PointLight.prototype.getClassName = function () {
  48695. return "PointLight";
  48696. };
  48697. /**
  48698. * Returns the integer 0.
  48699. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48700. */
  48701. PointLight.prototype.getTypeID = function () {
  48702. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48703. };
  48704. /**
  48705. * Specifies wether or not the shadowmap should be a cube texture.
  48706. * @returns true if the shadowmap needs to be a cube texture.
  48707. */
  48708. PointLight.prototype.needCube = function () {
  48709. return !this.direction;
  48710. };
  48711. /**
  48712. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48713. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48714. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48715. */
  48716. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48717. if (this.direction) {
  48718. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48719. }
  48720. else {
  48721. switch (faceIndex) {
  48722. case 0:
  48723. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48724. case 1:
  48725. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48726. case 2:
  48727. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48728. case 3:
  48729. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48730. case 4:
  48731. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48732. case 5:
  48733. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48734. }
  48735. }
  48736. return BABYLON.Vector3.Zero();
  48737. };
  48738. /**
  48739. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48740. * - fov = PI / 2
  48741. * - aspect ratio : 1.0
  48742. * - z-near and far equal to the active camera minZ and maxZ.
  48743. * Returns the PointLight.
  48744. */
  48745. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48746. var activeCamera = this.getScene().activeCamera;
  48747. if (!activeCamera) {
  48748. return;
  48749. }
  48750. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48751. };
  48752. PointLight.prototype._buildUniformLayout = function () {
  48753. this._uniformBuffer.addUniform("vLightData", 4);
  48754. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48755. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48756. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48757. this._uniformBuffer.addUniform("depthValues", 2);
  48758. this._uniformBuffer.create();
  48759. };
  48760. /**
  48761. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48762. * @param effect The effect to update
  48763. * @param lightIndex The index of the light in the effect to update
  48764. * @returns The point light
  48765. */
  48766. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48767. if (this.computeTransformedInformation()) {
  48768. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48769. return this;
  48770. }
  48771. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48772. return this;
  48773. };
  48774. __decorate([
  48775. BABYLON.serialize()
  48776. ], PointLight.prototype, "shadowAngle", null);
  48777. return PointLight;
  48778. }(BABYLON.ShadowLight));
  48779. BABYLON.PointLight = PointLight;
  48780. })(BABYLON || (BABYLON = {}));
  48781. //# sourceMappingURL=babylon.pointLight.js.map
  48782. var BABYLON;
  48783. (function (BABYLON) {
  48784. /**
  48785. * A directional light is defined by a direction (what a surprise!).
  48786. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48787. * 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.
  48788. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48789. */
  48790. var DirectionalLight = /** @class */ (function (_super) {
  48791. __extends(DirectionalLight, _super);
  48792. /**
  48793. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48794. * The directional light is emitted from everywhere in the given direction.
  48795. * It can cast shawdows.
  48796. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48797. * @param name The friendly name of the light
  48798. * @param direction The direction of the light
  48799. * @param scene The scene the light belongs to
  48800. */
  48801. function DirectionalLight(name, direction, scene) {
  48802. var _this = _super.call(this, name, scene) || this;
  48803. _this._shadowFrustumSize = 0;
  48804. _this._shadowOrthoScale = 0.1;
  48805. /**
  48806. * Automatically compute the projection matrix to best fit (including all the casters)
  48807. * on each frame.
  48808. */
  48809. _this.autoUpdateExtends = true;
  48810. // Cache
  48811. _this._orthoLeft = Number.MAX_VALUE;
  48812. _this._orthoRight = Number.MIN_VALUE;
  48813. _this._orthoTop = Number.MIN_VALUE;
  48814. _this._orthoBottom = Number.MAX_VALUE;
  48815. _this.position = direction.scale(-1.0);
  48816. _this.direction = direction;
  48817. return _this;
  48818. }
  48819. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48820. /**
  48821. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48822. */
  48823. get: function () {
  48824. return this._shadowFrustumSize;
  48825. },
  48826. /**
  48827. * Specifies a fix frustum size for the shadow generation.
  48828. */
  48829. set: function (value) {
  48830. this._shadowFrustumSize = value;
  48831. this.forceProjectionMatrixCompute();
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48837. /**
  48838. * Gets the shadow projection scale against the optimal computed one.
  48839. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48840. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48841. */
  48842. get: function () {
  48843. return this._shadowOrthoScale;
  48844. },
  48845. /**
  48846. * Sets the shadow projection scale against the optimal computed one.
  48847. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48848. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48849. */
  48850. set: function (value) {
  48851. this._shadowOrthoScale = value;
  48852. this.forceProjectionMatrixCompute();
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. /**
  48858. * Returns the string "DirectionalLight".
  48859. * @return The class name
  48860. */
  48861. DirectionalLight.prototype.getClassName = function () {
  48862. return "DirectionalLight";
  48863. };
  48864. /**
  48865. * Returns the integer 1.
  48866. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48867. */
  48868. DirectionalLight.prototype.getTypeID = function () {
  48869. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48870. };
  48871. /**
  48872. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48873. * Returns the DirectionalLight Shadow projection matrix.
  48874. */
  48875. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48876. if (this.shadowFrustumSize > 0) {
  48877. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48878. }
  48879. else {
  48880. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48881. }
  48882. };
  48883. /**
  48884. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48885. * Returns the DirectionalLight Shadow projection matrix.
  48886. */
  48887. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48888. var activeCamera = this.getScene().activeCamera;
  48889. if (!activeCamera) {
  48890. return;
  48891. }
  48892. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48893. };
  48894. /**
  48895. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48896. * Returns the DirectionalLight Shadow projection matrix.
  48897. */
  48898. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48899. var activeCamera = this.getScene().activeCamera;
  48900. if (!activeCamera) {
  48901. return;
  48902. }
  48903. // Check extends
  48904. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48905. var tempVector3 = BABYLON.Vector3.Zero();
  48906. this._orthoLeft = Number.MAX_VALUE;
  48907. this._orthoRight = Number.MIN_VALUE;
  48908. this._orthoTop = Number.MIN_VALUE;
  48909. this._orthoBottom = Number.MAX_VALUE;
  48910. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48911. var mesh = renderList[meshIndex];
  48912. if (!mesh) {
  48913. continue;
  48914. }
  48915. var boundingInfo = mesh.getBoundingInfo();
  48916. var boundingBox = boundingInfo.boundingBox;
  48917. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48918. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48919. if (tempVector3.x < this._orthoLeft)
  48920. this._orthoLeft = tempVector3.x;
  48921. if (tempVector3.y < this._orthoBottom)
  48922. this._orthoBottom = tempVector3.y;
  48923. if (tempVector3.x > this._orthoRight)
  48924. this._orthoRight = tempVector3.x;
  48925. if (tempVector3.y > this._orthoTop)
  48926. this._orthoTop = tempVector3.y;
  48927. }
  48928. }
  48929. }
  48930. var xOffset = this._orthoRight - this._orthoLeft;
  48931. var yOffset = this._orthoTop - this._orthoBottom;
  48932. 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);
  48933. };
  48934. DirectionalLight.prototype._buildUniformLayout = function () {
  48935. this._uniformBuffer.addUniform("vLightData", 4);
  48936. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48937. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48938. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48939. this._uniformBuffer.addUniform("depthValues", 2);
  48940. this._uniformBuffer.create();
  48941. };
  48942. /**
  48943. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48944. * @param effect The effect to update
  48945. * @param lightIndex The index of the light in the effect to update
  48946. * @returns The directional light
  48947. */
  48948. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48949. if (this.computeTransformedInformation()) {
  48950. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48951. return this;
  48952. }
  48953. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48954. return this;
  48955. };
  48956. /**
  48957. * Gets the minZ used for shadow according to both the scene and the light.
  48958. *
  48959. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48960. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48961. * @param activeCamera The camera we are returning the min for
  48962. * @returns the depth min z
  48963. */
  48964. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48965. return 1;
  48966. };
  48967. /**
  48968. * Gets the maxZ used for shadow according to both the scene and the light.
  48969. *
  48970. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48971. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48972. * @param activeCamera The camera we are returning the max for
  48973. * @returns the depth max z
  48974. */
  48975. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48976. return 1;
  48977. };
  48978. __decorate([
  48979. BABYLON.serialize()
  48980. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48981. __decorate([
  48982. BABYLON.serialize()
  48983. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48984. __decorate([
  48985. BABYLON.serialize()
  48986. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48987. return DirectionalLight;
  48988. }(BABYLON.ShadowLight));
  48989. BABYLON.DirectionalLight = DirectionalLight;
  48990. })(BABYLON || (BABYLON = {}));
  48991. //# sourceMappingURL=babylon.directionalLight.js.map
  48992. var BABYLON;
  48993. (function (BABYLON) {
  48994. /**
  48995. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48996. * These values define a cone of light starting from the position, emitting toward the direction.
  48997. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48998. * and the exponent defines the speed of the decay of the light with distance (reach).
  48999. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49000. */
  49001. var SpotLight = /** @class */ (function (_super) {
  49002. __extends(SpotLight, _super);
  49003. /**
  49004. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49005. * It can cast shadows.
  49006. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49007. * @param name The light friendly name
  49008. * @param position The position of the spot light in the scene
  49009. * @param direction The direction of the light in the scene
  49010. * @param angle The cone angle of the light in Radians
  49011. * @param exponent The light decay speed with the distance from the emission spot
  49012. * @param scene The scene the lights belongs to
  49013. */
  49014. function SpotLight(name, position, direction, angle, exponent, scene) {
  49015. var _this = _super.call(this, name, scene) || this;
  49016. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49017. _this._projectionTextureLightNear = 1e-6;
  49018. _this._projectionTextureLightFar = 1000.0;
  49019. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49020. _this._projectionTextureViewLightDirty = true;
  49021. _this._projectionTextureProjectionLightDirty = true;
  49022. _this._projectionTextureDirty = true;
  49023. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49024. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49025. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49026. _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);
  49027. _this.position = position;
  49028. _this.direction = direction;
  49029. _this.angle = angle;
  49030. _this.exponent = exponent;
  49031. return _this;
  49032. }
  49033. Object.defineProperty(SpotLight.prototype, "angle", {
  49034. /**
  49035. * Gets the cone angle of the spot light in Radians.
  49036. */
  49037. get: function () {
  49038. return this._angle;
  49039. },
  49040. /**
  49041. * Sets the cone angle of the spot light in Radians.
  49042. */
  49043. set: function (value) {
  49044. this._angle = value;
  49045. this._projectionTextureProjectionLightDirty = true;
  49046. this.forceProjectionMatrixCompute();
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49052. /**
  49053. * Allows scaling the angle of the light for shadow generation only.
  49054. */
  49055. get: function () {
  49056. return this._shadowAngleScale;
  49057. },
  49058. /**
  49059. * Allows scaling the angle of the light for shadow generation only.
  49060. */
  49061. set: function (value) {
  49062. this._shadowAngleScale = value;
  49063. this.forceProjectionMatrixCompute();
  49064. },
  49065. enumerable: true,
  49066. configurable: true
  49067. });
  49068. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49069. /**
  49070. * Allows reading the projecton texture
  49071. */
  49072. get: function () {
  49073. return this._projectionTextureMatrix;
  49074. },
  49075. enumerable: true,
  49076. configurable: true
  49077. });
  49078. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49079. /**
  49080. * Gets the near clip of the Spotlight for texture projection.
  49081. */
  49082. get: function () {
  49083. return this._projectionTextureLightNear;
  49084. },
  49085. /**
  49086. * Sets the near clip of the Spotlight for texture projection.
  49087. */
  49088. set: function (value) {
  49089. this._projectionTextureLightNear = value;
  49090. this._projectionTextureProjectionLightDirty = true;
  49091. },
  49092. enumerable: true,
  49093. configurable: true
  49094. });
  49095. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49096. /**
  49097. * Gets the far clip of the Spotlight for texture projection.
  49098. */
  49099. get: function () {
  49100. return this._projectionTextureLightFar;
  49101. },
  49102. /**
  49103. * Sets the far clip of the Spotlight for texture projection.
  49104. */
  49105. set: function (value) {
  49106. this._projectionTextureLightFar = value;
  49107. this._projectionTextureProjectionLightDirty = true;
  49108. },
  49109. enumerable: true,
  49110. configurable: true
  49111. });
  49112. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49113. /**
  49114. * Gets the Up vector of the Spotlight for texture projection.
  49115. */
  49116. get: function () {
  49117. return this._projectionTextureUpDirection;
  49118. },
  49119. /**
  49120. * Sets the Up vector of the Spotlight for texture projection.
  49121. */
  49122. set: function (value) {
  49123. this._projectionTextureUpDirection = value;
  49124. this._projectionTextureProjectionLightDirty = true;
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49130. /**
  49131. * Gets the projection texture of the light.
  49132. */
  49133. get: function () {
  49134. return this._projectionTexture;
  49135. },
  49136. /**
  49137. * Sets the projection texture of the light.
  49138. */
  49139. set: function (value) {
  49140. this._projectionTexture = value;
  49141. this._projectionTextureDirty = true;
  49142. },
  49143. enumerable: true,
  49144. configurable: true
  49145. });
  49146. /**
  49147. * Returns the string "SpotLight".
  49148. * @returns the class name
  49149. */
  49150. SpotLight.prototype.getClassName = function () {
  49151. return "SpotLight";
  49152. };
  49153. /**
  49154. * Returns the integer 2.
  49155. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49156. */
  49157. SpotLight.prototype.getTypeID = function () {
  49158. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49159. };
  49160. /**
  49161. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49162. */
  49163. SpotLight.prototype._setDirection = function (value) {
  49164. _super.prototype._setDirection.call(this, value);
  49165. this._projectionTextureViewLightDirty = true;
  49166. };
  49167. /**
  49168. * Overrides the position setter to recompute the projection texture view light Matrix.
  49169. */
  49170. SpotLight.prototype._setPosition = function (value) {
  49171. _super.prototype._setPosition.call(this, value);
  49172. this._projectionTextureViewLightDirty = true;
  49173. };
  49174. /**
  49175. * 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.
  49176. * Returns the SpotLight.
  49177. */
  49178. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49179. var activeCamera = this.getScene().activeCamera;
  49180. if (!activeCamera) {
  49181. return;
  49182. }
  49183. this._shadowAngleScale = this._shadowAngleScale || 1;
  49184. var angle = this._shadowAngleScale * this._angle;
  49185. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49186. };
  49187. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49188. this._projectionTextureViewLightDirty = false;
  49189. this._projectionTextureDirty = true;
  49190. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49191. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49192. };
  49193. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49194. this._projectionTextureProjectionLightDirty = false;
  49195. this._projectionTextureDirty = true;
  49196. var light_far = this.projectionTextureLightFar;
  49197. var light_near = this.projectionTextureLightNear;
  49198. var P = light_far / (light_far - light_near);
  49199. var Q = -P * light_near;
  49200. var S = 1.0 / Math.tan(this._angle / 2.0);
  49201. var A = 1.0;
  49202. 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);
  49203. };
  49204. /**
  49205. * Main function for light texture projection matrix computing.
  49206. */
  49207. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49208. this._projectionTextureDirty = false;
  49209. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49210. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49211. };
  49212. SpotLight.prototype._buildUniformLayout = function () {
  49213. this._uniformBuffer.addUniform("vLightData", 4);
  49214. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49215. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49216. this._uniformBuffer.addUniform("vLightDirection", 3);
  49217. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49218. this._uniformBuffer.addUniform("depthValues", 2);
  49219. this._uniformBuffer.create();
  49220. };
  49221. /**
  49222. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49223. * @param effect The effect to update
  49224. * @param lightIndex The index of the light in the effect to update
  49225. * @returns The spot light
  49226. */
  49227. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49228. var normalizeDirection;
  49229. if (this.computeTransformedInformation()) {
  49230. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49231. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49232. }
  49233. else {
  49234. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49235. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49236. }
  49237. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49238. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49239. if (this._projectionTextureViewLightDirty) {
  49240. this._computeProjectionTextureViewLightMatrix();
  49241. }
  49242. if (this._projectionTextureProjectionLightDirty) {
  49243. this._computeProjectionTextureProjectionLightMatrix();
  49244. }
  49245. if (this._projectionTextureDirty) {
  49246. this._computeProjectionTextureMatrix();
  49247. }
  49248. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49249. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49250. }
  49251. return this;
  49252. };
  49253. /**
  49254. * Disposes the light and the associated resources.
  49255. */
  49256. SpotLight.prototype.dispose = function () {
  49257. _super.prototype.dispose.call(this);
  49258. if (this._projectionTexture) {
  49259. this._projectionTexture.dispose();
  49260. }
  49261. };
  49262. __decorate([
  49263. BABYLON.serialize()
  49264. ], SpotLight.prototype, "angle", null);
  49265. __decorate([
  49266. BABYLON.serialize()
  49267. ], SpotLight.prototype, "shadowAngleScale", null);
  49268. __decorate([
  49269. BABYLON.serialize()
  49270. ], SpotLight.prototype, "exponent", void 0);
  49271. __decorate([
  49272. BABYLON.serialize()
  49273. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49274. __decorate([
  49275. BABYLON.serialize()
  49276. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49277. __decorate([
  49278. BABYLON.serialize()
  49279. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49280. __decorate([
  49281. BABYLON.serializeAsTexture("projectedLightTexture")
  49282. ], SpotLight.prototype, "_projectionTexture", void 0);
  49283. return SpotLight;
  49284. }(BABYLON.ShadowLight));
  49285. BABYLON.SpotLight = SpotLight;
  49286. })(BABYLON || (BABYLON = {}));
  49287. //# sourceMappingURL=babylon.spotLight.js.map
  49288. var BABYLON;
  49289. (function (BABYLON) {
  49290. /**
  49291. * Class used to override all child animations of a given target
  49292. */
  49293. var AnimationPropertiesOverride = /** @class */ (function () {
  49294. function AnimationPropertiesOverride() {
  49295. /**
  49296. * Gets or sets a value indicating if animation blending must be used
  49297. */
  49298. this.enableBlending = false;
  49299. /**
  49300. * Gets or sets the blending speed to use when enableBlending is true
  49301. */
  49302. this.blendingSpeed = 0.01;
  49303. /**
  49304. * Gets or sets the default loop mode to use
  49305. */
  49306. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49307. }
  49308. return AnimationPropertiesOverride;
  49309. }());
  49310. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49311. })(BABYLON || (BABYLON = {}));
  49312. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49313. var BABYLON;
  49314. (function (BABYLON) {
  49315. /**
  49316. * Represents the range of an animation
  49317. */
  49318. var AnimationRange = /** @class */ (function () {
  49319. /**
  49320. * Initializes the range of an animation
  49321. * @param name The name of the animation range
  49322. * @param from The starting frame of the animation
  49323. * @param to The ending frame of the animation
  49324. */
  49325. function AnimationRange(
  49326. /**The name of the animation range**/
  49327. name,
  49328. /**The starting frame of the animation */
  49329. from,
  49330. /**The ending frame of the animation*/
  49331. to) {
  49332. this.name = name;
  49333. this.from = from;
  49334. this.to = to;
  49335. }
  49336. /**
  49337. * Makes a copy of the animation range
  49338. * @returns A copy of the animation range
  49339. */
  49340. AnimationRange.prototype.clone = function () {
  49341. return new AnimationRange(this.name, this.from, this.to);
  49342. };
  49343. return AnimationRange;
  49344. }());
  49345. BABYLON.AnimationRange = AnimationRange;
  49346. /**
  49347. * Composed of a frame, and an action function
  49348. */
  49349. var AnimationEvent = /** @class */ (function () {
  49350. /**
  49351. * Initializes the animation event
  49352. * @param frame The frame for which the event is triggered
  49353. * @param action The event to perform when triggered
  49354. * @param onlyOnce Specifies if the event should be triggered only once
  49355. */
  49356. function AnimationEvent(
  49357. /** The frame for which the event is triggered **/
  49358. frame,
  49359. /** The event to perform when triggered **/
  49360. action,
  49361. /** Specifies if the event should be triggered only once**/
  49362. onlyOnce) {
  49363. this.frame = frame;
  49364. this.action = action;
  49365. this.onlyOnce = onlyOnce;
  49366. /**
  49367. * Specifies if the animation event is done
  49368. */
  49369. this.isDone = false;
  49370. }
  49371. /** @hidden */
  49372. AnimationEvent.prototype._clone = function () {
  49373. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49374. };
  49375. return AnimationEvent;
  49376. }());
  49377. BABYLON.AnimationEvent = AnimationEvent;
  49378. /**
  49379. * A cursor which tracks a point on a path
  49380. */
  49381. var PathCursor = /** @class */ (function () {
  49382. /**
  49383. * Initializes the path cursor
  49384. * @param path The path to track
  49385. */
  49386. function PathCursor(path) {
  49387. this.path = path;
  49388. /**
  49389. * Stores path cursor callbacks for when an onchange event is triggered
  49390. */
  49391. this._onchange = new Array();
  49392. /**
  49393. * The value of the path cursor
  49394. */
  49395. this.value = 0;
  49396. /**
  49397. * The animation array of the path cursor
  49398. */
  49399. this.animations = new Array();
  49400. }
  49401. /**
  49402. * Gets the cursor point on the path
  49403. * @returns A point on the path cursor at the cursor location
  49404. */
  49405. PathCursor.prototype.getPoint = function () {
  49406. var point = this.path.getPointAtLengthPosition(this.value);
  49407. return new BABYLON.Vector3(point.x, 0, point.y);
  49408. };
  49409. /**
  49410. * Moves the cursor ahead by the step amount
  49411. * @param step The amount to move the cursor forward
  49412. * @returns This path cursor
  49413. */
  49414. PathCursor.prototype.moveAhead = function (step) {
  49415. if (step === void 0) { step = 0.002; }
  49416. this.move(step);
  49417. return this;
  49418. };
  49419. /**
  49420. * Moves the cursor behind by the step amount
  49421. * @param step The amount to move the cursor back
  49422. * @returns This path cursor
  49423. */
  49424. PathCursor.prototype.moveBack = function (step) {
  49425. if (step === void 0) { step = 0.002; }
  49426. this.move(-step);
  49427. return this;
  49428. };
  49429. /**
  49430. * Moves the cursor by the step amount
  49431. * If the step amount is greater than one, an exception is thrown
  49432. * @param step The amount to move the cursor
  49433. * @returns This path cursor
  49434. */
  49435. PathCursor.prototype.move = function (step) {
  49436. if (Math.abs(step) > 1) {
  49437. throw "step size should be less than 1.";
  49438. }
  49439. this.value += step;
  49440. this.ensureLimits();
  49441. this.raiseOnChange();
  49442. return this;
  49443. };
  49444. /**
  49445. * Ensures that the value is limited between zero and one
  49446. * @returns This path cursor
  49447. */
  49448. PathCursor.prototype.ensureLimits = function () {
  49449. while (this.value > 1) {
  49450. this.value -= 1;
  49451. }
  49452. while (this.value < 0) {
  49453. this.value += 1;
  49454. }
  49455. return this;
  49456. };
  49457. /**
  49458. * Runs onchange callbacks on change (used by the animation engine)
  49459. * @returns This path cursor
  49460. */
  49461. PathCursor.prototype.raiseOnChange = function () {
  49462. var _this = this;
  49463. this._onchange.forEach(function (f) { return f(_this); });
  49464. return this;
  49465. };
  49466. /**
  49467. * Executes a function on change
  49468. * @param f A path cursor onchange callback
  49469. * @returns This path cursor
  49470. */
  49471. PathCursor.prototype.onchange = function (f) {
  49472. this._onchange.push(f);
  49473. return this;
  49474. };
  49475. return PathCursor;
  49476. }());
  49477. BABYLON.PathCursor = PathCursor;
  49478. /**
  49479. * Enum for the animation key frame interpolation type
  49480. */
  49481. var AnimationKeyInterpolation;
  49482. (function (AnimationKeyInterpolation) {
  49483. /**
  49484. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49485. */
  49486. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49487. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49488. /**
  49489. * Class used to store any kind of animation
  49490. */
  49491. var Animation = /** @class */ (function () {
  49492. /**
  49493. * Initializes the animation
  49494. * @param name Name of the animation
  49495. * @param targetProperty Property to animate
  49496. * @param framePerSecond The frames per second of the animation
  49497. * @param dataType The data type of the animation
  49498. * @param loopMode The loop mode of the animation
  49499. * @param enableBlendings Specifies if blending should be enabled
  49500. */
  49501. function Animation(
  49502. /**Name of the animation */
  49503. name,
  49504. /**Property to animate */
  49505. targetProperty,
  49506. /**The frames per second of the animation */
  49507. framePerSecond,
  49508. /**The data type of the animation */
  49509. dataType,
  49510. /**The loop mode of the animation */
  49511. loopMode,
  49512. /**Specifies if blending should be enabled */
  49513. enableBlending) {
  49514. this.name = name;
  49515. this.targetProperty = targetProperty;
  49516. this.framePerSecond = framePerSecond;
  49517. this.dataType = dataType;
  49518. this.loopMode = loopMode;
  49519. this.enableBlending = enableBlending;
  49520. /**
  49521. * @hidden Internal use only
  49522. */
  49523. this._runtimeAnimations = new Array();
  49524. /**
  49525. * The set of event that will be linked to this animation
  49526. */
  49527. this._events = new Array();
  49528. /**
  49529. * Stores the blending speed of the animation
  49530. */
  49531. this.blendingSpeed = 0.01;
  49532. /**
  49533. * Stores the animation ranges for the animation
  49534. */
  49535. this._ranges = {};
  49536. this.targetPropertyPath = targetProperty.split(".");
  49537. this.dataType = dataType;
  49538. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49539. }
  49540. /**
  49541. * @hidden Internal use
  49542. */
  49543. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49544. var dataType = undefined;
  49545. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49546. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49547. }
  49548. else if (from instanceof BABYLON.Quaternion) {
  49549. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49550. }
  49551. else if (from instanceof BABYLON.Vector3) {
  49552. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49553. }
  49554. else if (from instanceof BABYLON.Vector2) {
  49555. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49556. }
  49557. else if (from instanceof BABYLON.Color3) {
  49558. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49559. }
  49560. else if (from instanceof BABYLON.Size) {
  49561. dataType = Animation.ANIMATIONTYPE_SIZE;
  49562. }
  49563. if (dataType == undefined) {
  49564. return null;
  49565. }
  49566. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49567. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49568. animation.setKeys(keys);
  49569. if (easingFunction !== undefined) {
  49570. animation.setEasingFunction(easingFunction);
  49571. }
  49572. return animation;
  49573. };
  49574. /**
  49575. * Sets up an animation
  49576. * @param property The property to animate
  49577. * @param animationType The animation type to apply
  49578. * @param framePerSecond The frames per second of the animation
  49579. * @param easingFunction The easing function used in the animation
  49580. * @returns The created animation
  49581. */
  49582. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49583. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49584. animation.setEasingFunction(easingFunction);
  49585. return animation;
  49586. };
  49587. /**
  49588. * Create and start an animation on a node
  49589. * @param name defines the name of the global animation that will be run on all nodes
  49590. * @param node defines the root node where the animation will take place
  49591. * @param targetProperty defines property to animate
  49592. * @param framePerSecond defines the number of frame per second yo use
  49593. * @param totalFrame defines the number of frames in total
  49594. * @param from defines the initial value
  49595. * @param to defines the final value
  49596. * @param loopMode defines which loop mode you want to use (off by default)
  49597. * @param easingFunction defines the easing function to use (linear by default)
  49598. * @param onAnimationEnd defines the callback to call when animation end
  49599. * @returns the animatable created for this animation
  49600. */
  49601. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49602. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49603. if (!animation) {
  49604. return null;
  49605. }
  49606. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49607. };
  49608. /**
  49609. * Create and start an animation on a node and its descendants
  49610. * @param name defines the name of the global animation that will be run on all nodes
  49611. * @param node defines the root node where the animation will take place
  49612. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49613. * @param targetProperty defines property to animate
  49614. * @param framePerSecond defines the number of frame per second to use
  49615. * @param totalFrame defines the number of frames in total
  49616. * @param from defines the initial value
  49617. * @param to defines the final value
  49618. * @param loopMode defines which loop mode you want to use (off by default)
  49619. * @param easingFunction defines the easing function to use (linear by default)
  49620. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49621. * @returns the list of animatables created for all nodes
  49622. * @example https://www.babylonjs-playground.com/#MH0VLI
  49623. */
  49624. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49625. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49626. if (!animation) {
  49627. return null;
  49628. }
  49629. var scene = node.getScene();
  49630. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49631. };
  49632. /**
  49633. * Creates a new animation, merges it with the existing animations and starts it
  49634. * @param name Name of the animation
  49635. * @param node Node which contains the scene that begins the animations
  49636. * @param targetProperty Specifies which property to animate
  49637. * @param framePerSecond The frames per second of the animation
  49638. * @param totalFrame The total number of frames
  49639. * @param from The frame at the beginning of the animation
  49640. * @param to The frame at the end of the animation
  49641. * @param loopMode Specifies the loop mode of the animation
  49642. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49643. * @param onAnimationEnd Callback to run once the animation is complete
  49644. * @returns Nullable animation
  49645. */
  49646. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49647. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49648. if (!animation) {
  49649. return null;
  49650. }
  49651. node.animations.push(animation);
  49652. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49653. };
  49654. /**
  49655. * Transition property of an host to the target Value
  49656. * @param property The property to transition
  49657. * @param targetValue The target Value of the property
  49658. * @param host The object where the property to animate belongs
  49659. * @param scene Scene used to run the animation
  49660. * @param frameRate Framerate (in frame/s) to use
  49661. * @param transition The transition type we want to use
  49662. * @param duration The duration of the animation, in milliseconds
  49663. * @param onAnimationEnd Callback trigger at the end of the animation
  49664. * @returns Nullable animation
  49665. */
  49666. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49667. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49668. if (duration <= 0) {
  49669. host[property] = targetValue;
  49670. if (onAnimationEnd) {
  49671. onAnimationEnd();
  49672. }
  49673. return null;
  49674. }
  49675. var endFrame = frameRate * (duration / 1000);
  49676. transition.setKeys([{
  49677. frame: 0,
  49678. value: host[property].clone ? host[property].clone() : host[property]
  49679. },
  49680. {
  49681. frame: endFrame,
  49682. value: targetValue
  49683. }]);
  49684. if (!host.animations) {
  49685. host.animations = [];
  49686. }
  49687. host.animations.push(transition);
  49688. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49689. animation.onAnimationEnd = onAnimationEnd;
  49690. return animation;
  49691. };
  49692. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49693. /**
  49694. * Return the array of runtime animations currently using this animation
  49695. */
  49696. get: function () {
  49697. return this._runtimeAnimations;
  49698. },
  49699. enumerable: true,
  49700. configurable: true
  49701. });
  49702. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49703. /**
  49704. * Specifies if any of the runtime animations are currently running
  49705. */
  49706. get: function () {
  49707. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49708. var runtimeAnimation = _a[_i];
  49709. if (!runtimeAnimation.isStopped) {
  49710. return true;
  49711. }
  49712. }
  49713. return false;
  49714. },
  49715. enumerable: true,
  49716. configurable: true
  49717. });
  49718. // Methods
  49719. /**
  49720. * Converts the animation to a string
  49721. * @param fullDetails support for multiple levels of logging within scene loading
  49722. * @returns String form of the animation
  49723. */
  49724. Animation.prototype.toString = function (fullDetails) {
  49725. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49726. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49727. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49728. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49729. if (fullDetails) {
  49730. ret += ", Ranges: {";
  49731. var first = true;
  49732. for (var name in this._ranges) {
  49733. if (first) {
  49734. ret += ", ";
  49735. first = false;
  49736. }
  49737. ret += name;
  49738. }
  49739. ret += "}";
  49740. }
  49741. return ret;
  49742. };
  49743. /**
  49744. * Add an event to this animation
  49745. * @param event Event to add
  49746. */
  49747. Animation.prototype.addEvent = function (event) {
  49748. this._events.push(event);
  49749. };
  49750. /**
  49751. * Remove all events found at the given frame
  49752. * @param frame The frame to remove events from
  49753. */
  49754. Animation.prototype.removeEvents = function (frame) {
  49755. for (var index = 0; index < this._events.length; index++) {
  49756. if (this._events[index].frame === frame) {
  49757. this._events.splice(index, 1);
  49758. index--;
  49759. }
  49760. }
  49761. };
  49762. /**
  49763. * Retrieves all the events from the animation
  49764. * @returns Events from the animation
  49765. */
  49766. Animation.prototype.getEvents = function () {
  49767. return this._events;
  49768. };
  49769. /**
  49770. * Creates an animation range
  49771. * @param name Name of the animation range
  49772. * @param from Starting frame of the animation range
  49773. * @param to Ending frame of the animation
  49774. */
  49775. Animation.prototype.createRange = function (name, from, to) {
  49776. // check name not already in use; could happen for bones after serialized
  49777. if (!this._ranges[name]) {
  49778. this._ranges[name] = new AnimationRange(name, from, to);
  49779. }
  49780. };
  49781. /**
  49782. * Deletes an animation range by name
  49783. * @param name Name of the animation range to delete
  49784. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49785. */
  49786. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49787. if (deleteFrames === void 0) { deleteFrames = true; }
  49788. var range = this._ranges[name];
  49789. if (!range) {
  49790. return;
  49791. }
  49792. if (deleteFrames) {
  49793. var from = range.from;
  49794. var to = range.to;
  49795. // this loop MUST go high to low for multiple splices to work
  49796. for (var key = this._keys.length - 1; key >= 0; key--) {
  49797. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49798. this._keys.splice(key, 1);
  49799. }
  49800. }
  49801. }
  49802. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49803. };
  49804. /**
  49805. * Gets the animation range by name, or null if not defined
  49806. * @param name Name of the animation range
  49807. * @returns Nullable animation range
  49808. */
  49809. Animation.prototype.getRange = function (name) {
  49810. return this._ranges[name];
  49811. };
  49812. /**
  49813. * Gets the key frames from the animation
  49814. * @returns The key frames of the animation
  49815. */
  49816. Animation.prototype.getKeys = function () {
  49817. return this._keys;
  49818. };
  49819. /**
  49820. * Gets the highest frame rate of the animation
  49821. * @returns Highest frame rate of the animation
  49822. */
  49823. Animation.prototype.getHighestFrame = function () {
  49824. var ret = 0;
  49825. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49826. if (ret < this._keys[key].frame) {
  49827. ret = this._keys[key].frame;
  49828. }
  49829. }
  49830. return ret;
  49831. };
  49832. /**
  49833. * Gets the easing function of the animation
  49834. * @returns Easing function of the animation
  49835. */
  49836. Animation.prototype.getEasingFunction = function () {
  49837. return this._easingFunction;
  49838. };
  49839. /**
  49840. * Sets the easing function of the animation
  49841. * @param easingFunction A custom mathematical formula for animation
  49842. */
  49843. Animation.prototype.setEasingFunction = function (easingFunction) {
  49844. this._easingFunction = easingFunction;
  49845. };
  49846. /**
  49847. * Interpolates a scalar linearly
  49848. * @param startValue Start value of the animation curve
  49849. * @param endValue End value of the animation curve
  49850. * @param gradient Scalar amount to interpolate
  49851. * @returns Interpolated scalar value
  49852. */
  49853. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49854. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49855. };
  49856. /**
  49857. * Interpolates a scalar cubically
  49858. * @param startValue Start value of the animation curve
  49859. * @param outTangent End tangent of the animation
  49860. * @param endValue End value of the animation curve
  49861. * @param inTangent Start tangent of the animation curve
  49862. * @param gradient Scalar amount to interpolate
  49863. * @returns Interpolated scalar value
  49864. */
  49865. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49866. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49867. };
  49868. /**
  49869. * Interpolates a quaternion using a spherical linear interpolation
  49870. * @param startValue Start value of the animation curve
  49871. * @param endValue End value of the animation curve
  49872. * @param gradient Scalar amount to interpolate
  49873. * @returns Interpolated quaternion value
  49874. */
  49875. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49876. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49877. };
  49878. /**
  49879. * Interpolates a quaternion cubically
  49880. * @param startValue Start value of the animation curve
  49881. * @param outTangent End tangent of the animation curve
  49882. * @param endValue End value of the animation curve
  49883. * @param inTangent Start tangent of the animation curve
  49884. * @param gradient Scalar amount to interpolate
  49885. * @returns Interpolated quaternion value
  49886. */
  49887. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49888. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49889. };
  49890. /**
  49891. * Interpolates a Vector3 linearl
  49892. * @param startValue Start value of the animation curve
  49893. * @param endValue End value of the animation curve
  49894. * @param gradient Scalar amount to interpolate
  49895. * @returns Interpolated scalar value
  49896. */
  49897. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49898. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49899. };
  49900. /**
  49901. * Interpolates a Vector3 cubically
  49902. * @param startValue Start value of the animation curve
  49903. * @param outTangent End tangent of the animation
  49904. * @param endValue End value of the animation curve
  49905. * @param inTangent Start tangent of the animation curve
  49906. * @param gradient Scalar amount to interpolate
  49907. * @returns InterpolatedVector3 value
  49908. */
  49909. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49910. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49911. };
  49912. /**
  49913. * Interpolates a Vector2 linearly
  49914. * @param startValue Start value of the animation curve
  49915. * @param endValue End value of the animation curve
  49916. * @param gradient Scalar amount to interpolate
  49917. * @returns Interpolated Vector2 value
  49918. */
  49919. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49920. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49921. };
  49922. /**
  49923. * Interpolates a Vector2 cubically
  49924. * @param startValue Start value of the animation curve
  49925. * @param outTangent End tangent of the animation
  49926. * @param endValue End value of the animation curve
  49927. * @param inTangent Start tangent of the animation curve
  49928. * @param gradient Scalar amount to interpolate
  49929. * @returns Interpolated Vector2 value
  49930. */
  49931. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49932. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49933. };
  49934. /**
  49935. * Interpolates a size linearly
  49936. * @param startValue Start value of the animation curve
  49937. * @param endValue End value of the animation curve
  49938. * @param gradient Scalar amount to interpolate
  49939. * @returns Interpolated Size value
  49940. */
  49941. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49942. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49943. };
  49944. /**
  49945. * Interpolates a Color3 linearly
  49946. * @param startValue Start value of the animation curve
  49947. * @param endValue End value of the animation curve
  49948. * @param gradient Scalar amount to interpolate
  49949. * @returns Interpolated Color3 value
  49950. */
  49951. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49952. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49953. };
  49954. /**
  49955. * @hidden Internal use only
  49956. */
  49957. Animation.prototype._getKeyValue = function (value) {
  49958. if (typeof value === "function") {
  49959. return value();
  49960. }
  49961. return value;
  49962. };
  49963. /**
  49964. * @hidden Internal use only
  49965. */
  49966. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49967. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49968. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49969. }
  49970. var keys = this.getKeys();
  49971. // Try to get a hash to find the right key
  49972. 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));
  49973. if (keys[startKeyIndex].frame >= currentFrame) {
  49974. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49975. startKeyIndex--;
  49976. }
  49977. }
  49978. for (var key = startKeyIndex; key < keys.length; key++) {
  49979. var endKey = keys[key + 1];
  49980. if (endKey.frame >= currentFrame) {
  49981. var startKey = keys[key];
  49982. var startValue = this._getKeyValue(startKey.value);
  49983. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49984. return startValue;
  49985. }
  49986. var endValue = this._getKeyValue(endKey.value);
  49987. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49988. var frameDelta = endKey.frame - startKey.frame;
  49989. // gradient : percent of currentFrame between the frame inf and the frame sup
  49990. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49991. // check for easingFunction and correction of gradient
  49992. var easingFunction = this.getEasingFunction();
  49993. if (easingFunction != null) {
  49994. gradient = easingFunction.ease(gradient);
  49995. }
  49996. switch (this.dataType) {
  49997. // Float
  49998. case Animation.ANIMATIONTYPE_FLOAT:
  49999. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50000. switch (loopMode) {
  50001. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50002. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50003. return floatValue;
  50004. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50005. return offsetValue * repeatCount + floatValue;
  50006. }
  50007. break;
  50008. // Quaternion
  50009. case Animation.ANIMATIONTYPE_QUATERNION:
  50010. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50011. switch (loopMode) {
  50012. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50013. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50014. return quatValue;
  50015. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50016. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50017. }
  50018. return quatValue;
  50019. // Vector3
  50020. case Animation.ANIMATIONTYPE_VECTOR3:
  50021. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50022. switch (loopMode) {
  50023. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50024. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50025. return vec3Value;
  50026. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50027. return vec3Value.add(offsetValue.scale(repeatCount));
  50028. }
  50029. // Vector2
  50030. case Animation.ANIMATIONTYPE_VECTOR2:
  50031. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50032. switch (loopMode) {
  50033. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50034. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50035. return vec2Value;
  50036. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50037. return vec2Value.add(offsetValue.scale(repeatCount));
  50038. }
  50039. // Size
  50040. case Animation.ANIMATIONTYPE_SIZE:
  50041. switch (loopMode) {
  50042. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50043. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50044. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50045. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50046. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50047. }
  50048. // Color3
  50049. case Animation.ANIMATIONTYPE_COLOR3:
  50050. switch (loopMode) {
  50051. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50052. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50053. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50054. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50055. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50056. }
  50057. // Matrix
  50058. case Animation.ANIMATIONTYPE_MATRIX:
  50059. switch (loopMode) {
  50060. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50061. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50062. if (Animation.AllowMatricesInterpolation) {
  50063. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50064. }
  50065. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50066. return startValue;
  50067. }
  50068. default:
  50069. break;
  50070. }
  50071. break;
  50072. }
  50073. }
  50074. return this._getKeyValue(keys[keys.length - 1].value);
  50075. };
  50076. /**
  50077. * Defines the function to use to interpolate matrices
  50078. * @param startValue defines the start matrix
  50079. * @param endValue defines the end matrix
  50080. * @param gradient defines the gradient between both matrices
  50081. * @param result defines an optional target matrix where to store the interpolation
  50082. * @returns the interpolated matrix
  50083. */
  50084. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50085. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50086. if (result) {
  50087. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50088. return result;
  50089. }
  50090. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50091. }
  50092. if (result) {
  50093. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50094. return result;
  50095. }
  50096. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50097. };
  50098. /**
  50099. * Makes a copy of the animation
  50100. * @returns Cloned animation
  50101. */
  50102. Animation.prototype.clone = function () {
  50103. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50104. clone.enableBlending = this.enableBlending;
  50105. clone.blendingSpeed = this.blendingSpeed;
  50106. if (this._keys) {
  50107. clone.setKeys(this._keys);
  50108. }
  50109. if (this._ranges) {
  50110. clone._ranges = {};
  50111. for (var name in this._ranges) {
  50112. var range = this._ranges[name];
  50113. if (!range) {
  50114. continue;
  50115. }
  50116. clone._ranges[name] = range.clone();
  50117. }
  50118. }
  50119. return clone;
  50120. };
  50121. /**
  50122. * Sets the key frames of the animation
  50123. * @param values The animation key frames to set
  50124. */
  50125. Animation.prototype.setKeys = function (values) {
  50126. this._keys = values.slice(0);
  50127. };
  50128. /**
  50129. * Serializes the animation to an object
  50130. * @returns Serialized object
  50131. */
  50132. Animation.prototype.serialize = function () {
  50133. var serializationObject = {};
  50134. serializationObject.name = this.name;
  50135. serializationObject.property = this.targetProperty;
  50136. serializationObject.framePerSecond = this.framePerSecond;
  50137. serializationObject.dataType = this.dataType;
  50138. serializationObject.loopBehavior = this.loopMode;
  50139. serializationObject.enableBlending = this.enableBlending;
  50140. serializationObject.blendingSpeed = this.blendingSpeed;
  50141. var dataType = this.dataType;
  50142. serializationObject.keys = [];
  50143. var keys = this.getKeys();
  50144. for (var index = 0; index < keys.length; index++) {
  50145. var animationKey = keys[index];
  50146. var key = {};
  50147. key.frame = animationKey.frame;
  50148. switch (dataType) {
  50149. case Animation.ANIMATIONTYPE_FLOAT:
  50150. key.values = [animationKey.value];
  50151. break;
  50152. case Animation.ANIMATIONTYPE_QUATERNION:
  50153. case Animation.ANIMATIONTYPE_MATRIX:
  50154. case Animation.ANIMATIONTYPE_VECTOR3:
  50155. case Animation.ANIMATIONTYPE_COLOR3:
  50156. key.values = animationKey.value.asArray();
  50157. break;
  50158. }
  50159. serializationObject.keys.push(key);
  50160. }
  50161. serializationObject.ranges = [];
  50162. for (var name in this._ranges) {
  50163. var source = this._ranges[name];
  50164. if (!source) {
  50165. continue;
  50166. }
  50167. var range = {};
  50168. range.name = name;
  50169. range.from = source.from;
  50170. range.to = source.to;
  50171. serializationObject.ranges.push(range);
  50172. }
  50173. return serializationObject;
  50174. };
  50175. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50176. /**
  50177. * Get the float animation type
  50178. */
  50179. get: function () {
  50180. return Animation._ANIMATIONTYPE_FLOAT;
  50181. },
  50182. enumerable: true,
  50183. configurable: true
  50184. });
  50185. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50186. /**
  50187. * Get the Vector3 animation type
  50188. */
  50189. get: function () {
  50190. return Animation._ANIMATIONTYPE_VECTOR3;
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50196. /**
  50197. * Get the Vectpr2 animation type
  50198. */
  50199. get: function () {
  50200. return Animation._ANIMATIONTYPE_VECTOR2;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50206. /**
  50207. * Get the Size animation type
  50208. */
  50209. get: function () {
  50210. return Animation._ANIMATIONTYPE_SIZE;
  50211. },
  50212. enumerable: true,
  50213. configurable: true
  50214. });
  50215. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50216. /**
  50217. * Get the Quaternion animation type
  50218. */
  50219. get: function () {
  50220. return Animation._ANIMATIONTYPE_QUATERNION;
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50226. /**
  50227. * Get the Matrix animation type
  50228. */
  50229. get: function () {
  50230. return Animation._ANIMATIONTYPE_MATRIX;
  50231. },
  50232. enumerable: true,
  50233. configurable: true
  50234. });
  50235. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50236. /**
  50237. * Get the Color3 animation type
  50238. */
  50239. get: function () {
  50240. return Animation._ANIMATIONTYPE_COLOR3;
  50241. },
  50242. enumerable: true,
  50243. configurable: true
  50244. });
  50245. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50246. /**
  50247. * Get the Relative Loop Mode
  50248. */
  50249. get: function () {
  50250. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50251. },
  50252. enumerable: true,
  50253. configurable: true
  50254. });
  50255. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50256. /**
  50257. * Get the Cycle Loop Mode
  50258. */
  50259. get: function () {
  50260. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50261. },
  50262. enumerable: true,
  50263. configurable: true
  50264. });
  50265. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50266. /**
  50267. * Get the Constant Loop Mode
  50268. */
  50269. get: function () {
  50270. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. /** @hidden */
  50276. Animation._UniversalLerp = function (left, right, amount) {
  50277. var constructor = left.constructor;
  50278. if (constructor.Lerp) { // Lerp supported
  50279. return constructor.Lerp(left, right, amount);
  50280. }
  50281. else if (constructor.Slerp) { // Slerp supported
  50282. return constructor.Slerp(left, right, amount);
  50283. }
  50284. else if (left.toFixed) { // Number
  50285. return left * (1.0 - amount) + amount * right;
  50286. }
  50287. else { // Blending not supported
  50288. return right;
  50289. }
  50290. };
  50291. /**
  50292. * Parses an animation object and creates an animation
  50293. * @param parsedAnimation Parsed animation object
  50294. * @returns Animation object
  50295. */
  50296. Animation.Parse = function (parsedAnimation) {
  50297. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50298. var dataType = parsedAnimation.dataType;
  50299. var keys = [];
  50300. var data;
  50301. var index;
  50302. if (parsedAnimation.enableBlending) {
  50303. animation.enableBlending = parsedAnimation.enableBlending;
  50304. }
  50305. if (parsedAnimation.blendingSpeed) {
  50306. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50307. }
  50308. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50309. var key = parsedAnimation.keys[index];
  50310. var inTangent;
  50311. var outTangent;
  50312. switch (dataType) {
  50313. case Animation.ANIMATIONTYPE_FLOAT:
  50314. data = key.values[0];
  50315. if (key.values.length >= 1) {
  50316. inTangent = key.values[1];
  50317. }
  50318. if (key.values.length >= 2) {
  50319. outTangent = key.values[2];
  50320. }
  50321. break;
  50322. case Animation.ANIMATIONTYPE_QUATERNION:
  50323. data = BABYLON.Quaternion.FromArray(key.values);
  50324. if (key.values.length >= 8) {
  50325. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50326. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50327. inTangent = _inTangent;
  50328. }
  50329. }
  50330. if (key.values.length >= 12) {
  50331. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50332. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50333. outTangent = _outTangent;
  50334. }
  50335. }
  50336. break;
  50337. case Animation.ANIMATIONTYPE_MATRIX:
  50338. data = BABYLON.Matrix.FromArray(key.values);
  50339. break;
  50340. case Animation.ANIMATIONTYPE_COLOR3:
  50341. data = BABYLON.Color3.FromArray(key.values);
  50342. break;
  50343. case Animation.ANIMATIONTYPE_VECTOR3:
  50344. default:
  50345. data = BABYLON.Vector3.FromArray(key.values);
  50346. break;
  50347. }
  50348. var keyData = {};
  50349. keyData.frame = key.frame;
  50350. keyData.value = data;
  50351. if (inTangent != undefined) {
  50352. keyData.inTangent = inTangent;
  50353. }
  50354. if (outTangent != undefined) {
  50355. keyData.outTangent = outTangent;
  50356. }
  50357. keys.push(keyData);
  50358. }
  50359. animation.setKeys(keys);
  50360. if (parsedAnimation.ranges) {
  50361. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50362. data = parsedAnimation.ranges[index];
  50363. animation.createRange(data.name, data.from, data.to);
  50364. }
  50365. }
  50366. return animation;
  50367. };
  50368. /**
  50369. * Appends the serialized animations from the source animations
  50370. * @param source Source containing the animations
  50371. * @param destination Target to store the animations
  50372. */
  50373. Animation.AppendSerializedAnimations = function (source, destination) {
  50374. if (source.animations) {
  50375. destination.animations = [];
  50376. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50377. var animation = source.animations[animationIndex];
  50378. destination.animations.push(animation.serialize());
  50379. }
  50380. }
  50381. };
  50382. /**
  50383. * Use matrix interpolation instead of using direct key value when animating matrices
  50384. */
  50385. Animation.AllowMatricesInterpolation = false;
  50386. /**
  50387. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50388. */
  50389. Animation.AllowMatrixDecomposeForInterpolation = true;
  50390. // Statics
  50391. /**
  50392. * Float animation type
  50393. */
  50394. Animation._ANIMATIONTYPE_FLOAT = 0;
  50395. /**
  50396. * Vector3 animation type
  50397. */
  50398. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50399. /**
  50400. * Quaternion animation type
  50401. */
  50402. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50403. /**
  50404. * Matrix animation type
  50405. */
  50406. Animation._ANIMATIONTYPE_MATRIX = 3;
  50407. /**
  50408. * Color3 animation type
  50409. */
  50410. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50411. /**
  50412. * Vector2 animation type
  50413. */
  50414. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50415. /**
  50416. * Size animation type
  50417. */
  50418. Animation._ANIMATIONTYPE_SIZE = 6;
  50419. /**
  50420. * Relative Loop Mode
  50421. */
  50422. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50423. /**
  50424. * Cycle Loop Mode
  50425. */
  50426. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50427. /**
  50428. * Constant Loop Mode
  50429. */
  50430. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50431. return Animation;
  50432. }());
  50433. BABYLON.Animation = Animation;
  50434. })(BABYLON || (BABYLON = {}));
  50435. //# sourceMappingURL=babylon.animation.js.map
  50436. var BABYLON;
  50437. (function (BABYLON) {
  50438. /**
  50439. * This class defines the direct association between an animation and a target
  50440. */
  50441. var TargetedAnimation = /** @class */ (function () {
  50442. function TargetedAnimation() {
  50443. }
  50444. return TargetedAnimation;
  50445. }());
  50446. BABYLON.TargetedAnimation = TargetedAnimation;
  50447. /**
  50448. * Use this class to create coordinated animations on multiple targets
  50449. */
  50450. var AnimationGroup = /** @class */ (function () {
  50451. function AnimationGroup(name, scene) {
  50452. if (scene === void 0) { scene = null; }
  50453. this.name = name;
  50454. this._targetedAnimations = new Array();
  50455. this._animatables = new Array();
  50456. this._from = Number.MAX_VALUE;
  50457. this._to = -Number.MAX_VALUE;
  50458. this._speedRatio = 1;
  50459. this.onAnimationEndObservable = new BABYLON.Observable();
  50460. /**
  50461. * This observable will notify when all animations have ended.
  50462. */
  50463. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50464. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50465. this._scene.animationGroups.push(this);
  50466. }
  50467. Object.defineProperty(AnimationGroup.prototype, "from", {
  50468. /**
  50469. * Gets the first frame
  50470. */
  50471. get: function () {
  50472. return this._from;
  50473. },
  50474. enumerable: true,
  50475. configurable: true
  50476. });
  50477. Object.defineProperty(AnimationGroup.prototype, "to", {
  50478. /**
  50479. * Gets the last frame
  50480. */
  50481. get: function () {
  50482. return this._to;
  50483. },
  50484. enumerable: true,
  50485. configurable: true
  50486. });
  50487. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50488. /**
  50489. * Define if the animations are started
  50490. */
  50491. get: function () {
  50492. return this._isStarted;
  50493. },
  50494. enumerable: true,
  50495. configurable: true
  50496. });
  50497. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50498. /**
  50499. * Gets or sets the speed ratio to use for all animations
  50500. */
  50501. get: function () {
  50502. return this._speedRatio;
  50503. },
  50504. /**
  50505. * Gets or sets the speed ratio to use for all animations
  50506. */
  50507. set: function (value) {
  50508. if (this._speedRatio === value) {
  50509. return;
  50510. }
  50511. this._speedRatio = value;
  50512. for (var index = 0; index < this._animatables.length; index++) {
  50513. var animatable = this._animatables[index];
  50514. animatable.speedRatio = this._speedRatio;
  50515. }
  50516. },
  50517. enumerable: true,
  50518. configurable: true
  50519. });
  50520. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50521. /**
  50522. * Gets the targeted animations for this animation group
  50523. */
  50524. get: function () {
  50525. return this._targetedAnimations;
  50526. },
  50527. enumerable: true,
  50528. configurable: true
  50529. });
  50530. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50531. /**
  50532. * returning the list of animatables controlled by this animation group.
  50533. */
  50534. get: function () {
  50535. return this._animatables;
  50536. },
  50537. enumerable: true,
  50538. configurable: true
  50539. });
  50540. /**
  50541. * Add an animation (with its target) in the group
  50542. * @param animation defines the animation we want to add
  50543. * @param target defines the target of the animation
  50544. * @returns the {BABYLON.TargetedAnimation} object
  50545. */
  50546. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50547. var targetedAnimation = {
  50548. animation: animation,
  50549. target: target
  50550. };
  50551. var keys = animation.getKeys();
  50552. if (this._from > keys[0].frame) {
  50553. this._from = keys[0].frame;
  50554. }
  50555. if (this._to < keys[keys.length - 1].frame) {
  50556. this._to = keys[keys.length - 1].frame;
  50557. }
  50558. this._targetedAnimations.push(targetedAnimation);
  50559. return targetedAnimation;
  50560. };
  50561. /**
  50562. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50563. * It can add constant keys at begin or end
  50564. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50565. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50566. */
  50567. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50568. if (beginFrame === void 0) { beginFrame = null; }
  50569. if (endFrame === void 0) { endFrame = null; }
  50570. if (beginFrame == null)
  50571. beginFrame = this._from;
  50572. if (endFrame == null)
  50573. endFrame = this._to;
  50574. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50575. var targetedAnimation = this._targetedAnimations[index];
  50576. var keys = targetedAnimation.animation.getKeys();
  50577. var startKey = keys[0];
  50578. var endKey = keys[keys.length - 1];
  50579. if (startKey.frame > beginFrame) {
  50580. var newKey = {
  50581. frame: beginFrame,
  50582. value: startKey.value,
  50583. inTangent: startKey.inTangent,
  50584. outTangent: startKey.outTangent,
  50585. interpolation: startKey.interpolation
  50586. };
  50587. keys.splice(0, 0, newKey);
  50588. }
  50589. if (endKey.frame < endFrame) {
  50590. var newKey = {
  50591. frame: endFrame,
  50592. value: endKey.value,
  50593. inTangent: endKey.outTangent,
  50594. outTangent: endKey.outTangent,
  50595. interpolation: endKey.interpolation
  50596. };
  50597. keys.push(newKey);
  50598. }
  50599. }
  50600. this._from = beginFrame;
  50601. this._to = endFrame;
  50602. return this;
  50603. };
  50604. /**
  50605. * Start all animations on given targets
  50606. * @param loop defines if animations must loop
  50607. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50608. * @param from defines the from key (optional)
  50609. * @param to defines the to key (optional)
  50610. * @returns the current animation group
  50611. */
  50612. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50613. var _this = this;
  50614. if (loop === void 0) { loop = false; }
  50615. if (speedRatio === void 0) { speedRatio = 1; }
  50616. if (this._isStarted || this._targetedAnimations.length === 0) {
  50617. return this;
  50618. }
  50619. var _loop_1 = function (targetedAnimation) {
  50620. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50621. animatable.onAnimationEnd = function () {
  50622. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50623. _this._checkAnimationGroupEnded(animatable);
  50624. };
  50625. this_1._animatables.push(animatable);
  50626. };
  50627. var this_1 = this;
  50628. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50629. var targetedAnimation = _a[_i];
  50630. _loop_1(targetedAnimation);
  50631. }
  50632. this._speedRatio = speedRatio;
  50633. this._isStarted = true;
  50634. return this;
  50635. };
  50636. /**
  50637. * Pause all animations
  50638. */
  50639. AnimationGroup.prototype.pause = function () {
  50640. if (!this._isStarted) {
  50641. return this;
  50642. }
  50643. for (var index = 0; index < this._animatables.length; index++) {
  50644. var animatable = this._animatables[index];
  50645. animatable.pause();
  50646. }
  50647. return this;
  50648. };
  50649. /**
  50650. * Play all animations to initial state
  50651. * This function will start() the animations if they were not started or will restart() them if they were paused
  50652. * @param loop defines if animations must loop
  50653. */
  50654. AnimationGroup.prototype.play = function (loop) {
  50655. // only if all animatables are ready and exist
  50656. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50657. if (loop !== undefined) {
  50658. for (var index = 0; index < this._animatables.length; index++) {
  50659. var animatable = this._animatables[index];
  50660. animatable.loopAnimation = loop;
  50661. }
  50662. }
  50663. this.restart();
  50664. }
  50665. else {
  50666. this.stop();
  50667. this.start(loop, this._speedRatio);
  50668. }
  50669. return this;
  50670. };
  50671. /**
  50672. * Reset all animations to initial state
  50673. */
  50674. AnimationGroup.prototype.reset = function () {
  50675. if (!this._isStarted) {
  50676. return this;
  50677. }
  50678. for (var index = 0; index < this._animatables.length; index++) {
  50679. var animatable = this._animatables[index];
  50680. animatable.reset();
  50681. }
  50682. return this;
  50683. };
  50684. /**
  50685. * Restart animations from key 0
  50686. */
  50687. AnimationGroup.prototype.restart = function () {
  50688. if (!this._isStarted) {
  50689. return this;
  50690. }
  50691. for (var index = 0; index < this._animatables.length; index++) {
  50692. var animatable = this._animatables[index];
  50693. animatable.restart();
  50694. }
  50695. return this;
  50696. };
  50697. /**
  50698. * Stop all animations
  50699. */
  50700. AnimationGroup.prototype.stop = function () {
  50701. if (!this._isStarted) {
  50702. return this;
  50703. }
  50704. var list = this._animatables.slice();
  50705. for (var index = 0; index < list.length; index++) {
  50706. list[index].stop();
  50707. }
  50708. this._isStarted = false;
  50709. return this;
  50710. };
  50711. /**
  50712. * Set animation weight for all animatables
  50713. * @param weight defines the weight to use
  50714. * @return the animationGroup
  50715. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50716. */
  50717. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50718. for (var index = 0; index < this._animatables.length; index++) {
  50719. var animatable = this._animatables[index];
  50720. animatable.weight = weight;
  50721. }
  50722. return this;
  50723. };
  50724. /**
  50725. * Synchronize and normalize all animatables with a source animatable
  50726. * @param root defines the root animatable to synchronize with
  50727. * @return the animationGroup
  50728. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50729. */
  50730. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50731. for (var index = 0; index < this._animatables.length; index++) {
  50732. var animatable = this._animatables[index];
  50733. animatable.syncWith(root);
  50734. }
  50735. return this;
  50736. };
  50737. /**
  50738. * Goes to a specific frame in this animation group
  50739. * @param frame the frame number to go to
  50740. * @return the animationGroup
  50741. */
  50742. AnimationGroup.prototype.goToFrame = function (frame) {
  50743. if (!this._isStarted) {
  50744. return this;
  50745. }
  50746. for (var index = 0; index < this._animatables.length; index++) {
  50747. var animatable = this._animatables[index];
  50748. animatable.goToFrame(frame);
  50749. }
  50750. return this;
  50751. };
  50752. /**
  50753. * Dispose all associated resources
  50754. */
  50755. AnimationGroup.prototype.dispose = function () {
  50756. this._targetedAnimations = [];
  50757. this._animatables = [];
  50758. var index = this._scene.animationGroups.indexOf(this);
  50759. if (index > -1) {
  50760. this._scene.animationGroups.splice(index, 1);
  50761. }
  50762. };
  50763. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50764. // animatable should be taken out of the array
  50765. var idx = this._animatables.indexOf(animatable);
  50766. if (idx > -1) {
  50767. this._animatables.splice(idx, 1);
  50768. }
  50769. // all animatables were removed? animation group ended!
  50770. if (this._animatables.length === 0) {
  50771. this._isStarted = false;
  50772. this.onAnimationGroupEndObservable.notifyObservers(this);
  50773. }
  50774. };
  50775. return AnimationGroup;
  50776. }());
  50777. BABYLON.AnimationGroup = AnimationGroup;
  50778. })(BABYLON || (BABYLON = {}));
  50779. //# sourceMappingURL=babylon.animationGroup.js.map
  50780. var BABYLON;
  50781. (function (BABYLON) {
  50782. /**
  50783. * Defines a runtime animation
  50784. */
  50785. var RuntimeAnimation = /** @class */ (function () {
  50786. /**
  50787. * Create a new RuntimeAnimation object
  50788. * @param target defines the target of the animation
  50789. * @param animation defines the source animation object
  50790. * @param scene defines the hosting scene
  50791. * @param host defines the initiating Animatable
  50792. */
  50793. function RuntimeAnimation(target, animation, scene, host) {
  50794. var _this = this;
  50795. this._events = new Array();
  50796. /**
  50797. * The current frame of the runtime animation
  50798. */
  50799. this._currentFrame = 0;
  50800. /**
  50801. * The original value of the runtime animation
  50802. */
  50803. this._originalValue = new Array();
  50804. /**
  50805. * The offsets cache of the runtime animation
  50806. */
  50807. this._offsetsCache = {};
  50808. /**
  50809. * The high limits cache of the runtime animation
  50810. */
  50811. this._highLimitsCache = {};
  50812. /**
  50813. * Specifies if the runtime animation has been stopped
  50814. */
  50815. this._stopped = false;
  50816. /**
  50817. * The blending factor of the runtime animation
  50818. */
  50819. this._blendingFactor = 0;
  50820. /**
  50821. * The target path of the runtime animation
  50822. */
  50823. this._targetPath = "";
  50824. /**
  50825. * The weight of the runtime animation
  50826. */
  50827. this._weight = 1.0;
  50828. /**
  50829. * The ratio offset of the runtime animation
  50830. */
  50831. this._ratioOffset = 0;
  50832. /**
  50833. * The previous delay of the runtime animation
  50834. */
  50835. this._previousDelay = 0;
  50836. /**
  50837. * The previous ratio of the runtime animation
  50838. */
  50839. this._previousRatio = 0;
  50840. this._animation = animation;
  50841. this._target = target;
  50842. this._scene = scene;
  50843. this._host = host;
  50844. animation._runtimeAnimations.push(this);
  50845. // Cloning events locally
  50846. var events = animation.getEvents();
  50847. if (events && events.length > 0) {
  50848. events.forEach(function (e) {
  50849. _this._events.push(e._clone());
  50850. });
  50851. }
  50852. }
  50853. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50854. /**
  50855. * Gets the current frame of the runtime animation
  50856. */
  50857. get: function () {
  50858. return this._currentFrame;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50864. /**
  50865. * Gets the weight of the runtime animation
  50866. */
  50867. get: function () {
  50868. return this._weight;
  50869. },
  50870. enumerable: true,
  50871. configurable: true
  50872. });
  50873. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50874. /**
  50875. * Gets the current value of the runtime animation
  50876. */
  50877. get: function () {
  50878. return this._currentValue;
  50879. },
  50880. enumerable: true,
  50881. configurable: true
  50882. });
  50883. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50884. /**
  50885. * Gets the target path of the runtime animation
  50886. */
  50887. get: function () {
  50888. return this._targetPath;
  50889. },
  50890. enumerable: true,
  50891. configurable: true
  50892. });
  50893. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50894. /**
  50895. * Gets the actual target of the runtime animation
  50896. */
  50897. get: function () {
  50898. return this._activeTarget;
  50899. },
  50900. enumerable: true,
  50901. configurable: true
  50902. });
  50903. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50904. /**
  50905. * Gets the animation from the runtime animation
  50906. */
  50907. get: function () {
  50908. return this._animation;
  50909. },
  50910. enumerable: true,
  50911. configurable: true
  50912. });
  50913. /**
  50914. * Resets the runtime animation to the beginning
  50915. * @param restoreOriginal defines whether to restore the target property to the original value
  50916. */
  50917. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50918. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50919. if (restoreOriginal) {
  50920. if (this._target instanceof Array) {
  50921. var index = 0;
  50922. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50923. var target = _a[_i];
  50924. if (this._originalValue[index] !== undefined) {
  50925. this._setValue(target, this._originalValue[index], -1);
  50926. }
  50927. index++;
  50928. }
  50929. }
  50930. else {
  50931. if (this._originalValue[0] !== undefined) {
  50932. this._setValue(this._target, this._originalValue[0], -1);
  50933. }
  50934. }
  50935. }
  50936. this._offsetsCache = {};
  50937. this._highLimitsCache = {};
  50938. this._currentFrame = 0;
  50939. this._blendingFactor = 0;
  50940. this._originalValue = new Array();
  50941. // Events
  50942. for (var index = 0; index < this._events.length; index++) {
  50943. this._events[index].isDone = false;
  50944. }
  50945. };
  50946. /**
  50947. * Specifies if the runtime animation is stopped
  50948. * @returns Boolean specifying if the runtime animation is stopped
  50949. */
  50950. RuntimeAnimation.prototype.isStopped = function () {
  50951. return this._stopped;
  50952. };
  50953. /**
  50954. * Disposes of the runtime animation
  50955. */
  50956. RuntimeAnimation.prototype.dispose = function () {
  50957. var index = this._animation.runtimeAnimations.indexOf(this);
  50958. if (index > -1) {
  50959. this._animation.runtimeAnimations.splice(index, 1);
  50960. }
  50961. };
  50962. /**
  50963. * Interpolates the animation from the current frame
  50964. * @param currentFrame The frame to interpolate the animation to
  50965. * @param repeatCount The number of times that the animation should loop
  50966. * @param loopMode The type of looping mode to use
  50967. * @param offsetValue Animation offset value
  50968. * @param highLimitValue The high limit value
  50969. * @returns The interpolated value
  50970. */
  50971. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50972. this._currentFrame = currentFrame;
  50973. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50974. this._workValue = BABYLON.Matrix.Zero();
  50975. }
  50976. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50977. };
  50978. /**
  50979. * Apply the interpolated value to the target
  50980. * @param currentValue defines the value computed by the animation
  50981. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50982. */
  50983. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50984. if (weight === void 0) { weight = 1.0; }
  50985. if (this._target instanceof Array) {
  50986. var index = 0;
  50987. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50988. var target = _a[_i];
  50989. this._setValue(target, currentValue, weight, index);
  50990. index++;
  50991. }
  50992. }
  50993. else {
  50994. this._setValue(this._target, currentValue, weight);
  50995. }
  50996. };
  50997. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50998. if (targetIndex === void 0) { targetIndex = 0; }
  50999. // Set value
  51000. var path;
  51001. var destination;
  51002. var targetPropertyPath = this._animation.targetPropertyPath;
  51003. if (targetPropertyPath.length > 1) {
  51004. var property = target[targetPropertyPath[0]];
  51005. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51006. property = property[targetPropertyPath[index]];
  51007. }
  51008. path = targetPropertyPath[targetPropertyPath.length - 1];
  51009. destination = property;
  51010. }
  51011. else {
  51012. path = targetPropertyPath[0];
  51013. destination = target;
  51014. }
  51015. this._targetPath = path;
  51016. this._activeTarget = destination;
  51017. this._weight = weight;
  51018. if (this._originalValue[targetIndex] === undefined) {
  51019. var originalValue = void 0;
  51020. if (destination.getRestPose && path === "_matrix") { // For bones
  51021. originalValue = destination.getRestPose();
  51022. }
  51023. else {
  51024. originalValue = destination[path];
  51025. }
  51026. if (originalValue && originalValue.clone) {
  51027. this._originalValue[targetIndex] = originalValue.clone();
  51028. }
  51029. else {
  51030. this._originalValue[targetIndex] = originalValue;
  51031. }
  51032. }
  51033. // Blending
  51034. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51035. if (enableBlending && this._blendingFactor <= 1.0) {
  51036. if (!this._originalBlendValue) {
  51037. var originalValue = destination[path];
  51038. if (originalValue.clone) {
  51039. this._originalBlendValue = originalValue.clone();
  51040. }
  51041. else {
  51042. this._originalBlendValue = originalValue;
  51043. }
  51044. }
  51045. if (this._originalBlendValue.m) { // Matrix
  51046. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51047. if (this._currentValue) {
  51048. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51049. }
  51050. else {
  51051. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51052. }
  51053. }
  51054. else {
  51055. if (this._currentValue) {
  51056. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51057. }
  51058. else {
  51059. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51060. }
  51061. }
  51062. }
  51063. else {
  51064. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51065. }
  51066. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51067. this._blendingFactor += blendingSpeed;
  51068. }
  51069. else {
  51070. this._currentValue = currentValue;
  51071. }
  51072. if (weight !== -1.0) {
  51073. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51074. }
  51075. else {
  51076. destination[path] = this._currentValue;
  51077. }
  51078. if (target.markAsDirty) {
  51079. target.markAsDirty(this._animation.targetProperty);
  51080. }
  51081. };
  51082. /**
  51083. * Gets the loop pmode of the runtime animation
  51084. * @returns Loop Mode
  51085. */
  51086. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51087. if (this._target && this._target.animationPropertiesOverride) {
  51088. return this._target.animationPropertiesOverride.loopMode;
  51089. }
  51090. return this._animation.loopMode;
  51091. };
  51092. /**
  51093. * Move the current animation to a given frame
  51094. * @param frame defines the frame to move to
  51095. */
  51096. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51097. var keys = this._animation.getKeys();
  51098. if (frame < keys[0].frame) {
  51099. frame = keys[0].frame;
  51100. }
  51101. else if (frame > keys[keys.length - 1].frame) {
  51102. frame = keys[keys.length - 1].frame;
  51103. }
  51104. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51105. this.setValue(currentValue, -1);
  51106. };
  51107. /**
  51108. * @hidden Internal use only
  51109. */
  51110. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51111. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51112. this._ratioOffset = this._previousRatio - newRatio;
  51113. };
  51114. /**
  51115. * Execute the current animation
  51116. * @param delay defines the delay to add to the current frame
  51117. * @param from defines the lower bound of the animation range
  51118. * @param to defines the upper bound of the animation range
  51119. * @param loop defines if the current animation must loop
  51120. * @param speedRatio defines the current speed ratio
  51121. * @param weight defines the weight of the animation (default is -1 so no weight)
  51122. * @returns a boolean indicating if the animation has ended
  51123. */
  51124. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51125. if (weight === void 0) { weight = -1.0; }
  51126. var targetPropertyPath = this._animation.targetPropertyPath;
  51127. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51128. this._stopped = true;
  51129. return false;
  51130. }
  51131. var returnValue = true;
  51132. var keys = this._animation.getKeys();
  51133. // Adding a start key at frame 0 if missing
  51134. if (keys[0].frame !== 0) {
  51135. var newKey = { frame: 0, value: keys[0].value };
  51136. keys.splice(0, 0, newKey);
  51137. }
  51138. // Check limits
  51139. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51140. from = keys[0].frame;
  51141. }
  51142. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51143. to = keys[keys.length - 1].frame;
  51144. }
  51145. //to and from cannot be the same key
  51146. if (from === to) {
  51147. if (from > keys[0].frame) {
  51148. from--;
  51149. }
  51150. else if (to < keys[keys.length - 1].frame) {
  51151. to++;
  51152. }
  51153. }
  51154. // Compute ratio
  51155. var range = to - from;
  51156. var offsetValue;
  51157. // ratio represents the frame delta between from and to
  51158. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51159. var highLimitValue = 0;
  51160. this._previousDelay = delay;
  51161. this._previousRatio = ratio;
  51162. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51163. returnValue = false;
  51164. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51165. }
  51166. else {
  51167. // Get max value if required
  51168. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51169. var keyOffset = to.toString() + from.toString();
  51170. if (!this._offsetsCache[keyOffset]) {
  51171. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51172. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51173. switch (this._animation.dataType) {
  51174. // Float
  51175. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51176. this._offsetsCache[keyOffset] = toValue - fromValue;
  51177. break;
  51178. // Quaternion
  51179. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51181. break;
  51182. // Vector3
  51183. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51184. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51185. // Vector2
  51186. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51187. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51188. // Size
  51189. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51190. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51191. // Color3
  51192. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51193. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51194. default:
  51195. break;
  51196. }
  51197. this._highLimitsCache[keyOffset] = toValue;
  51198. }
  51199. highLimitValue = this._highLimitsCache[keyOffset];
  51200. offsetValue = this._offsetsCache[keyOffset];
  51201. }
  51202. }
  51203. if (offsetValue === undefined) {
  51204. switch (this._animation.dataType) {
  51205. // Float
  51206. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51207. offsetValue = 0;
  51208. break;
  51209. // Quaternion
  51210. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51211. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51212. break;
  51213. // Vector3
  51214. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51215. offsetValue = BABYLON.Vector3.Zero();
  51216. break;
  51217. // Vector2
  51218. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51219. offsetValue = BABYLON.Vector2.Zero();
  51220. break;
  51221. // Size
  51222. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51223. offsetValue = BABYLON.Size.Zero();
  51224. break;
  51225. // Color3
  51226. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51227. offsetValue = BABYLON.Color3.Black();
  51228. }
  51229. }
  51230. // Compute value
  51231. var repeatCount = (ratio / range) >> 0;
  51232. var currentFrame = returnValue ? from + ratio % range : to;
  51233. // Need to normalize?
  51234. if (this._host && this._host.syncRoot) {
  51235. var syncRoot = this._host.syncRoot;
  51236. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51237. currentFrame = from + (to - from) * hostNormalizedFrame;
  51238. }
  51239. // Reset events if looping
  51240. var events = this._events;
  51241. if (range > 0 && this.currentFrame > currentFrame ||
  51242. range < 0 && this.currentFrame < currentFrame) {
  51243. // Need to reset animation events
  51244. for (var index = 0; index < events.length; index++) {
  51245. if (!events[index].onlyOnce) {
  51246. // reset event, the animation is looping
  51247. events[index].isDone = false;
  51248. }
  51249. }
  51250. }
  51251. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51252. // Set value
  51253. this.setValue(currentValue, weight);
  51254. // Check events
  51255. for (var index = 0; index < events.length; index++) {
  51256. // Make sure current frame has passed event frame and that event frame is within the current range
  51257. // Also, handle both forward and reverse animations
  51258. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51259. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51260. var event = events[index];
  51261. if (!event.isDone) {
  51262. // If event should be done only once, remove it.
  51263. if (event.onlyOnce) {
  51264. events.splice(index, 1);
  51265. index--;
  51266. }
  51267. event.isDone = true;
  51268. event.action();
  51269. } // Don't do anything if the event has already be done.
  51270. }
  51271. }
  51272. if (!returnValue) {
  51273. this._stopped = true;
  51274. }
  51275. return returnValue;
  51276. };
  51277. return RuntimeAnimation;
  51278. }());
  51279. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51280. })(BABYLON || (BABYLON = {}));
  51281. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51282. var BABYLON;
  51283. (function (BABYLON) {
  51284. var Animatable = /** @class */ (function () {
  51285. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51286. if (fromFrame === void 0) { fromFrame = 0; }
  51287. if (toFrame === void 0) { toFrame = 100; }
  51288. if (loopAnimation === void 0) { loopAnimation = false; }
  51289. if (speedRatio === void 0) { speedRatio = 1.0; }
  51290. this.target = target;
  51291. this.fromFrame = fromFrame;
  51292. this.toFrame = toFrame;
  51293. this.loopAnimation = loopAnimation;
  51294. this.onAnimationEnd = onAnimationEnd;
  51295. this._localDelayOffset = null;
  51296. this._pausedDelay = null;
  51297. this._runtimeAnimations = new Array();
  51298. this._paused = false;
  51299. this._speedRatio = 1;
  51300. this._weight = -1.0;
  51301. this.animationStarted = false;
  51302. /**
  51303. * Observer raised when the animation ends
  51304. */
  51305. this.onAnimationEndObservable = new BABYLON.Observable();
  51306. this._scene = scene;
  51307. if (animations) {
  51308. this.appendAnimations(target, animations);
  51309. }
  51310. this._speedRatio = speedRatio;
  51311. scene._activeAnimatables.push(this);
  51312. }
  51313. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51314. /**
  51315. * Gets the root Animatable used to synchronize and normalize animations
  51316. */
  51317. get: function () {
  51318. return this._syncRoot;
  51319. },
  51320. enumerable: true,
  51321. configurable: true
  51322. });
  51323. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51324. /**
  51325. * Gets the current frame of the first RuntimeAnimation
  51326. * Used to synchronize Animatables
  51327. */
  51328. get: function () {
  51329. if (this._runtimeAnimations.length === 0) {
  51330. return 0;
  51331. }
  51332. return this._runtimeAnimations[0].currentFrame;
  51333. },
  51334. enumerable: true,
  51335. configurable: true
  51336. });
  51337. Object.defineProperty(Animatable.prototype, "weight", {
  51338. /**
  51339. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51340. */
  51341. get: function () {
  51342. return this._weight;
  51343. },
  51344. set: function (value) {
  51345. if (value === -1) { // -1 is ok and means no weight
  51346. this._weight = -1;
  51347. return;
  51348. }
  51349. // Else weight must be in [0, 1] range
  51350. this._weight = Math.min(Math.max(value, 0), 1.0);
  51351. },
  51352. enumerable: true,
  51353. configurable: true
  51354. });
  51355. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51356. /**
  51357. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51358. */
  51359. get: function () {
  51360. return this._speedRatio;
  51361. },
  51362. set: function (value) {
  51363. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51364. var animation = this._runtimeAnimations[index];
  51365. animation._prepareForSpeedRatioChange(value);
  51366. }
  51367. this._speedRatio = value;
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. // Methods
  51373. /**
  51374. * Synchronize and normalize current Animatable with a source Animatable
  51375. * This is useful when using animation weights and when animations are not of the same length
  51376. * @param root defines the root Animatable to synchronize with
  51377. * @returns the current Animatable
  51378. */
  51379. Animatable.prototype.syncWith = function (root) {
  51380. this._syncRoot = root;
  51381. if (root) {
  51382. // Make sure this animatable will animate after the root
  51383. var index = this._scene._activeAnimatables.indexOf(this);
  51384. if (index > -1) {
  51385. this._scene._activeAnimatables.splice(index, 1);
  51386. this._scene._activeAnimatables.push(this);
  51387. }
  51388. }
  51389. return this;
  51390. };
  51391. Animatable.prototype.getAnimations = function () {
  51392. return this._runtimeAnimations;
  51393. };
  51394. Animatable.prototype.appendAnimations = function (target, animations) {
  51395. for (var index = 0; index < animations.length; index++) {
  51396. var animation = animations[index];
  51397. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51398. }
  51399. };
  51400. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51401. var runtimeAnimations = this._runtimeAnimations;
  51402. for (var index = 0; index < runtimeAnimations.length; index++) {
  51403. if (runtimeAnimations[index].animation.targetProperty === property) {
  51404. return runtimeAnimations[index].animation;
  51405. }
  51406. }
  51407. return null;
  51408. };
  51409. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51410. var runtimeAnimations = this._runtimeAnimations;
  51411. for (var index = 0; index < runtimeAnimations.length; index++) {
  51412. if (runtimeAnimations[index].animation.targetProperty === property) {
  51413. return runtimeAnimations[index];
  51414. }
  51415. }
  51416. return null;
  51417. };
  51418. Animatable.prototype.reset = function () {
  51419. var runtimeAnimations = this._runtimeAnimations;
  51420. for (var index = 0; index < runtimeAnimations.length; index++) {
  51421. runtimeAnimations[index].reset(true);
  51422. }
  51423. this._localDelayOffset = null;
  51424. this._pausedDelay = null;
  51425. };
  51426. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51427. var runtimeAnimations = this._runtimeAnimations;
  51428. for (var index = 0; index < runtimeAnimations.length; index++) {
  51429. runtimeAnimations[index].animation.enableBlending = true;
  51430. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51431. }
  51432. };
  51433. Animatable.prototype.disableBlending = function () {
  51434. var runtimeAnimations = this._runtimeAnimations;
  51435. for (var index = 0; index < runtimeAnimations.length; index++) {
  51436. runtimeAnimations[index].animation.enableBlending = false;
  51437. }
  51438. };
  51439. Animatable.prototype.goToFrame = function (frame) {
  51440. var runtimeAnimations = this._runtimeAnimations;
  51441. if (runtimeAnimations[0]) {
  51442. var fps = runtimeAnimations[0].animation.framePerSecond;
  51443. var currentFrame = runtimeAnimations[0].currentFrame;
  51444. var adjustTime = frame - currentFrame;
  51445. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51446. if (this._localDelayOffset === null) {
  51447. this._localDelayOffset = 0;
  51448. }
  51449. this._localDelayOffset -= delay;
  51450. }
  51451. for (var index = 0; index < runtimeAnimations.length; index++) {
  51452. runtimeAnimations[index].goToFrame(frame);
  51453. }
  51454. };
  51455. Animatable.prototype.pause = function () {
  51456. if (this._paused) {
  51457. return;
  51458. }
  51459. this._paused = true;
  51460. };
  51461. Animatable.prototype.restart = function () {
  51462. this._paused = false;
  51463. };
  51464. Animatable.prototype._raiseOnAnimationEnd = function () {
  51465. if (this.onAnimationEnd) {
  51466. this.onAnimationEnd();
  51467. }
  51468. this.onAnimationEndObservable.notifyObservers(this);
  51469. };
  51470. Animatable.prototype.stop = function (animationName) {
  51471. if (animationName) {
  51472. var idx = this._scene._activeAnimatables.indexOf(this);
  51473. if (idx > -1) {
  51474. var runtimeAnimations = this._runtimeAnimations;
  51475. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51476. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51477. continue;
  51478. }
  51479. runtimeAnimations[index].dispose();
  51480. runtimeAnimations.splice(index, 1);
  51481. }
  51482. if (runtimeAnimations.length == 0) {
  51483. this._scene._activeAnimatables.splice(idx, 1);
  51484. this._raiseOnAnimationEnd();
  51485. }
  51486. }
  51487. }
  51488. else {
  51489. var index = this._scene._activeAnimatables.indexOf(this);
  51490. if (index > -1) {
  51491. this._scene._activeAnimatables.splice(index, 1);
  51492. var runtimeAnimations = this._runtimeAnimations;
  51493. for (var index = 0; index < runtimeAnimations.length; index++) {
  51494. runtimeAnimations[index].dispose();
  51495. }
  51496. this._raiseOnAnimationEnd();
  51497. }
  51498. }
  51499. };
  51500. /**
  51501. * Wait asynchronously for the animation to end
  51502. * @returns a promise which will be fullfilled when the animation ends
  51503. */
  51504. Animatable.prototype.waitAsync = function () {
  51505. var _this = this;
  51506. return new Promise(function (resolve, reject) {
  51507. _this.onAnimationEndObservable.add(function () {
  51508. resolve(_this);
  51509. }, undefined, undefined, _this, true);
  51510. });
  51511. };
  51512. /** @hidden */
  51513. Animatable.prototype._animate = function (delay) {
  51514. if (this._paused) {
  51515. this.animationStarted = false;
  51516. if (this._pausedDelay === null) {
  51517. this._pausedDelay = delay;
  51518. }
  51519. return true;
  51520. }
  51521. if (this._localDelayOffset === null) {
  51522. this._localDelayOffset = delay;
  51523. this._pausedDelay = null;
  51524. }
  51525. else if (this._pausedDelay !== null) {
  51526. this._localDelayOffset += delay - this._pausedDelay;
  51527. this._pausedDelay = null;
  51528. }
  51529. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51530. return true;
  51531. }
  51532. // Animating
  51533. var running = false;
  51534. var runtimeAnimations = this._runtimeAnimations;
  51535. var index;
  51536. for (index = 0; index < runtimeAnimations.length; index++) {
  51537. var animation = runtimeAnimations[index];
  51538. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51539. running = running || isRunning;
  51540. }
  51541. this.animationStarted = running;
  51542. if (!running) {
  51543. // Remove from active animatables
  51544. index = this._scene._activeAnimatables.indexOf(this);
  51545. this._scene._activeAnimatables.splice(index, 1);
  51546. // Dispose all runtime animations
  51547. for (index = 0; index < runtimeAnimations.length; index++) {
  51548. runtimeAnimations[index].dispose();
  51549. }
  51550. this._raiseOnAnimationEnd();
  51551. this.onAnimationEnd = null;
  51552. this.onAnimationEndObservable.clear();
  51553. }
  51554. return running;
  51555. };
  51556. return Animatable;
  51557. }());
  51558. BABYLON.Animatable = Animatable;
  51559. })(BABYLON || (BABYLON = {}));
  51560. //# sourceMappingURL=babylon.animatable.js.map
  51561. var BABYLON;
  51562. (function (BABYLON) {
  51563. var EasingFunction = /** @class */ (function () {
  51564. function EasingFunction() {
  51565. // Properties
  51566. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51567. }
  51568. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51569. get: function () {
  51570. return EasingFunction._EASINGMODE_EASEIN;
  51571. },
  51572. enumerable: true,
  51573. configurable: true
  51574. });
  51575. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51576. get: function () {
  51577. return EasingFunction._EASINGMODE_EASEOUT;
  51578. },
  51579. enumerable: true,
  51580. configurable: true
  51581. });
  51582. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51583. get: function () {
  51584. return EasingFunction._EASINGMODE_EASEINOUT;
  51585. },
  51586. enumerable: true,
  51587. configurable: true
  51588. });
  51589. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51590. var n = Math.min(Math.max(easingMode, 0), 2);
  51591. this._easingMode = n;
  51592. };
  51593. EasingFunction.prototype.getEasingMode = function () {
  51594. return this._easingMode;
  51595. };
  51596. EasingFunction.prototype.easeInCore = function (gradient) {
  51597. throw new Error('You must implement this method');
  51598. };
  51599. EasingFunction.prototype.ease = function (gradient) {
  51600. switch (this._easingMode) {
  51601. case EasingFunction.EASINGMODE_EASEIN:
  51602. return this.easeInCore(gradient);
  51603. case EasingFunction.EASINGMODE_EASEOUT:
  51604. return (1 - this.easeInCore(1 - gradient));
  51605. }
  51606. if (gradient >= 0.5) {
  51607. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51608. }
  51609. return (this.easeInCore(gradient * 2) * 0.5);
  51610. };
  51611. //Statics
  51612. EasingFunction._EASINGMODE_EASEIN = 0;
  51613. EasingFunction._EASINGMODE_EASEOUT = 1;
  51614. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51615. return EasingFunction;
  51616. }());
  51617. BABYLON.EasingFunction = EasingFunction;
  51618. var CircleEase = /** @class */ (function (_super) {
  51619. __extends(CircleEase, _super);
  51620. function CircleEase() {
  51621. return _super !== null && _super.apply(this, arguments) || this;
  51622. }
  51623. CircleEase.prototype.easeInCore = function (gradient) {
  51624. gradient = Math.max(0, Math.min(1, gradient));
  51625. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51626. };
  51627. return CircleEase;
  51628. }(EasingFunction));
  51629. BABYLON.CircleEase = CircleEase;
  51630. var BackEase = /** @class */ (function (_super) {
  51631. __extends(BackEase, _super);
  51632. function BackEase(amplitude) {
  51633. if (amplitude === void 0) { amplitude = 1; }
  51634. var _this = _super.call(this) || this;
  51635. _this.amplitude = amplitude;
  51636. return _this;
  51637. }
  51638. BackEase.prototype.easeInCore = function (gradient) {
  51639. var num = Math.max(0, this.amplitude);
  51640. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51641. };
  51642. return BackEase;
  51643. }(EasingFunction));
  51644. BABYLON.BackEase = BackEase;
  51645. var BounceEase = /** @class */ (function (_super) {
  51646. __extends(BounceEase, _super);
  51647. function BounceEase(bounces, bounciness) {
  51648. if (bounces === void 0) { bounces = 3; }
  51649. if (bounciness === void 0) { bounciness = 2; }
  51650. var _this = _super.call(this) || this;
  51651. _this.bounces = bounces;
  51652. _this.bounciness = bounciness;
  51653. return _this;
  51654. }
  51655. BounceEase.prototype.easeInCore = function (gradient) {
  51656. var y = Math.max(0.0, this.bounces);
  51657. var bounciness = this.bounciness;
  51658. if (bounciness <= 1.0) {
  51659. bounciness = 1.001;
  51660. }
  51661. var num9 = Math.pow(bounciness, y);
  51662. var num5 = 1.0 - bounciness;
  51663. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51664. var num15 = gradient * num4;
  51665. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51666. var num3 = Math.floor(num65);
  51667. var num13 = num3 + 1.0;
  51668. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51669. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51670. var num7 = (num8 + num12) * 0.5;
  51671. var num6 = gradient - num7;
  51672. var num2 = num7 - num8;
  51673. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51674. };
  51675. return BounceEase;
  51676. }(EasingFunction));
  51677. BABYLON.BounceEase = BounceEase;
  51678. var CubicEase = /** @class */ (function (_super) {
  51679. __extends(CubicEase, _super);
  51680. function CubicEase() {
  51681. return _super !== null && _super.apply(this, arguments) || this;
  51682. }
  51683. CubicEase.prototype.easeInCore = function (gradient) {
  51684. return (gradient * gradient * gradient);
  51685. };
  51686. return CubicEase;
  51687. }(EasingFunction));
  51688. BABYLON.CubicEase = CubicEase;
  51689. var ElasticEase = /** @class */ (function (_super) {
  51690. __extends(ElasticEase, _super);
  51691. function ElasticEase(oscillations, springiness) {
  51692. if (oscillations === void 0) { oscillations = 3; }
  51693. if (springiness === void 0) { springiness = 3; }
  51694. var _this = _super.call(this) || this;
  51695. _this.oscillations = oscillations;
  51696. _this.springiness = springiness;
  51697. return _this;
  51698. }
  51699. ElasticEase.prototype.easeInCore = function (gradient) {
  51700. var num2;
  51701. var num3 = Math.max(0.0, this.oscillations);
  51702. var num = Math.max(0.0, this.springiness);
  51703. if (num == 0) {
  51704. num2 = gradient;
  51705. }
  51706. else {
  51707. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51708. }
  51709. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51710. };
  51711. return ElasticEase;
  51712. }(EasingFunction));
  51713. BABYLON.ElasticEase = ElasticEase;
  51714. var ExponentialEase = /** @class */ (function (_super) {
  51715. __extends(ExponentialEase, _super);
  51716. function ExponentialEase(exponent) {
  51717. if (exponent === void 0) { exponent = 2; }
  51718. var _this = _super.call(this) || this;
  51719. _this.exponent = exponent;
  51720. return _this;
  51721. }
  51722. ExponentialEase.prototype.easeInCore = function (gradient) {
  51723. if (this.exponent <= 0) {
  51724. return gradient;
  51725. }
  51726. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51727. };
  51728. return ExponentialEase;
  51729. }(EasingFunction));
  51730. BABYLON.ExponentialEase = ExponentialEase;
  51731. var PowerEase = /** @class */ (function (_super) {
  51732. __extends(PowerEase, _super);
  51733. function PowerEase(power) {
  51734. if (power === void 0) { power = 2; }
  51735. var _this = _super.call(this) || this;
  51736. _this.power = power;
  51737. return _this;
  51738. }
  51739. PowerEase.prototype.easeInCore = function (gradient) {
  51740. var y = Math.max(0.0, this.power);
  51741. return Math.pow(gradient, y);
  51742. };
  51743. return PowerEase;
  51744. }(EasingFunction));
  51745. BABYLON.PowerEase = PowerEase;
  51746. var QuadraticEase = /** @class */ (function (_super) {
  51747. __extends(QuadraticEase, _super);
  51748. function QuadraticEase() {
  51749. return _super !== null && _super.apply(this, arguments) || this;
  51750. }
  51751. QuadraticEase.prototype.easeInCore = function (gradient) {
  51752. return (gradient * gradient);
  51753. };
  51754. return QuadraticEase;
  51755. }(EasingFunction));
  51756. BABYLON.QuadraticEase = QuadraticEase;
  51757. var QuarticEase = /** @class */ (function (_super) {
  51758. __extends(QuarticEase, _super);
  51759. function QuarticEase() {
  51760. return _super !== null && _super.apply(this, arguments) || this;
  51761. }
  51762. QuarticEase.prototype.easeInCore = function (gradient) {
  51763. return (gradient * gradient * gradient * gradient);
  51764. };
  51765. return QuarticEase;
  51766. }(EasingFunction));
  51767. BABYLON.QuarticEase = QuarticEase;
  51768. var QuinticEase = /** @class */ (function (_super) {
  51769. __extends(QuinticEase, _super);
  51770. function QuinticEase() {
  51771. return _super !== null && _super.apply(this, arguments) || this;
  51772. }
  51773. QuinticEase.prototype.easeInCore = function (gradient) {
  51774. return (gradient * gradient * gradient * gradient * gradient);
  51775. };
  51776. return QuinticEase;
  51777. }(EasingFunction));
  51778. BABYLON.QuinticEase = QuinticEase;
  51779. var SineEase = /** @class */ (function (_super) {
  51780. __extends(SineEase, _super);
  51781. function SineEase() {
  51782. return _super !== null && _super.apply(this, arguments) || this;
  51783. }
  51784. SineEase.prototype.easeInCore = function (gradient) {
  51785. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51786. };
  51787. return SineEase;
  51788. }(EasingFunction));
  51789. BABYLON.SineEase = SineEase;
  51790. var BezierCurveEase = /** @class */ (function (_super) {
  51791. __extends(BezierCurveEase, _super);
  51792. function BezierCurveEase(x1, y1, x2, y2) {
  51793. if (x1 === void 0) { x1 = 0; }
  51794. if (y1 === void 0) { y1 = 0; }
  51795. if (x2 === void 0) { x2 = 1; }
  51796. if (y2 === void 0) { y2 = 1; }
  51797. var _this = _super.call(this) || this;
  51798. _this.x1 = x1;
  51799. _this.y1 = y1;
  51800. _this.x2 = x2;
  51801. _this.y2 = y2;
  51802. return _this;
  51803. }
  51804. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51805. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51806. };
  51807. return BezierCurveEase;
  51808. }(EasingFunction));
  51809. BABYLON.BezierCurveEase = BezierCurveEase;
  51810. })(BABYLON || (BABYLON = {}));
  51811. //# sourceMappingURL=babylon.easing.js.map
  51812. var BABYLON;
  51813. (function (BABYLON) {
  51814. /**
  51815. * A Condition applied to an Action
  51816. */
  51817. var Condition = /** @class */ (function () {
  51818. /**
  51819. * Creates a new Condition
  51820. * @param actionManager the manager of the action the condition is applied to
  51821. */
  51822. function Condition(actionManager) {
  51823. this._actionManager = actionManager;
  51824. }
  51825. /**
  51826. * Check if the current condition is valid
  51827. * @returns a boolean
  51828. */
  51829. Condition.prototype.isValid = function () {
  51830. return true;
  51831. };
  51832. /**
  51833. * Internal only
  51834. * @hidden
  51835. */
  51836. Condition.prototype._getProperty = function (propertyPath) {
  51837. return this._actionManager._getProperty(propertyPath);
  51838. };
  51839. /**
  51840. * Internal only
  51841. * @hidden
  51842. */
  51843. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51844. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51845. };
  51846. /**
  51847. * Serialize placeholder for child classes
  51848. * @returns the serialized object
  51849. */
  51850. Condition.prototype.serialize = function () {
  51851. };
  51852. /**
  51853. * Internal only
  51854. * @hidden
  51855. */
  51856. Condition.prototype._serialize = function (serializedCondition) {
  51857. return {
  51858. type: 2,
  51859. children: [],
  51860. name: serializedCondition.name,
  51861. properties: serializedCondition.properties
  51862. };
  51863. };
  51864. return Condition;
  51865. }());
  51866. BABYLON.Condition = Condition;
  51867. /**
  51868. * Defines specific conditional operators as extensions of Condition
  51869. */
  51870. var ValueCondition = /** @class */ (function (_super) {
  51871. __extends(ValueCondition, _super);
  51872. /**
  51873. * Creates a new ValueCondition
  51874. * @param actionManager manager for the action the condition applies to
  51875. * @param target for the action
  51876. * @param propertyPath path to specify the property of the target the conditional operator uses
  51877. * @param value the value compared by the conditional operator against the current value of the property
  51878. * @param operator the conditional operator, default ValueCondition.IsEqual
  51879. */
  51880. function ValueCondition(actionManager, target,
  51881. /** path to specify the property of the target the conditional operator uses */
  51882. propertyPath,
  51883. /** the value compared by the conditional operator against the current value of the property */
  51884. value,
  51885. /** the conditional operator, default ValueCondition.IsEqual */
  51886. operator) {
  51887. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51888. var _this = _super.call(this, actionManager) || this;
  51889. _this.propertyPath = propertyPath;
  51890. _this.value = value;
  51891. _this.operator = operator;
  51892. _this._target = target;
  51893. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51894. _this._property = _this._getProperty(_this.propertyPath);
  51895. return _this;
  51896. }
  51897. Object.defineProperty(ValueCondition, "IsEqual", {
  51898. /**
  51899. * returns the number for IsEqual
  51900. */
  51901. get: function () {
  51902. return ValueCondition._IsEqual;
  51903. },
  51904. enumerable: true,
  51905. configurable: true
  51906. });
  51907. Object.defineProperty(ValueCondition, "IsDifferent", {
  51908. /**
  51909. * Returns the number for IsDifferent
  51910. */
  51911. get: function () {
  51912. return ValueCondition._IsDifferent;
  51913. },
  51914. enumerable: true,
  51915. configurable: true
  51916. });
  51917. Object.defineProperty(ValueCondition, "IsGreater", {
  51918. /**
  51919. * Returns the number for IsGreater
  51920. */
  51921. get: function () {
  51922. return ValueCondition._IsGreater;
  51923. },
  51924. enumerable: true,
  51925. configurable: true
  51926. });
  51927. Object.defineProperty(ValueCondition, "IsLesser", {
  51928. /**
  51929. * Returns the number for IsLesser
  51930. */
  51931. get: function () {
  51932. return ValueCondition._IsLesser;
  51933. },
  51934. enumerable: true,
  51935. configurable: true
  51936. });
  51937. /**
  51938. * Compares the given value with the property value for the specified conditional operator
  51939. * @returns the result of the comparison
  51940. */
  51941. ValueCondition.prototype.isValid = function () {
  51942. switch (this.operator) {
  51943. case ValueCondition.IsGreater:
  51944. return this._effectiveTarget[this._property] > this.value;
  51945. case ValueCondition.IsLesser:
  51946. return this._effectiveTarget[this._property] < this.value;
  51947. case ValueCondition.IsEqual:
  51948. case ValueCondition.IsDifferent:
  51949. var check;
  51950. if (this.value.equals) {
  51951. check = this.value.equals(this._effectiveTarget[this._property]);
  51952. }
  51953. else {
  51954. check = this.value === this._effectiveTarget[this._property];
  51955. }
  51956. return this.operator === ValueCondition.IsEqual ? check : !check;
  51957. }
  51958. return false;
  51959. };
  51960. /**
  51961. * Serialize the ValueCondition into a JSON compatible object
  51962. * @returns serialization object
  51963. */
  51964. ValueCondition.prototype.serialize = function () {
  51965. return this._serialize({
  51966. name: "ValueCondition",
  51967. properties: [
  51968. BABYLON.Action._GetTargetProperty(this._target),
  51969. { name: "propertyPath", value: this.propertyPath },
  51970. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51971. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51972. ]
  51973. });
  51974. };
  51975. /**
  51976. * Gets the name of the conditional operator for the ValueCondition
  51977. * @param operator the conditional operator
  51978. * @returns the name
  51979. */
  51980. ValueCondition.GetOperatorName = function (operator) {
  51981. switch (operator) {
  51982. case ValueCondition._IsEqual: return "IsEqual";
  51983. case ValueCondition._IsDifferent: return "IsDifferent";
  51984. case ValueCondition._IsGreater: return "IsGreater";
  51985. case ValueCondition._IsLesser: return "IsLesser";
  51986. default: return "";
  51987. }
  51988. };
  51989. /**
  51990. * Internal only
  51991. * @hidden
  51992. */
  51993. ValueCondition._IsEqual = 0;
  51994. /**
  51995. * Internal only
  51996. * @hidden
  51997. */
  51998. ValueCondition._IsDifferent = 1;
  51999. /**
  52000. * Internal only
  52001. * @hidden
  52002. */
  52003. ValueCondition._IsGreater = 2;
  52004. /**
  52005. * Internal only
  52006. * @hidden
  52007. */
  52008. ValueCondition._IsLesser = 3;
  52009. return ValueCondition;
  52010. }(Condition));
  52011. BABYLON.ValueCondition = ValueCondition;
  52012. /**
  52013. * Defines a predicate condition as an extension of Condition
  52014. */
  52015. var PredicateCondition = /** @class */ (function (_super) {
  52016. __extends(PredicateCondition, _super);
  52017. /**
  52018. * Creates a new PredicateCondition
  52019. * @param actionManager manager for the action the condition applies to
  52020. * @param predicate defines the predicate function used to validate the condition
  52021. */
  52022. function PredicateCondition(actionManager,
  52023. /** defines the predicate function used to validate the condition */
  52024. predicate) {
  52025. var _this = _super.call(this, actionManager) || this;
  52026. _this.predicate = predicate;
  52027. return _this;
  52028. }
  52029. /**
  52030. * @returns the validity of the predicate condition
  52031. */
  52032. PredicateCondition.prototype.isValid = function () {
  52033. return this.predicate();
  52034. };
  52035. return PredicateCondition;
  52036. }(Condition));
  52037. BABYLON.PredicateCondition = PredicateCondition;
  52038. /**
  52039. * Defines a state condition as an extension of Condition
  52040. */
  52041. var StateCondition = /** @class */ (function (_super) {
  52042. __extends(StateCondition, _super);
  52043. /**
  52044. * Creates a new StateCondition
  52045. * @param actionManager manager for the action the condition applies to
  52046. * @param target of the condition
  52047. * @param value to compare with target state
  52048. */
  52049. function StateCondition(actionManager, target, value) {
  52050. var _this = _super.call(this, actionManager) || this;
  52051. _this.value = value;
  52052. _this._target = target;
  52053. return _this;
  52054. }
  52055. /**
  52056. * @returns the validity of the state
  52057. */
  52058. StateCondition.prototype.isValid = function () {
  52059. return this._target.state === this.value;
  52060. };
  52061. /**
  52062. * Serialize the StateCondition into a JSON compatible object
  52063. * @returns serialization object
  52064. */
  52065. StateCondition.prototype.serialize = function () {
  52066. return this._serialize({
  52067. name: "StateCondition",
  52068. properties: [
  52069. BABYLON.Action._GetTargetProperty(this._target),
  52070. { name: "value", value: this.value }
  52071. ]
  52072. });
  52073. };
  52074. return StateCondition;
  52075. }(Condition));
  52076. BABYLON.StateCondition = StateCondition;
  52077. })(BABYLON || (BABYLON = {}));
  52078. //# sourceMappingURL=babylon.condition.js.map
  52079. var BABYLON;
  52080. (function (BABYLON) {
  52081. /**
  52082. * The action to be carried out following a trigger
  52083. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52084. */
  52085. var Action = /** @class */ (function () {
  52086. /**
  52087. * Creates a new Action
  52088. * @param triggerOptions the trigger, with or without parameters, for the action
  52089. * @param condition an optional determinant of action
  52090. */
  52091. function Action(
  52092. /** the trigger, with or without parameters, for the action */
  52093. triggerOptions, condition) {
  52094. this.triggerOptions = triggerOptions;
  52095. /**
  52096. * An event triggered prior to action being executed.
  52097. */
  52098. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52099. if (triggerOptions.parameter) {
  52100. this.trigger = triggerOptions.trigger;
  52101. this._triggerParameter = triggerOptions.parameter;
  52102. }
  52103. else {
  52104. this.trigger = triggerOptions;
  52105. }
  52106. this._nextActiveAction = this;
  52107. this._condition = condition;
  52108. }
  52109. /**
  52110. * Internal only
  52111. * @hidden
  52112. */
  52113. Action.prototype._prepare = function () {
  52114. };
  52115. /**
  52116. * Gets the trigger parameters
  52117. * @returns the trigger parameters
  52118. */
  52119. Action.prototype.getTriggerParameter = function () {
  52120. return this._triggerParameter;
  52121. };
  52122. /**
  52123. * Internal only - executes current action event
  52124. * @hidden
  52125. */
  52126. Action.prototype._executeCurrent = function (evt) {
  52127. if (this._nextActiveAction._condition) {
  52128. var condition = this._nextActiveAction._condition;
  52129. var currentRenderId = this._actionManager.getScene().getRenderId();
  52130. // We cache the current evaluation for the current frame
  52131. if (condition._evaluationId === currentRenderId) {
  52132. if (!condition._currentResult) {
  52133. return;
  52134. }
  52135. }
  52136. else {
  52137. condition._evaluationId = currentRenderId;
  52138. if (!condition.isValid()) {
  52139. condition._currentResult = false;
  52140. return;
  52141. }
  52142. condition._currentResult = true;
  52143. }
  52144. }
  52145. this.onBeforeExecuteObservable.notifyObservers(this);
  52146. this._nextActiveAction.execute(evt);
  52147. this.skipToNextActiveAction();
  52148. };
  52149. /**
  52150. * Execute placeholder for child classes
  52151. * @param evt optional action event
  52152. */
  52153. Action.prototype.execute = function (evt) {
  52154. };
  52155. /**
  52156. * Skips to next active action
  52157. */
  52158. Action.prototype.skipToNextActiveAction = function () {
  52159. if (this._nextActiveAction._child) {
  52160. if (!this._nextActiveAction._child._actionManager) {
  52161. this._nextActiveAction._child._actionManager = this._actionManager;
  52162. }
  52163. this._nextActiveAction = this._nextActiveAction._child;
  52164. }
  52165. else {
  52166. this._nextActiveAction = this;
  52167. }
  52168. };
  52169. /**
  52170. * Adds action to chain of actions, may be a DoNothingAction
  52171. * @param action defines the next action to execute
  52172. * @returns The action passed in
  52173. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52174. */
  52175. Action.prototype.then = function (action) {
  52176. this._child = action;
  52177. action._actionManager = this._actionManager;
  52178. action._prepare();
  52179. return action;
  52180. };
  52181. /**
  52182. * Internal only
  52183. * @hidden
  52184. */
  52185. Action.prototype._getProperty = function (propertyPath) {
  52186. return this._actionManager._getProperty(propertyPath);
  52187. };
  52188. /**
  52189. * Internal only
  52190. * @hidden
  52191. */
  52192. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52193. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52194. };
  52195. /**
  52196. * Serialize placeholder for child classes
  52197. * @param parent of child
  52198. * @returns the serialized object
  52199. */
  52200. Action.prototype.serialize = function (parent) {
  52201. };
  52202. /**
  52203. * Internal only called by serialize
  52204. * @hidden
  52205. */
  52206. Action.prototype._serialize = function (serializedAction, parent) {
  52207. var serializationObject = {
  52208. type: 1,
  52209. children: [],
  52210. name: serializedAction.name,
  52211. properties: serializedAction.properties || []
  52212. };
  52213. // Serialize child
  52214. if (this._child) {
  52215. this._child.serialize(serializationObject);
  52216. }
  52217. // Check if "this" has a condition
  52218. if (this._condition) {
  52219. var serializedCondition = this._condition.serialize();
  52220. serializedCondition.children.push(serializationObject);
  52221. if (parent) {
  52222. parent.children.push(serializedCondition);
  52223. }
  52224. return serializedCondition;
  52225. }
  52226. if (parent) {
  52227. parent.children.push(serializationObject);
  52228. }
  52229. return serializationObject;
  52230. };
  52231. /**
  52232. * Internal only
  52233. * @hidden
  52234. */
  52235. Action._SerializeValueAsString = function (value) {
  52236. if (typeof value === "number") {
  52237. return value.toString();
  52238. }
  52239. if (typeof value === "boolean") {
  52240. return value ? "true" : "false";
  52241. }
  52242. if (value instanceof BABYLON.Vector2) {
  52243. return value.x + ", " + value.y;
  52244. }
  52245. if (value instanceof BABYLON.Vector3) {
  52246. return value.x + ", " + value.y + ", " + value.z;
  52247. }
  52248. if (value instanceof BABYLON.Color3) {
  52249. return value.r + ", " + value.g + ", " + value.b;
  52250. }
  52251. if (value instanceof BABYLON.Color4) {
  52252. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52253. }
  52254. return value; // string
  52255. };
  52256. /**
  52257. * Internal only
  52258. * @hidden
  52259. */
  52260. Action._GetTargetProperty = function (target) {
  52261. return {
  52262. name: "target",
  52263. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52264. : target instanceof BABYLON.Light ? "LightProperties"
  52265. : target instanceof BABYLON.Camera ? "CameraProperties"
  52266. : "SceneProperties",
  52267. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52268. };
  52269. };
  52270. return Action;
  52271. }());
  52272. BABYLON.Action = Action;
  52273. })(BABYLON || (BABYLON = {}));
  52274. //# sourceMappingURL=babylon.action.js.map
  52275. var BABYLON;
  52276. (function (BABYLON) {
  52277. /**
  52278. * ActionEvent is the event being sent when an action is triggered.
  52279. */
  52280. var ActionEvent = /** @class */ (function () {
  52281. /**
  52282. * Creates a new ActionEvent
  52283. * @param source The mesh or sprite that triggered the action
  52284. * @param pointerX The X mouse cursor position at the time of the event
  52285. * @param pointerY The Y mouse cursor position at the time of the event
  52286. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52287. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52288. * @param additionalData additional data for the event
  52289. */
  52290. function ActionEvent(
  52291. /** The mesh or sprite that triggered the action */
  52292. source,
  52293. /** The X mouse cursor position at the time of the event */
  52294. pointerX,
  52295. /** The Y mouse cursor position at the time of the event */
  52296. pointerY,
  52297. /** The mesh that is currently pointed at (can be null) */
  52298. meshUnderPointer,
  52299. /** the original (browser) event that triggered the ActionEvent */
  52300. sourceEvent,
  52301. /** additional data for the event */
  52302. additionalData) {
  52303. this.source = source;
  52304. this.pointerX = pointerX;
  52305. this.pointerY = pointerY;
  52306. this.meshUnderPointer = meshUnderPointer;
  52307. this.sourceEvent = sourceEvent;
  52308. this.additionalData = additionalData;
  52309. }
  52310. /**
  52311. * Helper function to auto-create an ActionEvent from a source mesh.
  52312. * @param source The source mesh that triggered the event
  52313. * @param evt The original (browser) event
  52314. * @param additionalData additional data for the event
  52315. * @returns the new ActionEvent
  52316. */
  52317. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52318. var scene = source.getScene();
  52319. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52320. };
  52321. /**
  52322. * Helper function to auto-create an ActionEvent from a source sprite
  52323. * @param source The source sprite that triggered the event
  52324. * @param scene Scene associated with the sprite
  52325. * @param evt The original (browser) event
  52326. * @param additionalData additional data for the event
  52327. * @returns the new ActionEvent
  52328. */
  52329. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52330. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52331. };
  52332. /**
  52333. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52334. * @param scene the scene where the event occurred
  52335. * @param evt The original (browser) event
  52336. * @returns the new ActionEvent
  52337. */
  52338. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52339. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52340. };
  52341. /**
  52342. * Helper function to auto-create an ActionEvent from a primitive
  52343. * @param prim defines the target primitive
  52344. * @param pointerPos defines the pointer position
  52345. * @param evt The original (browser) event
  52346. * @param additionalData additional data for the event
  52347. * @returns the new ActionEvent
  52348. */
  52349. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52350. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52351. };
  52352. return ActionEvent;
  52353. }());
  52354. BABYLON.ActionEvent = ActionEvent;
  52355. /**
  52356. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52357. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52359. */
  52360. var ActionManager = /** @class */ (function () {
  52361. /**
  52362. * Creates a new action manager
  52363. * @param scene defines the hosting scene
  52364. */
  52365. function ActionManager(scene) {
  52366. // Members
  52367. /** Gets the list of actions */
  52368. this.actions = new Array();
  52369. /** Gets the cursor to use when hovering items */
  52370. this.hoverCursor = '';
  52371. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52372. scene._actionManagers.push(this);
  52373. }
  52374. Object.defineProperty(ActionManager, "NothingTrigger", {
  52375. /**
  52376. * Nothing
  52377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52378. */
  52379. get: function () {
  52380. return ActionManager._NothingTrigger;
  52381. },
  52382. enumerable: true,
  52383. configurable: true
  52384. });
  52385. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52386. /**
  52387. * On pick
  52388. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52389. */
  52390. get: function () {
  52391. return ActionManager._OnPickTrigger;
  52392. },
  52393. enumerable: true,
  52394. configurable: true
  52395. });
  52396. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52397. /**
  52398. * On left pick
  52399. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52400. */
  52401. get: function () {
  52402. return ActionManager._OnLeftPickTrigger;
  52403. },
  52404. enumerable: true,
  52405. configurable: true
  52406. });
  52407. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52408. /**
  52409. * On right pick
  52410. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52411. */
  52412. get: function () {
  52413. return ActionManager._OnRightPickTrigger;
  52414. },
  52415. enumerable: true,
  52416. configurable: true
  52417. });
  52418. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52419. /**
  52420. * On center pick
  52421. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52422. */
  52423. get: function () {
  52424. return ActionManager._OnCenterPickTrigger;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52430. /**
  52431. * On pick down
  52432. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52433. */
  52434. get: function () {
  52435. return ActionManager._OnPickDownTrigger;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52441. /**
  52442. * On double pick
  52443. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52444. */
  52445. get: function () {
  52446. return ActionManager._OnDoublePickTrigger;
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52452. /**
  52453. * On pick up
  52454. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52455. */
  52456. get: function () {
  52457. return ActionManager._OnPickUpTrigger;
  52458. },
  52459. enumerable: true,
  52460. configurable: true
  52461. });
  52462. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52463. /**
  52464. * On pick out.
  52465. * This trigger will only be raised if you also declared a OnPickDown
  52466. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52467. */
  52468. get: function () {
  52469. return ActionManager._OnPickOutTrigger;
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52475. /**
  52476. * On long press
  52477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52478. */
  52479. get: function () {
  52480. return ActionManager._OnLongPressTrigger;
  52481. },
  52482. enumerable: true,
  52483. configurable: true
  52484. });
  52485. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52486. /**
  52487. * On pointer over
  52488. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52489. */
  52490. get: function () {
  52491. return ActionManager._OnPointerOverTrigger;
  52492. },
  52493. enumerable: true,
  52494. configurable: true
  52495. });
  52496. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52497. /**
  52498. * On pointer out
  52499. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52500. */
  52501. get: function () {
  52502. return ActionManager._OnPointerOutTrigger;
  52503. },
  52504. enumerable: true,
  52505. configurable: true
  52506. });
  52507. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52508. /**
  52509. * On every frame
  52510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52511. */
  52512. get: function () {
  52513. return ActionManager._OnEveryFrameTrigger;
  52514. },
  52515. enumerable: true,
  52516. configurable: true
  52517. });
  52518. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52519. /**
  52520. * On intersection enter
  52521. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52522. */
  52523. get: function () {
  52524. return ActionManager._OnIntersectionEnterTrigger;
  52525. },
  52526. enumerable: true,
  52527. configurable: true
  52528. });
  52529. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52530. /**
  52531. * On intersection exit
  52532. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52533. */
  52534. get: function () {
  52535. return ActionManager._OnIntersectionExitTrigger;
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52541. /**
  52542. * On key down
  52543. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52544. */
  52545. get: function () {
  52546. return ActionManager._OnKeyDownTrigger;
  52547. },
  52548. enumerable: true,
  52549. configurable: true
  52550. });
  52551. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52552. /**
  52553. * On key up
  52554. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52555. */
  52556. get: function () {
  52557. return ActionManager._OnKeyUpTrigger;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. // Methods
  52563. /**
  52564. * Releases all associated resources
  52565. */
  52566. ActionManager.prototype.dispose = function () {
  52567. var index = this._scene._actionManagers.indexOf(this);
  52568. for (var i = 0; i < this.actions.length; i++) {
  52569. var action = this.actions[i];
  52570. ActionManager.Triggers[action.trigger]--;
  52571. if (ActionManager.Triggers[action.trigger] === 0) {
  52572. delete ActionManager.Triggers[action.trigger];
  52573. }
  52574. }
  52575. if (index > -1) {
  52576. this._scene._actionManagers.splice(index, 1);
  52577. }
  52578. };
  52579. /**
  52580. * Gets hosting scene
  52581. * @returns the hosting scene
  52582. */
  52583. ActionManager.prototype.getScene = function () {
  52584. return this._scene;
  52585. };
  52586. /**
  52587. * Does this action manager handles actions of any of the given triggers
  52588. * @param triggers defines the triggers to be tested
  52589. * @return a boolean indicating whether one (or more) of the triggers is handled
  52590. */
  52591. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52592. for (var index = 0; index < this.actions.length; index++) {
  52593. var action = this.actions[index];
  52594. if (triggers.indexOf(action.trigger) > -1) {
  52595. return true;
  52596. }
  52597. }
  52598. return false;
  52599. };
  52600. /**
  52601. * Does this action manager handles actions of a given trigger
  52602. * @param trigger defines the trigger to be tested
  52603. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52604. * @return whether the trigger is handled
  52605. */
  52606. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52607. for (var index = 0; index < this.actions.length; index++) {
  52608. var action = this.actions[index];
  52609. if (action.trigger === trigger) {
  52610. if (parameterPredicate) {
  52611. if (parameterPredicate(action.getTriggerParameter())) {
  52612. return true;
  52613. }
  52614. }
  52615. else {
  52616. return true;
  52617. }
  52618. }
  52619. }
  52620. return false;
  52621. };
  52622. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52623. /**
  52624. * Does this action manager has pointer triggers
  52625. */
  52626. get: function () {
  52627. for (var index = 0; index < this.actions.length; index++) {
  52628. var action = this.actions[index];
  52629. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52630. return true;
  52631. }
  52632. }
  52633. return false;
  52634. },
  52635. enumerable: true,
  52636. configurable: true
  52637. });
  52638. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52639. /**
  52640. * Does this action manager has pick triggers
  52641. */
  52642. get: function () {
  52643. for (var index = 0; index < this.actions.length; index++) {
  52644. var action = this.actions[index];
  52645. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52646. return true;
  52647. }
  52648. }
  52649. return false;
  52650. },
  52651. enumerable: true,
  52652. configurable: true
  52653. });
  52654. Object.defineProperty(ActionManager, "HasTriggers", {
  52655. /**
  52656. * Does exist one action manager with at least one trigger
  52657. **/
  52658. get: function () {
  52659. for (var t in ActionManager.Triggers) {
  52660. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52661. return true;
  52662. }
  52663. }
  52664. return false;
  52665. },
  52666. enumerable: true,
  52667. configurable: true
  52668. });
  52669. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52670. /**
  52671. * Does exist one action manager with at least one pick trigger
  52672. **/
  52673. get: function () {
  52674. for (var t in ActionManager.Triggers) {
  52675. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52676. var t_int = parseInt(t);
  52677. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52678. return true;
  52679. }
  52680. }
  52681. }
  52682. return false;
  52683. },
  52684. enumerable: true,
  52685. configurable: true
  52686. });
  52687. /**
  52688. * Does exist one action manager that handles actions of a given trigger
  52689. * @param trigger defines the trigger to be tested
  52690. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52691. **/
  52692. ActionManager.HasSpecificTrigger = function (trigger) {
  52693. for (var t in ActionManager.Triggers) {
  52694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52695. var t_int = parseInt(t);
  52696. if (t_int === trigger) {
  52697. return true;
  52698. }
  52699. }
  52700. }
  52701. return false;
  52702. };
  52703. /**
  52704. * Registers an action to this action manager
  52705. * @param action defines the action to be registered
  52706. * @return the action amended (prepared) after registration
  52707. */
  52708. ActionManager.prototype.registerAction = function (action) {
  52709. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52710. if (this.getScene().actionManager !== this) {
  52711. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52712. return null;
  52713. }
  52714. }
  52715. this.actions.push(action);
  52716. if (ActionManager.Triggers[action.trigger]) {
  52717. ActionManager.Triggers[action.trigger]++;
  52718. }
  52719. else {
  52720. ActionManager.Triggers[action.trigger] = 1;
  52721. }
  52722. action._actionManager = this;
  52723. action._prepare();
  52724. return action;
  52725. };
  52726. /**
  52727. * Unregisters an action to this action manager
  52728. * @param action defines the action to be unregistered
  52729. * @return a boolean indicating whether the action has been unregistered
  52730. */
  52731. ActionManager.prototype.unregisterAction = function (action) {
  52732. var index = this.actions.indexOf(action);
  52733. if (index !== -1) {
  52734. this.actions.splice(index, 1);
  52735. ActionManager.Triggers[action.trigger] -= 1;
  52736. if (ActionManager.Triggers[action.trigger] === 0) {
  52737. delete ActionManager.Triggers[action.trigger];
  52738. }
  52739. delete action._actionManager;
  52740. return true;
  52741. }
  52742. return false;
  52743. };
  52744. /**
  52745. * Process a specific trigger
  52746. * @param trigger defines the trigger to process
  52747. * @param evt defines the event details to be processed
  52748. */
  52749. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52750. for (var index = 0; index < this.actions.length; index++) {
  52751. var action = this.actions[index];
  52752. if (action.trigger === trigger) {
  52753. if (evt) {
  52754. if (trigger === ActionManager.OnKeyUpTrigger
  52755. || trigger === ActionManager.OnKeyDownTrigger) {
  52756. var parameter = action.getTriggerParameter();
  52757. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52758. if (!parameter.toLowerCase) {
  52759. continue;
  52760. }
  52761. var lowerCase = parameter.toLowerCase();
  52762. if (lowerCase !== evt.sourceEvent.key) {
  52763. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52764. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52765. if (actualkey !== lowerCase) {
  52766. continue;
  52767. }
  52768. }
  52769. }
  52770. }
  52771. }
  52772. action._executeCurrent(evt);
  52773. }
  52774. }
  52775. };
  52776. /** @hidden */
  52777. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52778. var properties = propertyPath.split(".");
  52779. for (var index = 0; index < properties.length - 1; index++) {
  52780. target = target[properties[index]];
  52781. }
  52782. return target;
  52783. };
  52784. /** @hidden */
  52785. ActionManager.prototype._getProperty = function (propertyPath) {
  52786. var properties = propertyPath.split(".");
  52787. return properties[properties.length - 1];
  52788. };
  52789. /**
  52790. * Serialize this manager to a JSON object
  52791. * @param name defines the property name to store this manager
  52792. * @returns a JSON representation of this manager
  52793. */
  52794. ActionManager.prototype.serialize = function (name) {
  52795. var root = {
  52796. children: new Array(),
  52797. name: name,
  52798. type: 3,
  52799. properties: new Array() // Empty for root but required
  52800. };
  52801. for (var i = 0; i < this.actions.length; i++) {
  52802. var triggerObject = {
  52803. type: 0,
  52804. children: new Array(),
  52805. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52806. properties: new Array()
  52807. };
  52808. var triggerOptions = this.actions[i].triggerOptions;
  52809. if (triggerOptions && typeof triggerOptions !== "number") {
  52810. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52811. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52812. }
  52813. else {
  52814. var parameter = {};
  52815. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52816. if (triggerOptions.parameter.mesh) {
  52817. parameter._meshId = triggerOptions.parameter.mesh.id;
  52818. }
  52819. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52820. }
  52821. }
  52822. // Serialize child action, recursively
  52823. this.actions[i].serialize(triggerObject);
  52824. // Add serialized trigger
  52825. root.children.push(triggerObject);
  52826. }
  52827. return root;
  52828. };
  52829. /**
  52830. * Creates a new ActionManager from a JSON data
  52831. * @param parsedActions defines the JSON data to read from
  52832. * @param object defines the hosting mesh
  52833. * @param scene defines the hosting scene
  52834. */
  52835. ActionManager.Parse = function (parsedActions, object, scene) {
  52836. var actionManager = new ActionManager(scene);
  52837. if (object === null)
  52838. scene.actionManager = actionManager;
  52839. else
  52840. object.actionManager = actionManager;
  52841. // instanciate a new object
  52842. var instanciate = function (name, params) {
  52843. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52844. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52845. newInstance.constructor.apply(newInstance, params);
  52846. return newInstance;
  52847. };
  52848. var parseParameter = function (name, value, target, propertyPath) {
  52849. if (propertyPath === null) {
  52850. // String, boolean or float
  52851. var floatValue = parseFloat(value);
  52852. if (value === "true" || value === "false")
  52853. return value === "true";
  52854. else
  52855. return isNaN(floatValue) ? value : floatValue;
  52856. }
  52857. var effectiveTarget = propertyPath.split(".");
  52858. var values = value.split(",");
  52859. // Get effective Target
  52860. for (var i = 0; i < effectiveTarget.length; i++) {
  52861. target = target[effectiveTarget[i]];
  52862. }
  52863. // Return appropriate value with its type
  52864. if (typeof (target) === "boolean")
  52865. return values[0] === "true";
  52866. if (typeof (target) === "string")
  52867. return values[0];
  52868. // Parameters with multiple values such as Vector3 etc.
  52869. var split = new Array();
  52870. for (var i = 0; i < values.length; i++)
  52871. split.push(parseFloat(values[i]));
  52872. if (target instanceof BABYLON.Vector3)
  52873. return BABYLON.Vector3.FromArray(split);
  52874. if (target instanceof BABYLON.Vector4)
  52875. return BABYLON.Vector4.FromArray(split);
  52876. if (target instanceof BABYLON.Color3)
  52877. return BABYLON.Color3.FromArray(split);
  52878. if (target instanceof BABYLON.Color4)
  52879. return BABYLON.Color4.FromArray(split);
  52880. return parseFloat(values[0]);
  52881. };
  52882. // traverse graph per trigger
  52883. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52884. if (combineArray === void 0) { combineArray = null; }
  52885. if (parsedAction.detached)
  52886. return;
  52887. var parameters = new Array();
  52888. var target = null;
  52889. var propertyPath = null;
  52890. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52891. // Parameters
  52892. if (parsedAction.type === 2)
  52893. parameters.push(actionManager);
  52894. else
  52895. parameters.push(trigger);
  52896. if (combine) {
  52897. var actions = new Array();
  52898. for (var j = 0; j < parsedAction.combine.length; j++) {
  52899. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52900. }
  52901. parameters.push(actions);
  52902. }
  52903. else {
  52904. for (var i = 0; i < parsedAction.properties.length; i++) {
  52905. var value = parsedAction.properties[i].value;
  52906. var name = parsedAction.properties[i].name;
  52907. var targetType = parsedAction.properties[i].targetType;
  52908. if (name === "target")
  52909. if (targetType !== null && targetType === "SceneProperties")
  52910. value = target = scene;
  52911. else
  52912. value = target = scene.getNodeByName(value);
  52913. else if (name === "parent")
  52914. value = scene.getNodeByName(value);
  52915. else if (name === "sound")
  52916. value = scene.getSoundByName(value);
  52917. else if (name !== "propertyPath") {
  52918. if (parsedAction.type === 2 && name === "operator")
  52919. value = BABYLON.ValueCondition[value];
  52920. else
  52921. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52922. }
  52923. else {
  52924. propertyPath = value;
  52925. }
  52926. parameters.push(value);
  52927. }
  52928. }
  52929. if (combineArray === null) {
  52930. parameters.push(condition);
  52931. }
  52932. else {
  52933. parameters.push(null);
  52934. }
  52935. // If interpolate value action
  52936. if (parsedAction.name === "InterpolateValueAction") {
  52937. var param = parameters[parameters.length - 2];
  52938. parameters[parameters.length - 1] = param;
  52939. parameters[parameters.length - 2] = condition;
  52940. }
  52941. // Action or condition(s) and not CombineAction
  52942. var newAction = instanciate(parsedAction.name, parameters);
  52943. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52944. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52945. if (action)
  52946. action.then(nothing);
  52947. else
  52948. actionManager.registerAction(nothing);
  52949. action = nothing;
  52950. }
  52951. if (combineArray === null) {
  52952. if (newAction instanceof BABYLON.Condition) {
  52953. condition = newAction;
  52954. newAction = action;
  52955. }
  52956. else {
  52957. condition = null;
  52958. if (action)
  52959. action.then(newAction);
  52960. else
  52961. actionManager.registerAction(newAction);
  52962. }
  52963. }
  52964. else {
  52965. combineArray.push(newAction);
  52966. }
  52967. for (var i = 0; i < parsedAction.children.length; i++)
  52968. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52969. };
  52970. // triggers
  52971. for (var i = 0; i < parsedActions.children.length; i++) {
  52972. var triggerParams;
  52973. var trigger = parsedActions.children[i];
  52974. if (trigger.properties.length > 0) {
  52975. var param = trigger.properties[0].value;
  52976. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52977. if (value._meshId) {
  52978. value.mesh = scene.getMeshByID(value._meshId);
  52979. }
  52980. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52981. }
  52982. else
  52983. triggerParams = ActionManager[trigger.name];
  52984. for (var j = 0; j < trigger.children.length; j++) {
  52985. if (!trigger.detached)
  52986. traverse(trigger.children[j], triggerParams, null, null);
  52987. }
  52988. }
  52989. };
  52990. /**
  52991. * Get a trigger name by index
  52992. * @param trigger defines the trigger index
  52993. * @returns a trigger name
  52994. */
  52995. ActionManager.GetTriggerName = function (trigger) {
  52996. switch (trigger) {
  52997. case 0: return "NothingTrigger";
  52998. case 1: return "OnPickTrigger";
  52999. case 2: return "OnLeftPickTrigger";
  53000. case 3: return "OnRightPickTrigger";
  53001. case 4: return "OnCenterPickTrigger";
  53002. case 5: return "OnPickDownTrigger";
  53003. case 6: return "OnPickUpTrigger";
  53004. case 7: return "OnLongPressTrigger";
  53005. case 8: return "OnPointerOverTrigger";
  53006. case 9: return "OnPointerOutTrigger";
  53007. case 10: return "OnEveryFrameTrigger";
  53008. case 11: return "OnIntersectionEnterTrigger";
  53009. case 12: return "OnIntersectionExitTrigger";
  53010. case 13: return "OnKeyDownTrigger";
  53011. case 14: return "OnKeyUpTrigger";
  53012. case 15: return "OnPickOutTrigger";
  53013. default: return "";
  53014. }
  53015. };
  53016. // Statics
  53017. ActionManager._NothingTrigger = 0;
  53018. ActionManager._OnPickTrigger = 1;
  53019. ActionManager._OnLeftPickTrigger = 2;
  53020. ActionManager._OnRightPickTrigger = 3;
  53021. ActionManager._OnCenterPickTrigger = 4;
  53022. ActionManager._OnPickDownTrigger = 5;
  53023. ActionManager._OnDoublePickTrigger = 6;
  53024. ActionManager._OnPickUpTrigger = 7;
  53025. ActionManager._OnLongPressTrigger = 8;
  53026. ActionManager._OnPointerOverTrigger = 9;
  53027. ActionManager._OnPointerOutTrigger = 10;
  53028. ActionManager._OnEveryFrameTrigger = 11;
  53029. ActionManager._OnIntersectionEnterTrigger = 12;
  53030. ActionManager._OnIntersectionExitTrigger = 13;
  53031. ActionManager._OnKeyDownTrigger = 14;
  53032. ActionManager._OnKeyUpTrigger = 15;
  53033. ActionManager._OnPickOutTrigger = 16;
  53034. /** Gets the list of active triggers */
  53035. ActionManager.Triggers = {};
  53036. return ActionManager;
  53037. }());
  53038. BABYLON.ActionManager = ActionManager;
  53039. })(BABYLON || (BABYLON = {}));
  53040. //# sourceMappingURL=babylon.actionManager.js.map
  53041. var BABYLON;
  53042. (function (BABYLON) {
  53043. var InterpolateValueAction = /** @class */ (function (_super) {
  53044. __extends(InterpolateValueAction, _super);
  53045. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53046. if (duration === void 0) { duration = 1000; }
  53047. var _this = _super.call(this, triggerOptions, condition) || this;
  53048. _this.propertyPath = propertyPath;
  53049. _this.value = value;
  53050. _this.duration = duration;
  53051. _this.stopOtherAnimations = stopOtherAnimations;
  53052. _this.onInterpolationDone = onInterpolationDone;
  53053. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53054. _this._target = _this._effectiveTarget = target;
  53055. return _this;
  53056. }
  53057. InterpolateValueAction.prototype._prepare = function () {
  53058. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53059. this._property = this._getProperty(this.propertyPath);
  53060. };
  53061. InterpolateValueAction.prototype.execute = function () {
  53062. var _this = this;
  53063. var scene = this._actionManager.getScene();
  53064. var keys = [
  53065. {
  53066. frame: 0,
  53067. value: this._effectiveTarget[this._property]
  53068. }, {
  53069. frame: 100,
  53070. value: this.value
  53071. }
  53072. ];
  53073. var dataType;
  53074. if (typeof this.value === "number") {
  53075. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53076. }
  53077. else if (this.value instanceof BABYLON.Color3) {
  53078. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53079. }
  53080. else if (this.value instanceof BABYLON.Vector3) {
  53081. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53082. }
  53083. else if (this.value instanceof BABYLON.Matrix) {
  53084. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53085. }
  53086. else if (this.value instanceof BABYLON.Quaternion) {
  53087. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53088. }
  53089. else {
  53090. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53091. return;
  53092. }
  53093. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53094. animation.setKeys(keys);
  53095. if (this.stopOtherAnimations) {
  53096. scene.stopAnimation(this._effectiveTarget);
  53097. }
  53098. var wrapper = function () {
  53099. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53100. if (_this.onInterpolationDone) {
  53101. _this.onInterpolationDone();
  53102. }
  53103. };
  53104. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53105. };
  53106. InterpolateValueAction.prototype.serialize = function (parent) {
  53107. return _super.prototype._serialize.call(this, {
  53108. name: "InterpolateValueAction",
  53109. properties: [
  53110. BABYLON.Action._GetTargetProperty(this._target),
  53111. { name: "propertyPath", value: this.propertyPath },
  53112. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53113. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53114. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53115. ]
  53116. }, parent);
  53117. };
  53118. return InterpolateValueAction;
  53119. }(BABYLON.Action));
  53120. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53121. })(BABYLON || (BABYLON = {}));
  53122. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53123. var BABYLON;
  53124. (function (BABYLON) {
  53125. var SwitchBooleanAction = /** @class */ (function (_super) {
  53126. __extends(SwitchBooleanAction, _super);
  53127. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53128. var _this = _super.call(this, triggerOptions, condition) || this;
  53129. _this.propertyPath = propertyPath;
  53130. _this._target = _this._effectiveTarget = target;
  53131. return _this;
  53132. }
  53133. SwitchBooleanAction.prototype._prepare = function () {
  53134. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53135. this._property = this._getProperty(this.propertyPath);
  53136. };
  53137. SwitchBooleanAction.prototype.execute = function () {
  53138. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53139. };
  53140. SwitchBooleanAction.prototype.serialize = function (parent) {
  53141. return _super.prototype._serialize.call(this, {
  53142. name: "SwitchBooleanAction",
  53143. properties: [
  53144. BABYLON.Action._GetTargetProperty(this._target),
  53145. { name: "propertyPath", value: this.propertyPath }
  53146. ]
  53147. }, parent);
  53148. };
  53149. return SwitchBooleanAction;
  53150. }(BABYLON.Action));
  53151. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53152. var SetStateAction = /** @class */ (function (_super) {
  53153. __extends(SetStateAction, _super);
  53154. function SetStateAction(triggerOptions, target, value, condition) {
  53155. var _this = _super.call(this, triggerOptions, condition) || this;
  53156. _this.value = value;
  53157. _this._target = target;
  53158. return _this;
  53159. }
  53160. SetStateAction.prototype.execute = function () {
  53161. this._target.state = this.value;
  53162. };
  53163. SetStateAction.prototype.serialize = function (parent) {
  53164. return _super.prototype._serialize.call(this, {
  53165. name: "SetStateAction",
  53166. properties: [
  53167. BABYLON.Action._GetTargetProperty(this._target),
  53168. { name: "value", value: this.value }
  53169. ]
  53170. }, parent);
  53171. };
  53172. return SetStateAction;
  53173. }(BABYLON.Action));
  53174. BABYLON.SetStateAction = SetStateAction;
  53175. var SetValueAction = /** @class */ (function (_super) {
  53176. __extends(SetValueAction, _super);
  53177. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53178. var _this = _super.call(this, triggerOptions, condition) || this;
  53179. _this.propertyPath = propertyPath;
  53180. _this.value = value;
  53181. _this._target = _this._effectiveTarget = target;
  53182. return _this;
  53183. }
  53184. SetValueAction.prototype._prepare = function () {
  53185. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53186. this._property = this._getProperty(this.propertyPath);
  53187. };
  53188. SetValueAction.prototype.execute = function () {
  53189. this._effectiveTarget[this._property] = this.value;
  53190. if (this._target.markAsDirty) {
  53191. this._target.markAsDirty(this._property);
  53192. }
  53193. };
  53194. SetValueAction.prototype.serialize = function (parent) {
  53195. return _super.prototype._serialize.call(this, {
  53196. name: "SetValueAction",
  53197. properties: [
  53198. BABYLON.Action._GetTargetProperty(this._target),
  53199. { name: "propertyPath", value: this.propertyPath },
  53200. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53201. ]
  53202. }, parent);
  53203. };
  53204. return SetValueAction;
  53205. }(BABYLON.Action));
  53206. BABYLON.SetValueAction = SetValueAction;
  53207. var IncrementValueAction = /** @class */ (function (_super) {
  53208. __extends(IncrementValueAction, _super);
  53209. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53210. var _this = _super.call(this, triggerOptions, condition) || this;
  53211. _this.propertyPath = propertyPath;
  53212. _this.value = value;
  53213. _this._target = _this._effectiveTarget = target;
  53214. return _this;
  53215. }
  53216. IncrementValueAction.prototype._prepare = function () {
  53217. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53218. this._property = this._getProperty(this.propertyPath);
  53219. if (typeof this._effectiveTarget[this._property] !== "number") {
  53220. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53221. }
  53222. };
  53223. IncrementValueAction.prototype.execute = function () {
  53224. this._effectiveTarget[this._property] += this.value;
  53225. if (this._target.markAsDirty) {
  53226. this._target.markAsDirty(this._property);
  53227. }
  53228. };
  53229. IncrementValueAction.prototype.serialize = function (parent) {
  53230. return _super.prototype._serialize.call(this, {
  53231. name: "IncrementValueAction",
  53232. properties: [
  53233. BABYLON.Action._GetTargetProperty(this._target),
  53234. { name: "propertyPath", value: this.propertyPath },
  53235. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53236. ]
  53237. }, parent);
  53238. };
  53239. return IncrementValueAction;
  53240. }(BABYLON.Action));
  53241. BABYLON.IncrementValueAction = IncrementValueAction;
  53242. var PlayAnimationAction = /** @class */ (function (_super) {
  53243. __extends(PlayAnimationAction, _super);
  53244. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53245. var _this = _super.call(this, triggerOptions, condition) || this;
  53246. _this.from = from;
  53247. _this.to = to;
  53248. _this.loop = loop;
  53249. _this._target = target;
  53250. return _this;
  53251. }
  53252. PlayAnimationAction.prototype._prepare = function () {
  53253. };
  53254. PlayAnimationAction.prototype.execute = function () {
  53255. var scene = this._actionManager.getScene();
  53256. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53257. };
  53258. PlayAnimationAction.prototype.serialize = function (parent) {
  53259. return _super.prototype._serialize.call(this, {
  53260. name: "PlayAnimationAction",
  53261. properties: [
  53262. BABYLON.Action._GetTargetProperty(this._target),
  53263. { name: "from", value: String(this.from) },
  53264. { name: "to", value: String(this.to) },
  53265. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53266. ]
  53267. }, parent);
  53268. };
  53269. return PlayAnimationAction;
  53270. }(BABYLON.Action));
  53271. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53272. var StopAnimationAction = /** @class */ (function (_super) {
  53273. __extends(StopAnimationAction, _super);
  53274. function StopAnimationAction(triggerOptions, target, condition) {
  53275. var _this = _super.call(this, triggerOptions, condition) || this;
  53276. _this._target = target;
  53277. return _this;
  53278. }
  53279. StopAnimationAction.prototype._prepare = function () {
  53280. };
  53281. StopAnimationAction.prototype.execute = function () {
  53282. var scene = this._actionManager.getScene();
  53283. scene.stopAnimation(this._target);
  53284. };
  53285. StopAnimationAction.prototype.serialize = function (parent) {
  53286. return _super.prototype._serialize.call(this, {
  53287. name: "StopAnimationAction",
  53288. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53289. }, parent);
  53290. };
  53291. return StopAnimationAction;
  53292. }(BABYLON.Action));
  53293. BABYLON.StopAnimationAction = StopAnimationAction;
  53294. var DoNothingAction = /** @class */ (function (_super) {
  53295. __extends(DoNothingAction, _super);
  53296. function DoNothingAction(triggerOptions, condition) {
  53297. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53298. return _super.call(this, triggerOptions, condition) || this;
  53299. }
  53300. DoNothingAction.prototype.execute = function () {
  53301. };
  53302. DoNothingAction.prototype.serialize = function (parent) {
  53303. return _super.prototype._serialize.call(this, {
  53304. name: "DoNothingAction",
  53305. properties: []
  53306. }, parent);
  53307. };
  53308. return DoNothingAction;
  53309. }(BABYLON.Action));
  53310. BABYLON.DoNothingAction = DoNothingAction;
  53311. var CombineAction = /** @class */ (function (_super) {
  53312. __extends(CombineAction, _super);
  53313. function CombineAction(triggerOptions, children, condition) {
  53314. var _this = _super.call(this, triggerOptions, condition) || this;
  53315. _this.children = children;
  53316. return _this;
  53317. }
  53318. CombineAction.prototype._prepare = function () {
  53319. for (var index = 0; index < this.children.length; index++) {
  53320. this.children[index]._actionManager = this._actionManager;
  53321. this.children[index]._prepare();
  53322. }
  53323. };
  53324. CombineAction.prototype.execute = function (evt) {
  53325. for (var index = 0; index < this.children.length; index++) {
  53326. this.children[index].execute(evt);
  53327. }
  53328. };
  53329. CombineAction.prototype.serialize = function (parent) {
  53330. var serializationObject = _super.prototype._serialize.call(this, {
  53331. name: "CombineAction",
  53332. properties: [],
  53333. combine: []
  53334. }, parent);
  53335. for (var i = 0; i < this.children.length; i++) {
  53336. serializationObject.combine.push(this.children[i].serialize(null));
  53337. }
  53338. return serializationObject;
  53339. };
  53340. return CombineAction;
  53341. }(BABYLON.Action));
  53342. BABYLON.CombineAction = CombineAction;
  53343. var ExecuteCodeAction = /** @class */ (function (_super) {
  53344. __extends(ExecuteCodeAction, _super);
  53345. function ExecuteCodeAction(triggerOptions, func, condition) {
  53346. var _this = _super.call(this, triggerOptions, condition) || this;
  53347. _this.func = func;
  53348. return _this;
  53349. }
  53350. ExecuteCodeAction.prototype.execute = function (evt) {
  53351. this.func(evt);
  53352. };
  53353. return ExecuteCodeAction;
  53354. }(BABYLON.Action));
  53355. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53356. var SetParentAction = /** @class */ (function (_super) {
  53357. __extends(SetParentAction, _super);
  53358. function SetParentAction(triggerOptions, target, parent, condition) {
  53359. var _this = _super.call(this, triggerOptions, condition) || this;
  53360. _this._target = target;
  53361. _this._parent = parent;
  53362. return _this;
  53363. }
  53364. SetParentAction.prototype._prepare = function () {
  53365. };
  53366. SetParentAction.prototype.execute = function () {
  53367. if (this._target.parent === this._parent) {
  53368. return;
  53369. }
  53370. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53371. invertParentWorldMatrix.invert();
  53372. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53373. this._target.parent = this._parent;
  53374. };
  53375. SetParentAction.prototype.serialize = function (parent) {
  53376. return _super.prototype._serialize.call(this, {
  53377. name: "SetParentAction",
  53378. properties: [
  53379. BABYLON.Action._GetTargetProperty(this._target),
  53380. BABYLON.Action._GetTargetProperty(this._parent),
  53381. ]
  53382. }, parent);
  53383. };
  53384. return SetParentAction;
  53385. }(BABYLON.Action));
  53386. BABYLON.SetParentAction = SetParentAction;
  53387. var PlaySoundAction = /** @class */ (function (_super) {
  53388. __extends(PlaySoundAction, _super);
  53389. function PlaySoundAction(triggerOptions, sound, condition) {
  53390. var _this = _super.call(this, triggerOptions, condition) || this;
  53391. _this._sound = sound;
  53392. return _this;
  53393. }
  53394. PlaySoundAction.prototype._prepare = function () {
  53395. };
  53396. PlaySoundAction.prototype.execute = function () {
  53397. if (this._sound !== undefined)
  53398. this._sound.play();
  53399. };
  53400. PlaySoundAction.prototype.serialize = function (parent) {
  53401. return _super.prototype._serialize.call(this, {
  53402. name: "PlaySoundAction",
  53403. properties: [{ name: "sound", value: this._sound.name }]
  53404. }, parent);
  53405. };
  53406. return PlaySoundAction;
  53407. }(BABYLON.Action));
  53408. BABYLON.PlaySoundAction = PlaySoundAction;
  53409. var StopSoundAction = /** @class */ (function (_super) {
  53410. __extends(StopSoundAction, _super);
  53411. function StopSoundAction(triggerOptions, sound, condition) {
  53412. var _this = _super.call(this, triggerOptions, condition) || this;
  53413. _this._sound = sound;
  53414. return _this;
  53415. }
  53416. StopSoundAction.prototype._prepare = function () {
  53417. };
  53418. StopSoundAction.prototype.execute = function () {
  53419. if (this._sound !== undefined)
  53420. this._sound.stop();
  53421. };
  53422. StopSoundAction.prototype.serialize = function (parent) {
  53423. return _super.prototype._serialize.call(this, {
  53424. name: "StopSoundAction",
  53425. properties: [{ name: "sound", value: this._sound.name }]
  53426. }, parent);
  53427. };
  53428. return StopSoundAction;
  53429. }(BABYLON.Action));
  53430. BABYLON.StopSoundAction = StopSoundAction;
  53431. })(BABYLON || (BABYLON = {}));
  53432. //# sourceMappingURL=babylon.directActions.js.map
  53433. var BABYLON;
  53434. (function (BABYLON) {
  53435. var SpriteManager = /** @class */ (function () {
  53436. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53437. if (epsilon === void 0) { epsilon = 0.01; }
  53438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53439. this.name = name;
  53440. this.sprites = new Array();
  53441. this.renderingGroupId = 0;
  53442. this.layerMask = 0x0FFFFFFF;
  53443. this.fogEnabled = true;
  53444. this.isPickable = false;
  53445. /**
  53446. * An event triggered when the manager is disposed.
  53447. */
  53448. this.onDisposeObservable = new BABYLON.Observable();
  53449. this._vertexBuffers = {};
  53450. this._capacity = capacity;
  53451. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53452. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53453. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53454. if (cellSize.width && cellSize.height) {
  53455. this.cellWidth = cellSize.width;
  53456. this.cellHeight = cellSize.height;
  53457. }
  53458. else if (cellSize !== undefined) {
  53459. this.cellWidth = cellSize;
  53460. this.cellHeight = cellSize;
  53461. }
  53462. else {
  53463. return;
  53464. }
  53465. this._epsilon = epsilon;
  53466. this._scene = scene;
  53467. this._scene.spriteManagers.push(this);
  53468. var indices = [];
  53469. var index = 0;
  53470. for (var count = 0; count < capacity; count++) {
  53471. indices.push(index);
  53472. indices.push(index + 1);
  53473. indices.push(index + 2);
  53474. indices.push(index);
  53475. indices.push(index + 2);
  53476. indices.push(index + 3);
  53477. index += 4;
  53478. }
  53479. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53480. // VBO
  53481. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53482. this._vertexData = new Float32Array(capacity * 16 * 4);
  53483. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53484. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53485. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53486. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53487. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53489. this._vertexBuffers["options"] = options;
  53490. this._vertexBuffers["cellInfo"] = cellInfo;
  53491. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53492. // Effects
  53493. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53494. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53495. }
  53496. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53497. set: function (callback) {
  53498. if (this._onDisposeObserver) {
  53499. this.onDisposeObservable.remove(this._onDisposeObserver);
  53500. }
  53501. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53502. },
  53503. enumerable: true,
  53504. configurable: true
  53505. });
  53506. Object.defineProperty(SpriteManager.prototype, "texture", {
  53507. get: function () {
  53508. return this._spriteTexture;
  53509. },
  53510. set: function (value) {
  53511. this._spriteTexture = value;
  53512. },
  53513. enumerable: true,
  53514. configurable: true
  53515. });
  53516. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53517. var arrayOffset = index * 16;
  53518. if (offsetX === 0)
  53519. offsetX = this._epsilon;
  53520. else if (offsetX === 1)
  53521. offsetX = 1 - this._epsilon;
  53522. if (offsetY === 0)
  53523. offsetY = this._epsilon;
  53524. else if (offsetY === 1)
  53525. offsetY = 1 - this._epsilon;
  53526. this._vertexData[arrayOffset] = sprite.position.x;
  53527. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53528. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53529. this._vertexData[arrayOffset + 3] = sprite.angle;
  53530. this._vertexData[arrayOffset + 4] = sprite.width;
  53531. this._vertexData[arrayOffset + 5] = sprite.height;
  53532. this._vertexData[arrayOffset + 6] = offsetX;
  53533. this._vertexData[arrayOffset + 7] = offsetY;
  53534. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53535. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53536. var offset = (sprite.cellIndex / rowSize) >> 0;
  53537. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53538. this._vertexData[arrayOffset + 11] = offset;
  53539. // Color
  53540. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53541. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53542. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53543. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53544. };
  53545. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53546. var count = Math.min(this._capacity, this.sprites.length);
  53547. var min = BABYLON.Vector3.Zero();
  53548. var max = BABYLON.Vector3.Zero();
  53549. var distance = Number.MAX_VALUE;
  53550. var currentSprite = null;
  53551. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53552. var cameraView = camera.getViewMatrix();
  53553. for (var index = 0; index < count; index++) {
  53554. var sprite = this.sprites[index];
  53555. if (!sprite) {
  53556. continue;
  53557. }
  53558. if (predicate) {
  53559. if (!predicate(sprite)) {
  53560. continue;
  53561. }
  53562. }
  53563. else if (!sprite.isPickable) {
  53564. continue;
  53565. }
  53566. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53567. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53568. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53569. if (ray.intersectsBoxMinMax(min, max)) {
  53570. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53571. if (distance > currentDistance) {
  53572. distance = currentDistance;
  53573. currentSprite = sprite;
  53574. if (fastCheck) {
  53575. break;
  53576. }
  53577. }
  53578. }
  53579. }
  53580. if (currentSprite) {
  53581. var result = new BABYLON.PickingInfo();
  53582. result.hit = true;
  53583. result.pickedSprite = currentSprite;
  53584. result.distance = distance;
  53585. return result;
  53586. }
  53587. return null;
  53588. };
  53589. SpriteManager.prototype.render = function () {
  53590. // Check
  53591. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53592. return;
  53593. var engine = this._scene.getEngine();
  53594. var baseSize = this._spriteTexture.getBaseSize();
  53595. // Sprites
  53596. var deltaTime = engine.getDeltaTime();
  53597. var max = Math.min(this._capacity, this.sprites.length);
  53598. var rowSize = baseSize.width / this.cellWidth;
  53599. var offset = 0;
  53600. for (var index = 0; index < max; index++) {
  53601. var sprite = this.sprites[index];
  53602. if (!sprite || !sprite.isVisible) {
  53603. continue;
  53604. }
  53605. sprite._animate(deltaTime);
  53606. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53607. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53608. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53609. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53610. }
  53611. this._buffer.update(this._vertexData);
  53612. // Render
  53613. var effect = this._effectBase;
  53614. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53615. effect = this._effectFog;
  53616. }
  53617. engine.enableEffect(effect);
  53618. var viewMatrix = this._scene.getViewMatrix();
  53619. effect.setTexture("diffuseSampler", this._spriteTexture);
  53620. effect.setMatrix("view", viewMatrix);
  53621. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53622. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53623. // Fog
  53624. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53625. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53626. effect.setColor3("vFogColor", this._scene.fogColor);
  53627. }
  53628. // VBOs
  53629. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53630. // Draw order
  53631. engine.setDepthFunctionToLessOrEqual();
  53632. effect.setBool("alphaTest", true);
  53633. engine.setColorWrite(false);
  53634. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53635. engine.setColorWrite(true);
  53636. effect.setBool("alphaTest", false);
  53637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53638. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53639. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53640. };
  53641. SpriteManager.prototype.dispose = function () {
  53642. if (this._buffer) {
  53643. this._buffer.dispose();
  53644. this._buffer = null;
  53645. }
  53646. if (this._indexBuffer) {
  53647. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53648. this._indexBuffer = null;
  53649. }
  53650. if (this._spriteTexture) {
  53651. this._spriteTexture.dispose();
  53652. this._spriteTexture = null;
  53653. }
  53654. // Remove from scene
  53655. var index = this._scene.spriteManagers.indexOf(this);
  53656. this._scene.spriteManagers.splice(index, 1);
  53657. // Callback
  53658. this.onDisposeObservable.notifyObservers(this);
  53659. this.onDisposeObservable.clear();
  53660. };
  53661. return SpriteManager;
  53662. }());
  53663. BABYLON.SpriteManager = SpriteManager;
  53664. })(BABYLON || (BABYLON = {}));
  53665. //# sourceMappingURL=babylon.spriteManager.js.map
  53666. var BABYLON;
  53667. (function (BABYLON) {
  53668. var Sprite = /** @class */ (function () {
  53669. function Sprite(name, manager) {
  53670. this.name = name;
  53671. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53672. this.width = 1.0;
  53673. this.height = 1.0;
  53674. this.angle = 0;
  53675. this.cellIndex = 0;
  53676. this.invertU = 0;
  53677. this.invertV = 0;
  53678. this.animations = new Array();
  53679. this.isPickable = false;
  53680. this._animationStarted = false;
  53681. this._loopAnimation = false;
  53682. this._fromIndex = 0;
  53683. this._toIndex = 0;
  53684. this._delay = 0;
  53685. this._direction = 1;
  53686. this._time = 0;
  53687. /**
  53688. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53689. */
  53690. this.isVisible = true;
  53691. this._manager = manager;
  53692. this._manager.sprites.push(this);
  53693. this.position = BABYLON.Vector3.Zero();
  53694. }
  53695. Object.defineProperty(Sprite.prototype, "size", {
  53696. get: function () {
  53697. return this.width;
  53698. },
  53699. set: function (value) {
  53700. this.width = value;
  53701. this.height = value;
  53702. },
  53703. enumerable: true,
  53704. configurable: true
  53705. });
  53706. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53707. this._fromIndex = from;
  53708. this._toIndex = to;
  53709. this._loopAnimation = loop;
  53710. this._delay = delay;
  53711. this._animationStarted = true;
  53712. this._direction = from < to ? 1 : -1;
  53713. this.cellIndex = from;
  53714. this._time = 0;
  53715. this._onAnimationEnd = onAnimationEnd;
  53716. };
  53717. Sprite.prototype.stopAnimation = function () {
  53718. this._animationStarted = false;
  53719. };
  53720. Sprite.prototype._animate = function (deltaTime) {
  53721. if (!this._animationStarted)
  53722. return;
  53723. this._time += deltaTime;
  53724. if (this._time > this._delay) {
  53725. this._time = this._time % this._delay;
  53726. this.cellIndex += this._direction;
  53727. if (this.cellIndex > this._toIndex) {
  53728. if (this._loopAnimation) {
  53729. this.cellIndex = this._fromIndex;
  53730. }
  53731. else {
  53732. this.cellIndex = this._toIndex;
  53733. this._animationStarted = false;
  53734. if (this._onAnimationEnd) {
  53735. this._onAnimationEnd();
  53736. }
  53737. if (this.disposeWhenFinishedAnimating) {
  53738. this.dispose();
  53739. }
  53740. }
  53741. }
  53742. }
  53743. };
  53744. Sprite.prototype.dispose = function () {
  53745. for (var i = 0; i < this._manager.sprites.length; i++) {
  53746. if (this._manager.sprites[i] == this) {
  53747. this._manager.sprites.splice(i, 1);
  53748. }
  53749. }
  53750. };
  53751. return Sprite;
  53752. }());
  53753. BABYLON.Sprite = Sprite;
  53754. })(BABYLON || (BABYLON = {}));
  53755. //# sourceMappingURL=babylon.sprite.js.map
  53756. var BABYLON;
  53757. (function (BABYLON) {
  53758. var IntersectionInfo = /** @class */ (function () {
  53759. function IntersectionInfo(bu, bv, distance) {
  53760. this.bu = bu;
  53761. this.bv = bv;
  53762. this.distance = distance;
  53763. this.faceId = 0;
  53764. this.subMeshId = 0;
  53765. }
  53766. return IntersectionInfo;
  53767. }());
  53768. BABYLON.IntersectionInfo = IntersectionInfo;
  53769. /**
  53770. * Information about the result of picking within a scene
  53771. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53772. */
  53773. var PickingInfo = /** @class */ (function () {
  53774. function PickingInfo() {
  53775. /**
  53776. * If the pick collided with an object
  53777. */
  53778. this.hit = false;
  53779. /**
  53780. * Distance away where the pick collided
  53781. */
  53782. this.distance = 0;
  53783. /**
  53784. * The location of pick collision
  53785. */
  53786. this.pickedPoint = null;
  53787. /**
  53788. * The mesh corrisponding the the pick collision
  53789. */
  53790. this.pickedMesh = null;
  53791. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53792. this.bu = 0;
  53793. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53794. this.bv = 0;
  53795. /** The id of the face on the mesh that was picked */
  53796. this.faceId = -1;
  53797. /** Id of the the submesh that was picked */
  53798. this.subMeshId = 0;
  53799. /** If a sprite was picked, this will be the sprite the pick collided with */
  53800. this.pickedSprite = null;
  53801. /**
  53802. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53803. */
  53804. this.originMesh = null;
  53805. /**
  53806. * The ray that was used to perform the picking.
  53807. */
  53808. this.ray = null;
  53809. }
  53810. /**
  53811. * Gets the normal corrispodning to the face the pick collided with
  53812. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53813. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53814. * @returns The normal corrispodning to the face the pick collided with
  53815. */
  53816. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53817. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53818. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53819. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53820. return null;
  53821. }
  53822. var indices = this.pickedMesh.getIndices();
  53823. if (!indices) {
  53824. return null;
  53825. }
  53826. var result;
  53827. if (useVerticesNormals) {
  53828. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53829. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53830. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53831. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53832. normal0 = normal0.scale(this.bu);
  53833. normal1 = normal1.scale(this.bv);
  53834. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53835. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53836. }
  53837. else {
  53838. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53839. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53840. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53841. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53842. var p1p2 = vertex1.subtract(vertex2);
  53843. var p3p2 = vertex3.subtract(vertex2);
  53844. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53845. }
  53846. if (useWorldCoordinates) {
  53847. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53848. }
  53849. return BABYLON.Vector3.Normalize(result);
  53850. };
  53851. /**
  53852. * Gets the texture coordinates of where the pick occured
  53853. * @returns the vector containing the coordnates of the texture
  53854. */
  53855. PickingInfo.prototype.getTextureCoordinates = function () {
  53856. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53857. return null;
  53858. }
  53859. var indices = this.pickedMesh.getIndices();
  53860. if (!indices) {
  53861. return null;
  53862. }
  53863. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53864. if (!uvs) {
  53865. return null;
  53866. }
  53867. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53868. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53869. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53870. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53871. uv1 = uv1.scale(this.bu);
  53872. uv2 = uv2.scale(this.bv);
  53873. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53874. };
  53875. return PickingInfo;
  53876. }());
  53877. BABYLON.PickingInfo = PickingInfo;
  53878. })(BABYLON || (BABYLON = {}));
  53879. //# sourceMappingURL=babylon.pickingInfo.js.map
  53880. var BABYLON;
  53881. (function (BABYLON) {
  53882. var Ray = /** @class */ (function () {
  53883. function Ray(origin, direction, length) {
  53884. if (length === void 0) { length = Number.MAX_VALUE; }
  53885. this.origin = origin;
  53886. this.direction = direction;
  53887. this.length = length;
  53888. }
  53889. // Methods
  53890. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53891. var d = 0.0;
  53892. var maxValue = Number.MAX_VALUE;
  53893. var inv;
  53894. var min;
  53895. var max;
  53896. var temp;
  53897. if (Math.abs(this.direction.x) < 0.0000001) {
  53898. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53899. return false;
  53900. }
  53901. }
  53902. else {
  53903. inv = 1.0 / this.direction.x;
  53904. min = (minimum.x - this.origin.x) * inv;
  53905. max = (maximum.x - this.origin.x) * inv;
  53906. if (max === -Infinity) {
  53907. max = Infinity;
  53908. }
  53909. if (min > max) {
  53910. temp = min;
  53911. min = max;
  53912. max = temp;
  53913. }
  53914. d = Math.max(min, d);
  53915. maxValue = Math.min(max, maxValue);
  53916. if (d > maxValue) {
  53917. return false;
  53918. }
  53919. }
  53920. if (Math.abs(this.direction.y) < 0.0000001) {
  53921. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53922. return false;
  53923. }
  53924. }
  53925. else {
  53926. inv = 1.0 / this.direction.y;
  53927. min = (minimum.y - this.origin.y) * inv;
  53928. max = (maximum.y - this.origin.y) * inv;
  53929. if (max === -Infinity) {
  53930. max = Infinity;
  53931. }
  53932. if (min > max) {
  53933. temp = min;
  53934. min = max;
  53935. max = temp;
  53936. }
  53937. d = Math.max(min, d);
  53938. maxValue = Math.min(max, maxValue);
  53939. if (d > maxValue) {
  53940. return false;
  53941. }
  53942. }
  53943. if (Math.abs(this.direction.z) < 0.0000001) {
  53944. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53945. return false;
  53946. }
  53947. }
  53948. else {
  53949. inv = 1.0 / this.direction.z;
  53950. min = (minimum.z - this.origin.z) * inv;
  53951. max = (maximum.z - this.origin.z) * inv;
  53952. if (max === -Infinity) {
  53953. max = Infinity;
  53954. }
  53955. if (min > max) {
  53956. temp = min;
  53957. min = max;
  53958. max = temp;
  53959. }
  53960. d = Math.max(min, d);
  53961. maxValue = Math.min(max, maxValue);
  53962. if (d > maxValue) {
  53963. return false;
  53964. }
  53965. }
  53966. return true;
  53967. };
  53968. Ray.prototype.intersectsBox = function (box) {
  53969. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53970. };
  53971. Ray.prototype.intersectsSphere = function (sphere) {
  53972. var x = sphere.center.x - this.origin.x;
  53973. var y = sphere.center.y - this.origin.y;
  53974. var z = sphere.center.z - this.origin.z;
  53975. var pyth = (x * x) + (y * y) + (z * z);
  53976. var rr = sphere.radius * sphere.radius;
  53977. if (pyth <= rr) {
  53978. return true;
  53979. }
  53980. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53981. if (dot < 0.0) {
  53982. return false;
  53983. }
  53984. var temp = pyth - (dot * dot);
  53985. return temp <= rr;
  53986. };
  53987. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53988. if (!this._edge1) {
  53989. this._edge1 = BABYLON.Vector3.Zero();
  53990. this._edge2 = BABYLON.Vector3.Zero();
  53991. this._pvec = BABYLON.Vector3.Zero();
  53992. this._tvec = BABYLON.Vector3.Zero();
  53993. this._qvec = BABYLON.Vector3.Zero();
  53994. }
  53995. vertex1.subtractToRef(vertex0, this._edge1);
  53996. vertex2.subtractToRef(vertex0, this._edge2);
  53997. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53998. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53999. if (det === 0) {
  54000. return null;
  54001. }
  54002. var invdet = 1 / det;
  54003. this.origin.subtractToRef(vertex0, this._tvec);
  54004. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54005. if (bu < 0 || bu > 1.0) {
  54006. return null;
  54007. }
  54008. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54009. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54010. if (bv < 0 || bu + bv > 1.0) {
  54011. return null;
  54012. }
  54013. //check if the distance is longer than the predefined length.
  54014. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54015. if (distance > this.length) {
  54016. return null;
  54017. }
  54018. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54019. };
  54020. Ray.prototype.intersectsPlane = function (plane) {
  54021. var distance;
  54022. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54023. if (Math.abs(result1) < 9.99999997475243E-07) {
  54024. return null;
  54025. }
  54026. else {
  54027. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54028. distance = (-plane.d - result2) / result1;
  54029. if (distance < 0.0) {
  54030. if (distance < -9.99999997475243E-07) {
  54031. return null;
  54032. }
  54033. else {
  54034. return 0;
  54035. }
  54036. }
  54037. return distance;
  54038. }
  54039. };
  54040. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54041. var tm = BABYLON.Tmp.Matrix[0];
  54042. mesh.getWorldMatrix().invertToRef(tm);
  54043. if (this._tmpRay) {
  54044. Ray.TransformToRef(this, tm, this._tmpRay);
  54045. }
  54046. else {
  54047. this._tmpRay = Ray.Transform(this, tm);
  54048. }
  54049. return mesh.intersects(this._tmpRay, fastCheck);
  54050. };
  54051. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54052. if (results) {
  54053. results.length = 0;
  54054. }
  54055. else {
  54056. results = [];
  54057. }
  54058. for (var i = 0; i < meshes.length; i++) {
  54059. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54060. if (pickInfo.hit) {
  54061. results.push(pickInfo);
  54062. }
  54063. }
  54064. results.sort(this._comparePickingInfo);
  54065. return results;
  54066. };
  54067. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54068. if (pickingInfoA.distance < pickingInfoB.distance) {
  54069. return -1;
  54070. }
  54071. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54072. return 1;
  54073. }
  54074. else {
  54075. return 0;
  54076. }
  54077. };
  54078. /**
  54079. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54080. * @param sega the first point of the segment to test the intersection against
  54081. * @param segb the second point of the segment to test the intersection against
  54082. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54083. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54084. */
  54085. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54086. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54087. var u = segb.subtract(sega);
  54088. var v = rsegb.subtract(this.origin);
  54089. var w = sega.subtract(this.origin);
  54090. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54091. var b = BABYLON.Vector3.Dot(u, v);
  54092. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54093. var d = BABYLON.Vector3.Dot(u, w);
  54094. var e = BABYLON.Vector3.Dot(v, w);
  54095. var D = a * c - b * b; // always >= 0
  54096. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54097. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54098. // compute the line parameters of the two closest points
  54099. if (D < Ray.smallnum) { // the lines are almost parallel
  54100. sN = 0.0; // force using point P0 on segment S1
  54101. sD = 1.0; // to prevent possible division by 0.0 later
  54102. tN = e;
  54103. tD = c;
  54104. }
  54105. else { // get the closest points on the infinite lines
  54106. sN = (b * e - c * d);
  54107. tN = (a * e - b * d);
  54108. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54109. sN = 0.0;
  54110. tN = e;
  54111. tD = c;
  54112. }
  54113. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54114. sN = sD;
  54115. tN = e + b;
  54116. tD = c;
  54117. }
  54118. }
  54119. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54120. tN = 0.0;
  54121. // recompute sc for this edge
  54122. if (-d < 0.0) {
  54123. sN = 0.0;
  54124. }
  54125. else if (-d > a)
  54126. sN = sD;
  54127. else {
  54128. sN = -d;
  54129. sD = a;
  54130. }
  54131. }
  54132. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54133. tN = tD;
  54134. // recompute sc for this edge
  54135. if ((-d + b) < 0.0) {
  54136. sN = 0;
  54137. }
  54138. else if ((-d + b) > a) {
  54139. sN = sD;
  54140. }
  54141. else {
  54142. sN = (-d + b);
  54143. sD = a;
  54144. }
  54145. }
  54146. // finally do the division to get sc and tc
  54147. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54148. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54149. // get the difference of the two closest points
  54150. var qtc = v.multiplyByFloats(tc, tc, tc);
  54151. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54152. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54153. if (isIntersected) {
  54154. return qtc.length();
  54155. }
  54156. return -1;
  54157. };
  54158. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54159. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54160. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54161. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54162. this.direction.normalize();
  54163. return this;
  54164. };
  54165. // Statics
  54166. Ray.Zero = function () {
  54167. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54168. };
  54169. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54170. var result = Ray.Zero();
  54171. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54172. };
  54173. /**
  54174. * 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
  54175. * transformed to the given world matrix.
  54176. * @param origin The origin point
  54177. * @param end The end point
  54178. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54179. */
  54180. Ray.CreateNewFromTo = function (origin, end, world) {
  54181. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54182. var direction = end.subtract(origin);
  54183. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54184. direction.normalize();
  54185. return Ray.Transform(new Ray(origin, direction, length), world);
  54186. };
  54187. Ray.Transform = function (ray, matrix) {
  54188. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54189. Ray.TransformToRef(ray, matrix, result);
  54190. return result;
  54191. };
  54192. Ray.TransformToRef = function (ray, matrix, result) {
  54193. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54194. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54195. result.length = ray.length;
  54196. var dir = result.direction;
  54197. var len = dir.length();
  54198. if (!(len === 0 || len === 1)) {
  54199. var num = 1.0 / len;
  54200. dir.x *= num;
  54201. dir.y *= num;
  54202. dir.z *= num;
  54203. result.length *= len;
  54204. }
  54205. };
  54206. Ray.smallnum = 0.00000001;
  54207. Ray.rayl = 10e8;
  54208. return Ray;
  54209. }());
  54210. BABYLON.Ray = Ray;
  54211. })(BABYLON || (BABYLON = {}));
  54212. //# sourceMappingURL=babylon.ray.js.map
  54213. var BABYLON;
  54214. (function (BABYLON) {
  54215. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54216. if (boxMin.x > sphereCenter.x + sphereRadius)
  54217. return false;
  54218. if (sphereCenter.x - sphereRadius > boxMax.x)
  54219. return false;
  54220. if (boxMin.y > sphereCenter.y + sphereRadius)
  54221. return false;
  54222. if (sphereCenter.y - sphereRadius > boxMax.y)
  54223. return false;
  54224. if (boxMin.z > sphereCenter.z + sphereRadius)
  54225. return false;
  54226. if (sphereCenter.z - sphereRadius > boxMax.z)
  54227. return false;
  54228. return true;
  54229. };
  54230. var getLowestRoot = (function () {
  54231. var result = { root: 0, found: false };
  54232. return function (a, b, c, maxR) {
  54233. result.root = 0;
  54234. result.found = false;
  54235. var determinant = b * b - 4.0 * a * c;
  54236. if (determinant < 0)
  54237. return result;
  54238. var sqrtD = Math.sqrt(determinant);
  54239. var r1 = (-b - sqrtD) / (2.0 * a);
  54240. var r2 = (-b + sqrtD) / (2.0 * a);
  54241. if (r1 > r2) {
  54242. var temp = r2;
  54243. r2 = r1;
  54244. r1 = temp;
  54245. }
  54246. if (r1 > 0 && r1 < maxR) {
  54247. result.root = r1;
  54248. result.found = true;
  54249. return result;
  54250. }
  54251. if (r2 > 0 && r2 < maxR) {
  54252. result.root = r2;
  54253. result.found = true;
  54254. return result;
  54255. }
  54256. return result;
  54257. };
  54258. })();
  54259. var Collider = /** @class */ (function () {
  54260. function Collider() {
  54261. this._collisionPoint = BABYLON.Vector3.Zero();
  54262. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54263. this._tempVector = BABYLON.Vector3.Zero();
  54264. this._tempVector2 = BABYLON.Vector3.Zero();
  54265. this._tempVector3 = BABYLON.Vector3.Zero();
  54266. this._tempVector4 = BABYLON.Vector3.Zero();
  54267. this._edge = BABYLON.Vector3.Zero();
  54268. this._baseToVertex = BABYLON.Vector3.Zero();
  54269. this._destinationPoint = BABYLON.Vector3.Zero();
  54270. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54271. this._displacementVector = BABYLON.Vector3.Zero();
  54272. this._radius = BABYLON.Vector3.One();
  54273. this._retry = 0;
  54274. this._basePointWorld = BABYLON.Vector3.Zero();
  54275. this._velocityWorld = BABYLON.Vector3.Zero();
  54276. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54277. this._collisionMask = -1;
  54278. }
  54279. Object.defineProperty(Collider.prototype, "collisionMask", {
  54280. get: function () {
  54281. return this._collisionMask;
  54282. },
  54283. set: function (mask) {
  54284. this._collisionMask = !isNaN(mask) ? mask : -1;
  54285. },
  54286. enumerable: true,
  54287. configurable: true
  54288. });
  54289. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54290. /**
  54291. * Gets the plane normal used to compute the sliding response (in local space)
  54292. */
  54293. get: function () {
  54294. return this._slidePlaneNormal;
  54295. },
  54296. enumerable: true,
  54297. configurable: true
  54298. });
  54299. // Methods
  54300. Collider.prototype._initialize = function (source, dir, e) {
  54301. this._velocity = dir;
  54302. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54303. this._basePoint = source;
  54304. source.multiplyToRef(this._radius, this._basePointWorld);
  54305. dir.multiplyToRef(this._radius, this._velocityWorld);
  54306. this._velocityWorldLength = this._velocityWorld.length();
  54307. this._epsilon = e;
  54308. this.collisionFound = false;
  54309. };
  54310. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54311. pa.subtractToRef(point, this._tempVector);
  54312. pb.subtractToRef(point, this._tempVector2);
  54313. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54314. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54315. if (d < 0)
  54316. return false;
  54317. pc.subtractToRef(point, this._tempVector3);
  54318. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54319. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54320. if (d < 0)
  54321. return false;
  54322. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54323. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54324. return d >= 0;
  54325. };
  54326. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54327. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54328. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54329. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54330. return false;
  54331. }
  54332. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54333. return false;
  54334. return true;
  54335. };
  54336. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54337. var t0;
  54338. var embeddedInPlane = false;
  54339. //defensive programming, actually not needed.
  54340. if (!trianglePlaneArray) {
  54341. trianglePlaneArray = [];
  54342. }
  54343. if (!trianglePlaneArray[faceIndex]) {
  54344. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54345. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54346. }
  54347. var trianglePlane = trianglePlaneArray[faceIndex];
  54348. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54349. return;
  54350. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54351. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54352. if (normalDotVelocity == 0) {
  54353. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54354. return;
  54355. embeddedInPlane = true;
  54356. t0 = 0;
  54357. }
  54358. else {
  54359. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54360. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54361. if (t0 > t1) {
  54362. var temp = t1;
  54363. t1 = t0;
  54364. t0 = temp;
  54365. }
  54366. if (t0 > 1.0 || t1 < 0.0)
  54367. return;
  54368. if (t0 < 0)
  54369. t0 = 0;
  54370. if (t0 > 1.0)
  54371. t0 = 1.0;
  54372. }
  54373. this._collisionPoint.copyFromFloats(0, 0, 0);
  54374. var found = false;
  54375. var t = 1.0;
  54376. if (!embeddedInPlane) {
  54377. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54378. this._velocity.scaleToRef(t0, this._tempVector);
  54379. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54380. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54381. found = true;
  54382. t = t0;
  54383. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54384. }
  54385. }
  54386. if (!found) {
  54387. var velocitySquaredLength = this._velocity.lengthSquared();
  54388. var a = velocitySquaredLength;
  54389. this._basePoint.subtractToRef(p1, this._tempVector);
  54390. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54391. var c = this._tempVector.lengthSquared() - 1.0;
  54392. var lowestRoot = getLowestRoot(a, b, c, t);
  54393. if (lowestRoot.found) {
  54394. t = lowestRoot.root;
  54395. found = true;
  54396. this._collisionPoint.copyFrom(p1);
  54397. }
  54398. this._basePoint.subtractToRef(p2, this._tempVector);
  54399. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54400. c = this._tempVector.lengthSquared() - 1.0;
  54401. lowestRoot = getLowestRoot(a, b, c, t);
  54402. if (lowestRoot.found) {
  54403. t = lowestRoot.root;
  54404. found = true;
  54405. this._collisionPoint.copyFrom(p2);
  54406. }
  54407. this._basePoint.subtractToRef(p3, this._tempVector);
  54408. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54409. c = this._tempVector.lengthSquared() - 1.0;
  54410. lowestRoot = getLowestRoot(a, b, c, t);
  54411. if (lowestRoot.found) {
  54412. t = lowestRoot.root;
  54413. found = true;
  54414. this._collisionPoint.copyFrom(p3);
  54415. }
  54416. p2.subtractToRef(p1, this._edge);
  54417. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54418. var edgeSquaredLength = this._edge.lengthSquared();
  54419. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54420. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54421. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54422. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54423. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54424. lowestRoot = getLowestRoot(a, b, c, t);
  54425. if (lowestRoot.found) {
  54426. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54427. if (f >= 0.0 && f <= 1.0) {
  54428. t = lowestRoot.root;
  54429. found = true;
  54430. this._edge.scaleInPlace(f);
  54431. p1.addToRef(this._edge, this._collisionPoint);
  54432. }
  54433. }
  54434. p3.subtractToRef(p2, this._edge);
  54435. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54436. edgeSquaredLength = this._edge.lengthSquared();
  54437. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54438. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54439. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54440. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54441. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54442. lowestRoot = getLowestRoot(a, b, c, t);
  54443. if (lowestRoot.found) {
  54444. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54445. if (f >= 0.0 && f <= 1.0) {
  54446. t = lowestRoot.root;
  54447. found = true;
  54448. this._edge.scaleInPlace(f);
  54449. p2.addToRef(this._edge, this._collisionPoint);
  54450. }
  54451. }
  54452. p1.subtractToRef(p3, this._edge);
  54453. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54454. edgeSquaredLength = this._edge.lengthSquared();
  54455. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54456. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54457. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54458. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54459. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54460. lowestRoot = getLowestRoot(a, b, c, t);
  54461. if (lowestRoot.found) {
  54462. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54463. if (f >= 0.0 && f <= 1.0) {
  54464. t = lowestRoot.root;
  54465. found = true;
  54466. this._edge.scaleInPlace(f);
  54467. p3.addToRef(this._edge, this._collisionPoint);
  54468. }
  54469. }
  54470. }
  54471. if (found) {
  54472. var distToCollision = t * this._velocity.length();
  54473. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54474. if (!this.intersectionPoint) {
  54475. this.intersectionPoint = this._collisionPoint.clone();
  54476. }
  54477. else {
  54478. this.intersectionPoint.copyFrom(this._collisionPoint);
  54479. }
  54480. this._nearestDistance = distToCollision;
  54481. this.collisionFound = true;
  54482. }
  54483. }
  54484. };
  54485. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54486. for (var i = indexStart; i < indexEnd; i += 3) {
  54487. var p1 = pts[indices[i] - decal];
  54488. var p2 = pts[indices[i + 1] - decal];
  54489. var p3 = pts[indices[i + 2] - decal];
  54490. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54491. }
  54492. };
  54493. Collider.prototype._getResponse = function (pos, vel) {
  54494. pos.addToRef(vel, this._destinationPoint);
  54495. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54496. this._basePoint.addToRef(vel, pos);
  54497. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54498. this._slidePlaneNormal.normalize();
  54499. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54500. pos.addInPlace(this._displacementVector);
  54501. this.intersectionPoint.addInPlace(this._displacementVector);
  54502. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54503. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54504. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54505. };
  54506. return Collider;
  54507. }());
  54508. BABYLON.Collider = Collider;
  54509. })(BABYLON || (BABYLON = {}));
  54510. //# sourceMappingURL=babylon.collider.js.map
  54511. var BABYLON;
  54512. (function (BABYLON) {
  54513. //WebWorker code will be inserted to this variable.
  54514. BABYLON.CollisionWorker = "";
  54515. /** Defines supported task for worker process */
  54516. var WorkerTaskType;
  54517. (function (WorkerTaskType) {
  54518. /** Initialization */
  54519. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54520. /** Update of geometry */
  54521. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54522. /** Evaluate collision */
  54523. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54524. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54525. /** Defines kind of replies returned by worker */
  54526. var WorkerReplyType;
  54527. (function (WorkerReplyType) {
  54528. /** Success */
  54529. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54530. /** Unkown error */
  54531. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54532. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54533. var CollisionCoordinatorWorker = /** @class */ (function () {
  54534. function CollisionCoordinatorWorker() {
  54535. var _this = this;
  54536. this._scaledPosition = BABYLON.Vector3.Zero();
  54537. this._scaledVelocity = BABYLON.Vector3.Zero();
  54538. this.onMeshUpdated = function (transformNode) {
  54539. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54540. };
  54541. this.onGeometryUpdated = function (geometry) {
  54542. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54543. };
  54544. this._afterRender = function () {
  54545. if (!_this._init)
  54546. return;
  54547. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54548. return;
  54549. }
  54550. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54551. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54552. if (_this._runningUpdated > 4) {
  54553. return;
  54554. }
  54555. ++_this._runningUpdated;
  54556. var payload = {
  54557. updatedMeshes: _this._addUpdateMeshesList,
  54558. updatedGeometries: _this._addUpdateGeometriesList,
  54559. removedGeometries: _this._toRemoveGeometryArray,
  54560. removedMeshes: _this._toRemoveMeshesArray
  54561. };
  54562. var message = {
  54563. payload: payload,
  54564. taskType: WorkerTaskType.UPDATE
  54565. };
  54566. var serializable = [];
  54567. for (var id in payload.updatedGeometries) {
  54568. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54569. //prepare transferables
  54570. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54571. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54572. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54573. }
  54574. }
  54575. _this._worker.postMessage(message, serializable);
  54576. _this._addUpdateMeshesList = {};
  54577. _this._addUpdateGeometriesList = {};
  54578. _this._toRemoveGeometryArray = [];
  54579. _this._toRemoveMeshesArray = [];
  54580. };
  54581. this._onMessageFromWorker = function (e) {
  54582. var returnData = e.data;
  54583. if (returnData.error != WorkerReplyType.SUCCESS) {
  54584. //TODO what errors can be returned from the worker?
  54585. BABYLON.Tools.Warn("error returned from worker!");
  54586. return;
  54587. }
  54588. switch (returnData.taskType) {
  54589. case WorkerTaskType.INIT:
  54590. _this._init = true;
  54591. //Update the worked with ALL of the scene's current state
  54592. _this._scene.meshes.forEach(function (mesh) {
  54593. _this.onMeshAdded(mesh);
  54594. });
  54595. _this._scene.getGeometries().forEach(function (geometry) {
  54596. _this.onGeometryAdded(geometry);
  54597. });
  54598. break;
  54599. case WorkerTaskType.UPDATE:
  54600. _this._runningUpdated--;
  54601. break;
  54602. case WorkerTaskType.COLLIDE:
  54603. var returnPayload = returnData.payload;
  54604. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54605. return;
  54606. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54607. if (callback) {
  54608. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54609. if (mesh) {
  54610. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54611. }
  54612. }
  54613. //cleanup
  54614. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54615. break;
  54616. }
  54617. };
  54618. this._collisionsCallbackArray = [];
  54619. this._init = false;
  54620. this._runningUpdated = 0;
  54621. this._addUpdateMeshesList = {};
  54622. this._addUpdateGeometriesList = {};
  54623. this._toRemoveGeometryArray = [];
  54624. this._toRemoveMeshesArray = [];
  54625. }
  54626. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54627. if (!this._init)
  54628. return;
  54629. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54630. return;
  54631. position.divideToRef(collider._radius, this._scaledPosition);
  54632. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54633. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54634. var payload = {
  54635. collider: {
  54636. position: this._scaledPosition.asArray(),
  54637. velocity: this._scaledVelocity.asArray(),
  54638. radius: collider._radius.asArray()
  54639. },
  54640. collisionId: collisionIndex,
  54641. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54642. maximumRetry: maximumRetry
  54643. };
  54644. var message = {
  54645. payload: payload,
  54646. taskType: WorkerTaskType.COLLIDE
  54647. };
  54648. this._worker.postMessage(message);
  54649. };
  54650. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54651. this._scene = scene;
  54652. this._scene.registerAfterRender(this._afterRender);
  54653. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54654. this._worker = new Worker(workerUrl);
  54655. this._worker.onmessage = this._onMessageFromWorker;
  54656. var message = {
  54657. payload: {},
  54658. taskType: WorkerTaskType.INIT
  54659. };
  54660. this._worker.postMessage(message);
  54661. };
  54662. CollisionCoordinatorWorker.prototype.destroy = function () {
  54663. this._scene.unregisterAfterRender(this._afterRender);
  54664. this._worker.terminate();
  54665. };
  54666. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54667. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54668. this.onMeshUpdated(mesh);
  54669. };
  54670. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54671. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54672. };
  54673. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54674. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54675. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54676. this.onGeometryUpdated(geometry);
  54677. };
  54678. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54679. this._toRemoveGeometryArray.push(geometry.id);
  54680. };
  54681. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54682. var submeshes = [];
  54683. if (mesh.subMeshes) {
  54684. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54685. var boundingInfo = sm.getBoundingInfo();
  54686. return {
  54687. position: idx,
  54688. verticesStart: sm.verticesStart,
  54689. verticesCount: sm.verticesCount,
  54690. indexStart: sm.indexStart,
  54691. indexCount: sm.indexCount,
  54692. hasMaterial: !!sm.getMaterial(),
  54693. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54694. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54695. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54696. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54697. };
  54698. });
  54699. }
  54700. var geometryId = null;
  54701. if (mesh instanceof BABYLON.Mesh) {
  54702. var geometry = mesh.geometry;
  54703. geometryId = geometry ? geometry.id : null;
  54704. }
  54705. else if (mesh instanceof BABYLON.InstancedMesh) {
  54706. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54707. geometryId = geometry ? geometry.id : null;
  54708. }
  54709. var boundingInfo = mesh.getBoundingInfo();
  54710. return {
  54711. uniqueId: mesh.uniqueId,
  54712. id: mesh.id,
  54713. name: mesh.name,
  54714. geometryId: geometryId,
  54715. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54716. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54717. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54718. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54719. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54720. subMeshes: submeshes,
  54721. checkCollisions: mesh.checkCollisions
  54722. };
  54723. };
  54724. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54725. return {
  54726. id: geometry.id,
  54727. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54728. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54729. indices: new Uint32Array(geometry.getIndices() || []),
  54730. };
  54731. };
  54732. return CollisionCoordinatorWorker;
  54733. }());
  54734. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54735. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54736. function CollisionCoordinatorLegacy() {
  54737. this._scaledPosition = BABYLON.Vector3.Zero();
  54738. this._scaledVelocity = BABYLON.Vector3.Zero();
  54739. this._finalPosition = BABYLON.Vector3.Zero();
  54740. }
  54741. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54742. position.divideToRef(collider._radius, this._scaledPosition);
  54743. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54744. collider.collidedMesh = null;
  54745. collider._retry = 0;
  54746. collider._initialVelocity = this._scaledVelocity;
  54747. collider._initialPosition = this._scaledPosition;
  54748. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54749. this._finalPosition.multiplyInPlace(collider._radius);
  54750. //run the callback
  54751. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54752. };
  54753. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54754. this._scene = scene;
  54755. };
  54756. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54757. //Legacy need no destruction method.
  54758. };
  54759. //No update in legacy mode
  54760. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54761. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54762. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54763. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54764. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54765. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54766. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54767. if (excludedMesh === void 0) { excludedMesh = null; }
  54768. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54769. if (collider._retry >= maximumRetry) {
  54770. finalPosition.copyFrom(position);
  54771. return;
  54772. }
  54773. // Check if this is a mesh else camera or -1
  54774. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54775. collider._initialize(position, velocity, closeDistance);
  54776. // Check all meshes
  54777. for (var index = 0; index < this._scene.meshes.length; index++) {
  54778. var mesh = this._scene.meshes[index];
  54779. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54780. mesh._checkCollision(collider);
  54781. }
  54782. }
  54783. if (!collider.collisionFound) {
  54784. position.addToRef(velocity, finalPosition);
  54785. return;
  54786. }
  54787. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54788. collider._getResponse(position, velocity);
  54789. }
  54790. if (velocity.length() <= closeDistance) {
  54791. finalPosition.copyFrom(position);
  54792. return;
  54793. }
  54794. collider._retry++;
  54795. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54796. };
  54797. return CollisionCoordinatorLegacy;
  54798. }());
  54799. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54800. })(BABYLON || (BABYLON = {}));
  54801. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54802. var BABYLON;
  54803. (function (BABYLON) {
  54804. /**
  54805. * A particle represents one of the element emitted by a particle system.
  54806. * This is mainly define by its coordinates, direction, velocity and age.
  54807. */
  54808. var Particle = /** @class */ (function () {
  54809. /**
  54810. * Creates a new instance Particle
  54811. * @param particleSystem the particle system the particle belongs to
  54812. */
  54813. function Particle(
  54814. /**
  54815. * particleSystem the particle system the particle belongs to.
  54816. */
  54817. particleSystem) {
  54818. this.particleSystem = particleSystem;
  54819. /**
  54820. * The world position of the particle in the scene.
  54821. */
  54822. this.position = BABYLON.Vector3.Zero();
  54823. /**
  54824. * The world direction of the particle in the scene.
  54825. */
  54826. this.direction = BABYLON.Vector3.Zero();
  54827. /**
  54828. * The color of the particle.
  54829. */
  54830. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54831. /**
  54832. * The color change of the particle per step.
  54833. */
  54834. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54835. /**
  54836. * Defines how long will the life of the particle be.
  54837. */
  54838. this.lifeTime = 1.0;
  54839. /**
  54840. * The current age of the particle.
  54841. */
  54842. this.age = 0;
  54843. /**
  54844. * The current size of the particle.
  54845. */
  54846. this.size = 0;
  54847. /**
  54848. * The current scale of the particle.
  54849. */
  54850. this.scale = new BABYLON.Vector2(1, 1);
  54851. /**
  54852. * The current angle of the particle.
  54853. */
  54854. this.angle = 0;
  54855. /**
  54856. * Defines how fast is the angle changing.
  54857. */
  54858. this.angularSpeed = 0;
  54859. /**
  54860. * Defines the cell index used by the particle to be rendered from a sprite.
  54861. */
  54862. this.cellIndex = 0;
  54863. this._currentFrameCounter = 0;
  54864. if (!this.particleSystem.isAnimationSheetEnabled) {
  54865. return;
  54866. }
  54867. this.updateCellInfoFromSystem();
  54868. }
  54869. Particle.prototype.updateCellInfoFromSystem = function () {
  54870. this.cellIndex = this.particleSystem.startSpriteCellID;
  54871. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54872. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54873. }
  54874. else {
  54875. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54876. }
  54877. };
  54878. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54879. // (ageOffset / scaledUpdateSpeed) / available cells
  54880. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54881. this._currentFrameCounter += scaledUpdateSpeed;
  54882. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54883. this._currentFrameCounter = 0;
  54884. this.cellIndex++;
  54885. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54886. this.cellIndex = this.particleSystem.endSpriteCellID;
  54887. }
  54888. }
  54889. };
  54890. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54891. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54892. this.cellIndex++;
  54893. this._currentFrameCounter = 0;
  54894. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54895. if (this.particleSystem.spriteCellLoop) {
  54896. this.cellIndex = this.particleSystem.startSpriteCellID;
  54897. }
  54898. else {
  54899. this.cellIndex = this.particleSystem.endSpriteCellID;
  54900. }
  54901. }
  54902. }
  54903. else {
  54904. this._currentFrameCounter++;
  54905. }
  54906. };
  54907. /**
  54908. * Copy the properties of particle to another one.
  54909. * @param other the particle to copy the information to.
  54910. */
  54911. Particle.prototype.copyTo = function (other) {
  54912. other.position.copyFrom(this.position);
  54913. if (this._initialDirection) {
  54914. if (other._initialDirection) {
  54915. other._initialDirection.copyFrom(this._initialDirection);
  54916. }
  54917. else {
  54918. other._initialDirection = this._initialDirection.clone();
  54919. }
  54920. }
  54921. else {
  54922. other._initialDirection = null;
  54923. }
  54924. other.direction.copyFrom(this.direction);
  54925. other.color.copyFrom(this.color);
  54926. other.colorStep.copyFrom(this.colorStep);
  54927. other.lifeTime = this.lifeTime;
  54928. other.age = this.age;
  54929. other.size = this.size;
  54930. other.scale.copyFrom(this.scale);
  54931. other.angle = this.angle;
  54932. other.angularSpeed = this.angularSpeed;
  54933. other.particleSystem = this.particleSystem;
  54934. other.cellIndex = this.cellIndex;
  54935. };
  54936. return Particle;
  54937. }());
  54938. BABYLON.Particle = Particle;
  54939. })(BABYLON || (BABYLON = {}));
  54940. //# sourceMappingURL=babylon.particle.js.map
  54941. var BABYLON;
  54942. (function (BABYLON) {
  54943. /** @hidden */
  54944. var ColorGradient = /** @class */ (function () {
  54945. function ColorGradient() {
  54946. }
  54947. return ColorGradient;
  54948. }());
  54949. /** @hidden */
  54950. var FactorGradient = /** @class */ (function () {
  54951. function FactorGradient() {
  54952. }
  54953. return FactorGradient;
  54954. }());
  54955. /**
  54956. * This represents a particle system in Babylon.
  54957. * 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.
  54958. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54959. * @example https://doc.babylonjs.com/babylon101/particles
  54960. */
  54961. var ParticleSystem = /** @class */ (function () {
  54962. /**
  54963. * Instantiates a particle system.
  54964. * 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.
  54965. * @param name The name of the particle system
  54966. * @param capacity The max number of particles alive at the same time
  54967. * @param scene The scene the particle system belongs to
  54968. * @param customEffect a custom effect used to change the way particles are rendered by default
  54969. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54970. * @param epsilon Offset used to render the particles
  54971. */
  54972. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54973. if (customEffect === void 0) { customEffect = null; }
  54974. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54975. if (epsilon === void 0) { epsilon = 0.01; }
  54976. var _this = this;
  54977. /**
  54978. * List of animations used by the particle system.
  54979. */
  54980. this.animations = [];
  54981. /**
  54982. * The rendering group used by the Particle system to chose when to render.
  54983. */
  54984. this.renderingGroupId = 0;
  54985. /**
  54986. * The emitter represents the Mesh or position we are attaching the particle system to.
  54987. */
  54988. this.emitter = null;
  54989. /**
  54990. * The maximum number of particles to emit per frame
  54991. */
  54992. this.emitRate = 10;
  54993. /**
  54994. * If you want to launch only a few particles at once, that can be done, as well.
  54995. */
  54996. this.manualEmitCount = -1;
  54997. /**
  54998. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54999. */
  55000. this.updateSpeed = 0.01;
  55001. /**
  55002. * The amount of time the particle system is running (depends of the overall update speed).
  55003. */
  55004. this.targetStopDuration = 0;
  55005. /**
  55006. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55007. */
  55008. this.disposeOnStop = false;
  55009. /**
  55010. * Minimum power of emitting particles.
  55011. */
  55012. this.minEmitPower = 1;
  55013. /**
  55014. * Maximum power of emitting particles.
  55015. */
  55016. this.maxEmitPower = 1;
  55017. /**
  55018. * Minimum life time of emitting particles.
  55019. */
  55020. this.minLifeTime = 1;
  55021. /**
  55022. * Maximum life time of emitting particles.
  55023. */
  55024. this.maxLifeTime = 1;
  55025. /**
  55026. * Minimum Size of emitting particles.
  55027. */
  55028. this.minSize = 1;
  55029. /**
  55030. * Maximum Size of emitting particles.
  55031. */
  55032. this.maxSize = 1;
  55033. /**
  55034. * Minimum scale of emitting particles on X axis.
  55035. */
  55036. this.minScaleX = 1;
  55037. /**
  55038. * Maximum scale of emitting particles on X axis.
  55039. */
  55040. this.maxScaleX = 1;
  55041. /**
  55042. * Minimum scale of emitting particles on Y axis.
  55043. */
  55044. this.minScaleY = 1;
  55045. /**
  55046. * Maximum scale of emitting particles on Y axis.
  55047. */
  55048. this.maxScaleY = 1;
  55049. /**
  55050. * Gets or sets the minimal initial rotation in radians.
  55051. */
  55052. this.minInitialRotation = 0;
  55053. /**
  55054. * Gets or sets the maximal initial rotation in radians.
  55055. */
  55056. this.maxInitialRotation = 0;
  55057. /**
  55058. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55059. */
  55060. this.minAngularSpeed = 0;
  55061. /**
  55062. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55063. */
  55064. this.maxAngularSpeed = 0;
  55065. /**
  55066. * The layer mask we are rendering the particles through.
  55067. */
  55068. this.layerMask = 0x0FFFFFFF;
  55069. /**
  55070. * This can help using your own shader to render the particle system.
  55071. * The according effect will be created
  55072. */
  55073. this.customShader = null;
  55074. /**
  55075. * By default particle system starts as soon as they are created. This prevents the
  55076. * automatic start to happen and let you decide when to start emitting particles.
  55077. */
  55078. this.preventAutoStart = false;
  55079. /**
  55080. * Callback triggered when the particle animation is ending.
  55081. */
  55082. this.onAnimationEnd = null;
  55083. /**
  55084. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55085. */
  55086. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55087. /**
  55088. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55089. * to override the particles.
  55090. */
  55091. this.forceDepthWrite = false;
  55092. /**
  55093. * You can use gravity if you want to give an orientation to your particles.
  55094. */
  55095. this.gravity = BABYLON.Vector3.Zero();
  55096. this._colorGradients = null;
  55097. this._sizeGradients = null;
  55098. /**
  55099. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55100. */
  55101. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55102. /**
  55103. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55104. */
  55105. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55106. /**
  55107. * Color the particle will have at the end of its lifetime
  55108. */
  55109. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55110. /**
  55111. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55112. */
  55113. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55114. /**
  55115. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55116. */
  55117. this.spriteCellLoop = true;
  55118. /**
  55119. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55120. */
  55121. this.spriteCellChangeSpeed = 0;
  55122. /**
  55123. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55124. */
  55125. this.startSpriteCellID = 0;
  55126. /**
  55127. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55128. */
  55129. this.endSpriteCellID = 0;
  55130. /**
  55131. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55132. */
  55133. this.spriteCellWidth = 0;
  55134. /**
  55135. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55136. */
  55137. this.spriteCellHeight = 0;
  55138. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55139. this.preWarmCycles = 0;
  55140. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55141. this.preWarmStepOffset = 1;
  55142. /**
  55143. * An event triggered when the system is disposed
  55144. */
  55145. this.onDisposeObservable = new BABYLON.Observable();
  55146. this._particles = new Array();
  55147. this._stockParticles = new Array();
  55148. this._newPartsExcess = 0;
  55149. this._vertexBuffers = {};
  55150. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55151. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55152. this._scaledDirection = BABYLON.Vector3.Zero();
  55153. this._scaledGravity = BABYLON.Vector3.Zero();
  55154. this._currentRenderId = -1;
  55155. this._useInstancing = false;
  55156. this._started = false;
  55157. this._stopped = false;
  55158. this._actualFrame = 0;
  55159. this._isBillboardBased = true;
  55160. // start of sub system methods
  55161. /**
  55162. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55163. * Its lifetime will start back at 0.
  55164. */
  55165. this.recycleParticle = function (particle) {
  55166. var lastParticle = _this._particles.pop();
  55167. if (lastParticle !== particle) {
  55168. lastParticle.copyTo(particle);
  55169. }
  55170. _this._stockParticles.push(lastParticle);
  55171. };
  55172. this._createParticle = function () {
  55173. var particle;
  55174. if (_this._stockParticles.length !== 0) {
  55175. particle = _this._stockParticles.pop();
  55176. particle.age = 0;
  55177. particle.cellIndex = _this.startSpriteCellID;
  55178. }
  55179. else {
  55180. particle = new BABYLON.Particle(_this);
  55181. }
  55182. return particle;
  55183. };
  55184. this._emitFromParticle = function (particle) {
  55185. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55186. return;
  55187. }
  55188. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55189. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55190. subSystem._rootParticleSystem = _this;
  55191. _this.activeSubSystems.push(subSystem);
  55192. subSystem.start();
  55193. };
  55194. this.id = name;
  55195. this.name = name;
  55196. this._capacity = capacity;
  55197. this._epsilon = epsilon;
  55198. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55199. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55200. this._customEffect = customEffect;
  55201. scene.particleSystems.push(this);
  55202. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55203. this._createIndexBuffer();
  55204. this._createVertexBuffers();
  55205. // Default emitter type
  55206. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55207. this.updateFunction = function (particles) {
  55208. for (var index = 0; index < particles.length; index++) {
  55209. var particle = particles[index];
  55210. particle.age += _this._scaledUpdateSpeed;
  55211. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55212. _this._emitFromParticle(particle);
  55213. _this.recycleParticle(particle);
  55214. index--;
  55215. continue;
  55216. }
  55217. else {
  55218. var ratio = particle.age / particle.lifeTime;
  55219. // Color
  55220. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55221. _this._getCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55222. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  55223. });
  55224. }
  55225. else {
  55226. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55227. particle.color.addInPlace(_this._scaledColorStep);
  55228. if (particle.color.a < 0) {
  55229. particle.color.a = 0;
  55230. }
  55231. }
  55232. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55233. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55234. particle.position.addInPlace(_this._scaledDirection);
  55235. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55236. particle.direction.addInPlace(_this._scaledGravity);
  55237. // Gradient
  55238. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55239. _this._getCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55240. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55241. });
  55242. }
  55243. if (_this._isAnimationSheetEnabled) {
  55244. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55245. }
  55246. }
  55247. }
  55248. };
  55249. }
  55250. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55251. /**
  55252. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55253. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55254. */
  55255. get: function () {
  55256. if (this.particleEmitterType.direction1) {
  55257. return this.particleEmitterType.direction1;
  55258. }
  55259. return BABYLON.Vector3.Zero();
  55260. },
  55261. set: function (value) {
  55262. if (this.particleEmitterType.direction1) {
  55263. this.particleEmitterType.direction1 = value;
  55264. }
  55265. },
  55266. enumerable: true,
  55267. configurable: true
  55268. });
  55269. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55270. /**
  55271. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55272. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55273. */
  55274. get: function () {
  55275. if (this.particleEmitterType.direction2) {
  55276. return this.particleEmitterType.direction2;
  55277. }
  55278. return BABYLON.Vector3.Zero();
  55279. },
  55280. set: function (value) {
  55281. if (this.particleEmitterType.direction2) {
  55282. this.particleEmitterType.direction2 = value;
  55283. }
  55284. },
  55285. enumerable: true,
  55286. configurable: true
  55287. });
  55288. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55289. /**
  55290. * 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.
  55291. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55292. */
  55293. get: function () {
  55294. if (this.particleEmitterType.minEmitBox) {
  55295. return this.particleEmitterType.minEmitBox;
  55296. }
  55297. return BABYLON.Vector3.Zero();
  55298. },
  55299. set: function (value) {
  55300. if (this.particleEmitterType.minEmitBox) {
  55301. this.particleEmitterType.minEmitBox = value;
  55302. }
  55303. },
  55304. enumerable: true,
  55305. configurable: true
  55306. });
  55307. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55308. /**
  55309. * 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.
  55310. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55311. */
  55312. get: function () {
  55313. if (this.particleEmitterType.maxEmitBox) {
  55314. return this.particleEmitterType.maxEmitBox;
  55315. }
  55316. return BABYLON.Vector3.Zero();
  55317. },
  55318. set: function (value) {
  55319. if (this.particleEmitterType.maxEmitBox) {
  55320. this.particleEmitterType.maxEmitBox = value;
  55321. }
  55322. },
  55323. enumerable: true,
  55324. configurable: true
  55325. });
  55326. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55327. /**
  55328. * Sets a callback that will be triggered when the system is disposed
  55329. */
  55330. set: function (callback) {
  55331. if (this._onDisposeObserver) {
  55332. this.onDisposeObservable.remove(this._onDisposeObserver);
  55333. }
  55334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55335. },
  55336. enumerable: true,
  55337. configurable: true
  55338. });
  55339. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55340. /**
  55341. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55342. */
  55343. get: function () {
  55344. return this._isAnimationSheetEnabled;
  55345. },
  55346. enumerable: true,
  55347. configurable: true
  55348. });
  55349. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55350. /**
  55351. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55352. */
  55353. get: function () {
  55354. return this._isBillboardBased;
  55355. },
  55356. set: function (value) {
  55357. if (this._isBillboardBased === value) {
  55358. return;
  55359. }
  55360. this._isBillboardBased = value;
  55361. this._resetEffect();
  55362. },
  55363. enumerable: true,
  55364. configurable: true
  55365. });
  55366. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55367. //end of Sub-emitter
  55368. /**
  55369. * Gets the current list of active particles
  55370. */
  55371. get: function () {
  55372. return this._particles;
  55373. },
  55374. enumerable: true,
  55375. configurable: true
  55376. });
  55377. /**
  55378. * Returns the string "ParticleSystem"
  55379. * @returns a string containing the class name
  55380. */
  55381. ParticleSystem.prototype.getClassName = function () {
  55382. return "ParticleSystem";
  55383. };
  55384. ParticleSystem.prototype._getCurrentGradient = function (ratio, gradients, updateFunc) {
  55385. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  55386. var currentGradient = gradients[gradientIndex];
  55387. var nextGradient = gradients[gradientIndex + 1];
  55388. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  55389. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  55390. updateFunc(currentGradient, nextGradient, scale);
  55391. }
  55392. }
  55393. };
  55394. /**
  55395. * Adds a new size gradient
  55396. * @param gradient defines the gradient to use (between 0 and 1)
  55397. * @param factor defines the size factor to affect to the specified gradient
  55398. */
  55399. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55400. if (!this._sizeGradients) {
  55401. this._sizeGradients = [];
  55402. }
  55403. var sizeGradient = new FactorGradient();
  55404. sizeGradient.gradient = gradient;
  55405. sizeGradient.factor = factor;
  55406. this._sizeGradients.push(sizeGradient);
  55407. this._sizeGradients.sort(function (a, b) {
  55408. if (a.gradient < b.gradient) {
  55409. return -1;
  55410. }
  55411. else if (a.gradient > b.gradient) {
  55412. return 1;
  55413. }
  55414. return 0;
  55415. });
  55416. return this;
  55417. };
  55418. /**
  55419. * Remove a specific size gradient
  55420. * @param gradient defines the gradient to remove
  55421. */
  55422. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55423. if (!this._sizeGradients) {
  55424. return this;
  55425. }
  55426. var index = 0;
  55427. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55428. var sizeGradient = _a[_i];
  55429. if (sizeGradient.gradient === gradient) {
  55430. this._sizeGradients.splice(index, 1);
  55431. break;
  55432. }
  55433. index++;
  55434. }
  55435. return this;
  55436. };
  55437. /**
  55438. * Adds a new color gradient
  55439. * @param gradient defines the gradient to use (between 0 and 1)
  55440. * @param color defines the color to affect to the specified gradient
  55441. */
  55442. ParticleSystem.prototype.addColorGradient = function (gradient, color) {
  55443. if (!this._colorGradients) {
  55444. this._colorGradients = [];
  55445. }
  55446. var colorGradient = new ColorGradient();
  55447. colorGradient.gradient = gradient;
  55448. colorGradient.color = color;
  55449. this._colorGradients.push(colorGradient);
  55450. this._colorGradients.sort(function (a, b) {
  55451. if (a.gradient < b.gradient) {
  55452. return -1;
  55453. }
  55454. else if (a.gradient > b.gradient) {
  55455. return 1;
  55456. }
  55457. return 0;
  55458. });
  55459. return this;
  55460. };
  55461. /**
  55462. * Remove a specific color gradient
  55463. * @param gradient defines the gradient to remove
  55464. */
  55465. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55466. if (!this._colorGradients) {
  55467. return this;
  55468. }
  55469. var index = 0;
  55470. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55471. var colorGradient = _a[_i];
  55472. if (colorGradient.gradient === gradient) {
  55473. this._colorGradients.splice(index, 1);
  55474. break;
  55475. }
  55476. index++;
  55477. }
  55478. return this;
  55479. };
  55480. ParticleSystem.prototype._resetEffect = function () {
  55481. if (this._vertexBuffer) {
  55482. this._vertexBuffer.dispose();
  55483. this._vertexBuffer = null;
  55484. }
  55485. if (this._spriteBuffer) {
  55486. this._spriteBuffer.dispose();
  55487. this._spriteBuffer = null;
  55488. }
  55489. this._createVertexBuffers();
  55490. };
  55491. ParticleSystem.prototype._createVertexBuffers = function () {
  55492. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55493. if (this._isAnimationSheetEnabled) {
  55494. this._vertexBufferSize += 1;
  55495. }
  55496. if (!this._isBillboardBased) {
  55497. this._vertexBufferSize += 3;
  55498. }
  55499. var engine = this._scene.getEngine();
  55500. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55501. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55502. var dataOffset = 0;
  55503. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55504. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55505. dataOffset += 3;
  55506. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55507. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55508. dataOffset += 4;
  55509. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55510. this._vertexBuffers["angle"] = options;
  55511. dataOffset += 1;
  55512. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55513. this._vertexBuffers["size"] = size;
  55514. dataOffset += 2;
  55515. if (this._isAnimationSheetEnabled) {
  55516. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55517. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55518. dataOffset += 1;
  55519. }
  55520. if (!this._isBillboardBased) {
  55521. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55522. this._vertexBuffers["direction"] = directionBuffer;
  55523. dataOffset += 3;
  55524. }
  55525. var offsets;
  55526. if (this._useInstancing) {
  55527. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55528. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55529. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55530. }
  55531. else {
  55532. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55533. dataOffset += 2;
  55534. }
  55535. this._vertexBuffers["offset"] = offsets;
  55536. };
  55537. ParticleSystem.prototype._createIndexBuffer = function () {
  55538. if (this._useInstancing) {
  55539. return;
  55540. }
  55541. var indices = [];
  55542. var index = 0;
  55543. for (var count = 0; count < this._capacity; count++) {
  55544. indices.push(index);
  55545. indices.push(index + 1);
  55546. indices.push(index + 2);
  55547. indices.push(index);
  55548. indices.push(index + 2);
  55549. indices.push(index + 3);
  55550. index += 4;
  55551. }
  55552. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55553. };
  55554. /**
  55555. * Gets the maximum number of particles active at the same time.
  55556. * @returns The max number of active particles.
  55557. */
  55558. ParticleSystem.prototype.getCapacity = function () {
  55559. return this._capacity;
  55560. };
  55561. /**
  55562. * Gets Wether there are still active particles in the system.
  55563. * @returns True if it is alive, otherwise false.
  55564. */
  55565. ParticleSystem.prototype.isAlive = function () {
  55566. return this._alive;
  55567. };
  55568. /**
  55569. * Gets Wether the system has been started.
  55570. * @returns True if it has been started, otherwise false.
  55571. */
  55572. ParticleSystem.prototype.isStarted = function () {
  55573. return this._started;
  55574. };
  55575. /**
  55576. * Starts the particle system and begins to emit.
  55577. */
  55578. ParticleSystem.prototype.start = function () {
  55579. this._started = true;
  55580. this._stopped = false;
  55581. this._actualFrame = 0;
  55582. if (this.subEmitters && this.subEmitters.length != 0) {
  55583. this.activeSubSystems = new Array();
  55584. }
  55585. if (this.preWarmCycles) {
  55586. for (var index = 0; index < this.preWarmCycles; index++) {
  55587. this.animate(true);
  55588. }
  55589. }
  55590. };
  55591. /**
  55592. * Stops the particle system.
  55593. * @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.
  55594. */
  55595. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55596. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55597. this._stopped = true;
  55598. if (stopSubEmitters) {
  55599. this._stopSubEmitters();
  55600. }
  55601. };
  55602. // animation sheet
  55603. /**
  55604. * Remove all active particles
  55605. */
  55606. ParticleSystem.prototype.reset = function () {
  55607. this._stockParticles = [];
  55608. this._particles = [];
  55609. };
  55610. /**
  55611. * @hidden (for internal use only)
  55612. */
  55613. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55614. var offset = index * this._vertexBufferSize;
  55615. this._vertexData[offset++] = particle.position.x;
  55616. this._vertexData[offset++] = particle.position.y;
  55617. this._vertexData[offset++] = particle.position.z;
  55618. this._vertexData[offset++] = particle.color.r;
  55619. this._vertexData[offset++] = particle.color.g;
  55620. this._vertexData[offset++] = particle.color.b;
  55621. this._vertexData[offset++] = particle.color.a;
  55622. this._vertexData[offset++] = particle.angle;
  55623. this._vertexData[offset++] = particle.scale.x * particle.size;
  55624. this._vertexData[offset++] = particle.scale.y * particle.size;
  55625. if (this._isAnimationSheetEnabled) {
  55626. this._vertexData[offset++] = particle.cellIndex;
  55627. }
  55628. if (!this._isBillboardBased) {
  55629. if (particle._initialDirection) {
  55630. this._vertexData[offset++] = particle._initialDirection.x;
  55631. this._vertexData[offset++] = particle._initialDirection.y;
  55632. this._vertexData[offset++] = particle._initialDirection.z;
  55633. }
  55634. else {
  55635. this._vertexData[offset++] = particle.direction.x;
  55636. this._vertexData[offset++] = particle.direction.y;
  55637. this._vertexData[offset++] = particle.direction.z;
  55638. }
  55639. }
  55640. if (!this._useInstancing) {
  55641. if (this._isAnimationSheetEnabled) {
  55642. if (offsetX === 0)
  55643. offsetX = this._epsilon;
  55644. else if (offsetX === 1)
  55645. offsetX = 1 - this._epsilon;
  55646. if (offsetY === 0)
  55647. offsetY = this._epsilon;
  55648. else if (offsetY === 1)
  55649. offsetY = 1 - this._epsilon;
  55650. }
  55651. this._vertexData[offset++] = offsetX;
  55652. this._vertexData[offset++] = offsetY;
  55653. }
  55654. };
  55655. ParticleSystem.prototype._stopSubEmitters = function () {
  55656. if (!this.activeSubSystems) {
  55657. return;
  55658. }
  55659. this.activeSubSystems.forEach(function (subSystem) {
  55660. subSystem.stop(true);
  55661. });
  55662. this.activeSubSystems = new Array();
  55663. };
  55664. ParticleSystem.prototype._removeFromRoot = function () {
  55665. if (!this._rootParticleSystem) {
  55666. return;
  55667. }
  55668. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55669. if (index !== -1) {
  55670. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55671. }
  55672. };
  55673. // end of sub system methods
  55674. ParticleSystem.prototype._update = function (newParticles) {
  55675. // Update current
  55676. this._alive = this._particles.length > 0;
  55677. this.updateFunction(this._particles);
  55678. // Add new ones
  55679. var worldMatrix;
  55680. if (this.emitter.position) {
  55681. var emitterMesh = this.emitter;
  55682. worldMatrix = emitterMesh.getWorldMatrix();
  55683. }
  55684. else {
  55685. var emitterPosition = this.emitter;
  55686. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55687. }
  55688. var particle;
  55689. for (var index = 0; index < newParticles; index++) {
  55690. if (this._particles.length === this._capacity) {
  55691. break;
  55692. }
  55693. particle = this._createParticle();
  55694. this._particles.push(particle);
  55695. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55696. if (this.startPositionFunction) {
  55697. this.startPositionFunction(worldMatrix, particle.position, particle);
  55698. }
  55699. else {
  55700. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55701. }
  55702. if (this.startDirectionFunction) {
  55703. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55704. }
  55705. else {
  55706. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55707. }
  55708. if (emitPower === 0) {
  55709. if (!particle._initialDirection) {
  55710. particle._initialDirection = particle.direction.clone();
  55711. }
  55712. else {
  55713. particle._initialDirection.copyFrom(particle.direction);
  55714. }
  55715. }
  55716. else {
  55717. particle._initialDirection = null;
  55718. }
  55719. particle.direction.scaleInPlace(emitPower);
  55720. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55721. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55722. particle._initialSize = particle.size;
  55723. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55724. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55725. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55726. if (!this._colorGradients || this._colorGradients.length === 0) {
  55727. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55728. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55729. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55730. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55731. }
  55732. else {
  55733. particle.color.copyFrom(this._colorGradients[0].color);
  55734. }
  55735. }
  55736. };
  55737. ParticleSystem.prototype._getEffect = function () {
  55738. if (this._customEffect) {
  55739. return this._customEffect;
  55740. }
  55741. ;
  55742. var defines = [];
  55743. if (this._scene.clipPlane) {
  55744. defines.push("#define CLIPPLANE");
  55745. }
  55746. if (this._isAnimationSheetEnabled) {
  55747. defines.push("#define ANIMATESHEET");
  55748. }
  55749. if (this._isBillboardBased) {
  55750. defines.push("#define BILLBOARD");
  55751. }
  55752. // Effect
  55753. var join = defines.join("\n");
  55754. if (this._cachedDefines !== join) {
  55755. this._cachedDefines = join;
  55756. var attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55757. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55758. if (this._isAnimationSheetEnabled) {
  55759. attributesNamesOrOptions.push("cellIndex");
  55760. effectCreationOption.push("particlesInfos");
  55761. }
  55762. if (!this._isBillboardBased) {
  55763. attributesNamesOrOptions.push("direction");
  55764. }
  55765. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55766. }
  55767. return this._effect;
  55768. };
  55769. /**
  55770. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55771. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55772. */
  55773. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55774. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55775. if (!this._started)
  55776. return;
  55777. if (!preWarmOnly) {
  55778. var effect = this._getEffect();
  55779. // Check
  55780. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55781. return;
  55782. if (this._currentRenderId === this._scene.getRenderId()) {
  55783. return;
  55784. }
  55785. this._currentRenderId = this._scene.getRenderId();
  55786. }
  55787. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55788. // determine the number of particles we need to create
  55789. var newParticles;
  55790. if (this.manualEmitCount > -1) {
  55791. newParticles = this.manualEmitCount;
  55792. this._newPartsExcess = 0;
  55793. this.manualEmitCount = 0;
  55794. }
  55795. else {
  55796. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55797. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55798. }
  55799. if (this._newPartsExcess > 1.0) {
  55800. newParticles += this._newPartsExcess >> 0;
  55801. this._newPartsExcess -= this._newPartsExcess >> 0;
  55802. }
  55803. this._alive = false;
  55804. if (!this._stopped) {
  55805. this._actualFrame += this._scaledUpdateSpeed;
  55806. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55807. this.stop();
  55808. }
  55809. else {
  55810. newParticles = 0;
  55811. }
  55812. this._update(newParticles);
  55813. // Stopped?
  55814. if (this._stopped) {
  55815. if (!this._alive) {
  55816. this._started = false;
  55817. if (this.onAnimationEnd) {
  55818. this.onAnimationEnd();
  55819. }
  55820. if (this.disposeOnStop) {
  55821. this._scene._toBeDisposed.push(this);
  55822. }
  55823. }
  55824. }
  55825. if (!preWarmOnly) {
  55826. // Update VBO
  55827. var offset = 0;
  55828. for (var index = 0; index < this._particles.length; index++) {
  55829. var particle = this._particles[index];
  55830. this._appendParticleVertices(offset, particle);
  55831. offset += this._useInstancing ? 1 : 4;
  55832. }
  55833. if (this._vertexBuffer) {
  55834. this._vertexBuffer.update(this._vertexData);
  55835. }
  55836. }
  55837. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55838. this.stop();
  55839. }
  55840. };
  55841. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55842. this._appendParticleVertex(offset++, particle, 0, 0);
  55843. if (!this._useInstancing) {
  55844. this._appendParticleVertex(offset++, particle, 1, 0);
  55845. this._appendParticleVertex(offset++, particle, 1, 1);
  55846. this._appendParticleVertex(offset++, particle, 0, 1);
  55847. }
  55848. };
  55849. /**
  55850. * Rebuilds the particle system.
  55851. */
  55852. ParticleSystem.prototype.rebuild = function () {
  55853. this._createIndexBuffer();
  55854. if (this._vertexBuffer) {
  55855. this._vertexBuffer._rebuild();
  55856. }
  55857. };
  55858. /**
  55859. * Is this system ready to be used/rendered
  55860. * @return true if the system is ready
  55861. */
  55862. ParticleSystem.prototype.isReady = function () {
  55863. var effect = this._getEffect();
  55864. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55865. return false;
  55866. }
  55867. return true;
  55868. };
  55869. /**
  55870. * Renders the particle system in its current state.
  55871. * @returns the current number of particles
  55872. */
  55873. ParticleSystem.prototype.render = function () {
  55874. var effect = this._getEffect();
  55875. // Check
  55876. if (!this.isReady() || !this._particles.length) {
  55877. return 0;
  55878. }
  55879. var engine = this._scene.getEngine();
  55880. // Render
  55881. engine.enableEffect(effect);
  55882. engine.setState(false);
  55883. var viewMatrix = this._scene.getViewMatrix();
  55884. effect.setTexture("diffuseSampler", this.particleTexture);
  55885. effect.setMatrix("view", viewMatrix);
  55886. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55887. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55888. var baseSize = this.particleTexture.getBaseSize();
  55889. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55890. }
  55891. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55892. if (this._scene.clipPlane) {
  55893. var clipPlane = this._scene.clipPlane;
  55894. var invView = viewMatrix.clone();
  55895. invView.invert();
  55896. effect.setMatrix("invView", invView);
  55897. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55898. }
  55899. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55900. // Draw order
  55901. switch (this.blendMode) {
  55902. case ParticleSystem.BLENDMODE_ADD:
  55903. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55904. break;
  55905. case ParticleSystem.BLENDMODE_ONEONE:
  55906. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55907. break;
  55908. case ParticleSystem.BLENDMODE_STANDARD:
  55909. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55910. break;
  55911. }
  55912. if (this.forceDepthWrite) {
  55913. engine.setDepthWrite(true);
  55914. }
  55915. if (this._useInstancing) {
  55916. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55917. engine.unbindInstanceAttributes();
  55918. }
  55919. else {
  55920. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55921. }
  55922. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55923. return this._particles.length;
  55924. };
  55925. /**
  55926. * Disposes the particle system and free the associated resources
  55927. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55928. */
  55929. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55930. if (disposeTexture === void 0) { disposeTexture = true; }
  55931. if (this._vertexBuffer) {
  55932. this._vertexBuffer.dispose();
  55933. this._vertexBuffer = null;
  55934. }
  55935. if (this._spriteBuffer) {
  55936. this._spriteBuffer.dispose();
  55937. this._spriteBuffer = null;
  55938. }
  55939. if (this._indexBuffer) {
  55940. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55941. this._indexBuffer = null;
  55942. }
  55943. if (disposeTexture && this.particleTexture) {
  55944. this.particleTexture.dispose();
  55945. this.particleTexture = null;
  55946. }
  55947. this._removeFromRoot();
  55948. // Remove from scene
  55949. var index = this._scene.particleSystems.indexOf(this);
  55950. if (index > -1) {
  55951. this._scene.particleSystems.splice(index, 1);
  55952. }
  55953. // Callback
  55954. this.onDisposeObservable.notifyObservers(this);
  55955. this.onDisposeObservable.clear();
  55956. };
  55957. /**
  55958. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55959. * @param radius The radius of the sphere to emit from
  55960. * @returns the emitter
  55961. */
  55962. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55963. if (radius === void 0) { radius = 1; }
  55964. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55965. this.particleEmitterType = particleEmitter;
  55966. return particleEmitter;
  55967. };
  55968. /**
  55969. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55970. * @param radius The radius of the sphere to emit from
  55971. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55972. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55973. * @returns the emitter
  55974. */
  55975. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55976. if (radius === void 0) { radius = 1; }
  55977. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55978. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55979. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55980. this.particleEmitterType = particleEmitter;
  55981. return particleEmitter;
  55982. };
  55983. /**
  55984. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55985. * @param radius The radius of the cone to emit from
  55986. * @param angle The base angle of the cone
  55987. * @returns the emitter
  55988. */
  55989. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55990. if (radius === void 0) { radius = 1; }
  55991. if (angle === void 0) { angle = Math.PI / 4; }
  55992. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55993. this.particleEmitterType = particleEmitter;
  55994. return particleEmitter;
  55995. };
  55996. // 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.
  55997. /**
  55998. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55999. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56000. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56001. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56002. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56003. * @returns the emitter
  56004. */
  56005. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56006. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56007. this.particleEmitterType = particleEmitter;
  56008. this.direction1 = direction1;
  56009. this.direction2 = direction2;
  56010. this.minEmitBox = minEmitBox;
  56011. this.maxEmitBox = maxEmitBox;
  56012. return particleEmitter;
  56013. };
  56014. // Clone
  56015. /**
  56016. * Clones the particle system.
  56017. * @param name The name of the cloned object
  56018. * @param newEmitter The new emitter to use
  56019. * @returns the cloned particle system
  56020. */
  56021. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56022. var custom = null;
  56023. var program = null;
  56024. if (this.customShader != null) {
  56025. program = this.customShader;
  56026. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56027. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56028. }
  56029. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56030. result.customShader = program;
  56031. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56032. if (newEmitter === undefined) {
  56033. newEmitter = this.emitter;
  56034. }
  56035. result.emitter = newEmitter;
  56036. if (this.particleTexture) {
  56037. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56038. }
  56039. if (!this.preventAutoStart) {
  56040. result.start();
  56041. }
  56042. return result;
  56043. };
  56044. /**
  56045. * Serializes the particle system to a JSON object.
  56046. * @returns the JSON object
  56047. */
  56048. ParticleSystem.prototype.serialize = function () {
  56049. var serializationObject = {};
  56050. serializationObject.name = this.name;
  56051. serializationObject.id = this.id;
  56052. // Emitter
  56053. if (this.emitter.position) {
  56054. var emitterMesh = this.emitter;
  56055. serializationObject.emitterId = emitterMesh.id;
  56056. }
  56057. else {
  56058. var emitterPosition = this.emitter;
  56059. serializationObject.emitter = emitterPosition.asArray();
  56060. }
  56061. serializationObject.capacity = this.getCapacity();
  56062. if (this.particleTexture) {
  56063. serializationObject.textureName = this.particleTexture.name;
  56064. }
  56065. // Animations
  56066. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56067. // Particle system
  56068. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56069. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56070. serializationObject.minSize = this.minSize;
  56071. serializationObject.maxSize = this.maxSize;
  56072. serializationObject.minScaleX = this.minScaleX;
  56073. serializationObject.maxScaleX = this.maxScaleX;
  56074. serializationObject.minScaleY = this.minScaleY;
  56075. serializationObject.maxScaleY = this.maxScaleY;
  56076. serializationObject.minEmitPower = this.minEmitPower;
  56077. serializationObject.maxEmitPower = this.maxEmitPower;
  56078. serializationObject.minLifeTime = this.minLifeTime;
  56079. serializationObject.maxLifeTime = this.maxLifeTime;
  56080. serializationObject.emitRate = this.emitRate;
  56081. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56082. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56083. serializationObject.gravity = this.gravity.asArray();
  56084. serializationObject.direction1 = this.direction1.asArray();
  56085. serializationObject.direction2 = this.direction2.asArray();
  56086. serializationObject.color1 = this.color1.asArray();
  56087. serializationObject.color2 = this.color2.asArray();
  56088. serializationObject.colorDead = this.colorDead.asArray();
  56089. serializationObject.updateSpeed = this.updateSpeed;
  56090. serializationObject.targetStopDuration = this.targetStopDuration;
  56091. serializationObject.textureMask = this.textureMask.asArray();
  56092. serializationObject.blendMode = this.blendMode;
  56093. serializationObject.customShader = this.customShader;
  56094. serializationObject.preventAutoStart = this.preventAutoStart;
  56095. serializationObject.preWarmCycles = this.preWarmCycles;
  56096. serializationObject.preWarmStepOffset = this.preWarmStepOffset;
  56097. serializationObject.minInitialRotation = this.minInitialRotation;
  56098. serializationObject.maxInitialRotation = this.maxInitialRotation;
  56099. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56100. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56101. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56102. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56103. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56104. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56105. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56106. // Emitter
  56107. if (this.particleEmitterType) {
  56108. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56109. }
  56110. return serializationObject;
  56111. };
  56112. /**
  56113. * Parses a JSON object to create a particle system.
  56114. * @param parsedParticleSystem The JSON object to parse
  56115. * @param scene The scene to create the particle system in
  56116. * @param rootUrl The root url to use to load external dependencies like texture
  56117. * @returns the Parsed particle system
  56118. */
  56119. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56120. var name = parsedParticleSystem.name;
  56121. var custom = null;
  56122. var program = null;
  56123. if (parsedParticleSystem.customShader) {
  56124. program = parsedParticleSystem.customShader;
  56125. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56126. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56127. }
  56128. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56129. particleSystem.customShader = program;
  56130. if (parsedParticleSystem.id) {
  56131. particleSystem.id = parsedParticleSystem.id;
  56132. }
  56133. // Auto start
  56134. if (parsedParticleSystem.preventAutoStart) {
  56135. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56136. }
  56137. // Texture
  56138. if (parsedParticleSystem.textureName) {
  56139. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56140. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56141. }
  56142. // Emitter
  56143. if (parsedParticleSystem.emitterId) {
  56144. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56145. }
  56146. else {
  56147. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56148. }
  56149. // Animations
  56150. if (parsedParticleSystem.animations) {
  56151. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56152. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56153. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56154. }
  56155. }
  56156. if (parsedParticleSystem.autoAnimate) {
  56157. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56158. }
  56159. // Particle system
  56160. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56161. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56162. particleSystem.minSize = parsedParticleSystem.minSize;
  56163. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56164. if (parsedParticleSystem.minScaleX) {
  56165. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56166. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56167. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56168. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56169. }
  56170. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56171. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56172. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56173. }
  56174. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56175. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56176. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56177. }
  56178. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56179. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56180. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56181. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56182. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56183. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56184. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56185. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56186. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56187. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56188. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56189. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56190. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56191. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56192. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56193. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56194. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56195. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56196. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56197. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56198. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56199. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56200. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56201. if (!particleSystem.preventAutoStart) {
  56202. particleSystem.start();
  56203. }
  56204. return particleSystem;
  56205. };
  56206. /**
  56207. * Source color is added to the destination color without alpha affecting the result.
  56208. */
  56209. ParticleSystem.BLENDMODE_ONEONE = 0;
  56210. /**
  56211. * Blend current color and particle color using particle’s alpha.
  56212. */
  56213. ParticleSystem.BLENDMODE_STANDARD = 1;
  56214. /**
  56215. * Add current color and particle color multiplied by particle’s alpha.
  56216. */
  56217. ParticleSystem.BLENDMODE_ADD = 2;
  56218. return ParticleSystem;
  56219. }());
  56220. BABYLON.ParticleSystem = ParticleSystem;
  56221. })(BABYLON || (BABYLON = {}));
  56222. //# sourceMappingURL=babylon.particleSystem.js.map
  56223. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56224. var BABYLON;
  56225. (function (BABYLON) {
  56226. /**
  56227. * Particle emitter emitting particles from the inside of a box.
  56228. * It emits the particles randomly between 2 given directions.
  56229. */
  56230. var BoxParticleEmitter = /** @class */ (function () {
  56231. /**
  56232. * Creates a new instance BoxParticleEmitter
  56233. */
  56234. function BoxParticleEmitter() {
  56235. /**
  56236. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56237. */
  56238. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56239. /**
  56240. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56241. */
  56242. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56243. /**
  56244. * 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.
  56245. */
  56246. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56247. /**
  56248. * 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.
  56249. */
  56250. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56251. }
  56252. /**
  56253. * Called by the particle System when the direction is computed for the created particle.
  56254. * @param worldMatrix is the world matrix of the particle system
  56255. * @param directionToUpdate is the direction vector to update with the result
  56256. * @param particle is the particle we are computed the direction for
  56257. */
  56258. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56259. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56260. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56261. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56262. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56263. };
  56264. /**
  56265. * Called by the particle System when the position is computed for the created particle.
  56266. * @param worldMatrix is the world matrix of the particle system
  56267. * @param positionToUpdate is the position vector to update with the result
  56268. * @param particle is the particle we are computed the position for
  56269. */
  56270. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56271. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56272. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56273. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56275. };
  56276. /**
  56277. * Clones the current emitter and returns a copy of it
  56278. * @returns the new emitter
  56279. */
  56280. BoxParticleEmitter.prototype.clone = function () {
  56281. var newOne = new BoxParticleEmitter();
  56282. BABYLON.Tools.DeepCopy(this, newOne);
  56283. return newOne;
  56284. };
  56285. /**
  56286. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56287. * @param effect defines the update shader
  56288. */
  56289. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56290. effect.setVector3("direction1", this.direction1);
  56291. effect.setVector3("direction2", this.direction2);
  56292. effect.setVector3("minEmitBox", this.minEmitBox);
  56293. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56294. };
  56295. /**
  56296. * Returns a string to use to update the GPU particles update shader
  56297. * @returns a string containng the defines string
  56298. */
  56299. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56300. return "#define BOXEMITTER";
  56301. };
  56302. /**
  56303. * Returns the string "BoxEmitter"
  56304. * @returns a string containing the class name
  56305. */
  56306. BoxParticleEmitter.prototype.getClassName = function () {
  56307. return "BoxEmitter";
  56308. };
  56309. /**
  56310. * Serializes the particle system to a JSON object.
  56311. * @returns the JSON object
  56312. */
  56313. BoxParticleEmitter.prototype.serialize = function () {
  56314. var serializationObject = {};
  56315. serializationObject.type = this.getClassName();
  56316. serializationObject.direction1 = this.direction1.asArray();
  56317. serializationObject.direction2 = this.direction2.asArray();
  56318. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56319. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56320. return serializationObject;
  56321. };
  56322. /**
  56323. * Parse properties from a JSON object
  56324. * @param serializationObject defines the JSON object
  56325. */
  56326. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56327. this.direction1.copyFrom(serializationObject.direction1);
  56328. this.direction2.copyFrom(serializationObject.direction2);
  56329. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56330. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56331. };
  56332. return BoxParticleEmitter;
  56333. }());
  56334. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56335. })(BABYLON || (BABYLON = {}));
  56336. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56337. var BABYLON;
  56338. (function (BABYLON) {
  56339. /**
  56340. * Particle emitter emitting particles from the inside of a cone.
  56341. * It emits the particles alongside the cone volume from the base to the particle.
  56342. * The emission direction might be randomized.
  56343. */
  56344. var ConeParticleEmitter = /** @class */ (function () {
  56345. /**
  56346. * Creates a new instance ConeParticleEmitter
  56347. * @param radius the radius of the emission cone (1 by default)
  56348. * @param angles the cone base angle (PI by default)
  56349. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56350. */
  56351. function ConeParticleEmitter(radius, angle,
  56352. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56353. directionRandomizer) {
  56354. if (radius === void 0) { radius = 1; }
  56355. if (angle === void 0) { angle = Math.PI; }
  56356. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56357. this.directionRandomizer = directionRandomizer;
  56358. this.angle = angle;
  56359. this.radius = radius;
  56360. }
  56361. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56362. /**
  56363. * Gets or sets the radius of the emission cone
  56364. */
  56365. get: function () {
  56366. return this._radius;
  56367. },
  56368. set: function (value) {
  56369. this._radius = value;
  56370. this._buildHeight();
  56371. },
  56372. enumerable: true,
  56373. configurable: true
  56374. });
  56375. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56376. /**
  56377. * Gets or sets the angle of the emission cone
  56378. */
  56379. get: function () {
  56380. return this._angle;
  56381. },
  56382. set: function (value) {
  56383. this._angle = value;
  56384. this._buildHeight();
  56385. },
  56386. enumerable: true,
  56387. configurable: true
  56388. });
  56389. ConeParticleEmitter.prototype._buildHeight = function () {
  56390. if (this._angle !== 0) {
  56391. this._height = this._radius / Math.tan(this._angle / 2);
  56392. }
  56393. else {
  56394. this._height = 1;
  56395. }
  56396. };
  56397. /**
  56398. * Called by the particle System when the direction is computed for the created particle.
  56399. * @param worldMatrix is the world matrix of the particle system
  56400. * @param directionToUpdate is the direction vector to update with the result
  56401. * @param particle is the particle we are computed the direction for
  56402. */
  56403. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56404. if (this._angle === 0) {
  56405. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56406. }
  56407. else {
  56408. // measure the direction Vector from the emitter to the particle.
  56409. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56410. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56411. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56412. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56413. direction.x += randX;
  56414. direction.y += randY;
  56415. direction.z += randZ;
  56416. direction.normalize();
  56417. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56418. }
  56419. };
  56420. /**
  56421. * Called by the particle System when the position is computed for the created particle.
  56422. * @param worldMatrix is the world matrix of the particle system
  56423. * @param positionToUpdate is the position vector to update with the result
  56424. * @param particle is the particle we are computed the position for
  56425. */
  56426. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56427. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56428. var h = BABYLON.Scalar.RandomRange(0, 1);
  56429. // Better distribution in a cone at normal angles.
  56430. h = 1 - h * h;
  56431. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56432. radius = radius * h;
  56433. var randX = radius * Math.sin(s);
  56434. var randZ = radius * Math.cos(s);
  56435. var randY = h * this._height;
  56436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56437. };
  56438. /**
  56439. * Clones the current emitter and returns a copy of it
  56440. * @returns the new emitter
  56441. */
  56442. ConeParticleEmitter.prototype.clone = function () {
  56443. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56444. BABYLON.Tools.DeepCopy(this, newOne);
  56445. return newOne;
  56446. };
  56447. /**
  56448. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56449. * @param effect defines the update shader
  56450. */
  56451. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56452. effect.setFloat("radius", this._radius);
  56453. effect.setFloat("coneAngle", this._angle);
  56454. effect.setFloat("height", this._height);
  56455. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56456. };
  56457. /**
  56458. * Returns a string to use to update the GPU particles update shader
  56459. * @returns a string containng the defines string
  56460. */
  56461. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56462. return "#define CONEEMITTER";
  56463. };
  56464. /**
  56465. * Returns the string "BoxEmitter"
  56466. * @returns a string containing the class name
  56467. */
  56468. ConeParticleEmitter.prototype.getClassName = function () {
  56469. return "ConeEmitter";
  56470. };
  56471. /**
  56472. * Serializes the particle system to a JSON object.
  56473. * @returns the JSON object
  56474. */
  56475. ConeParticleEmitter.prototype.serialize = function () {
  56476. var serializationObject = {};
  56477. serializationObject.type = this.getClassName();
  56478. serializationObject.radius = this._radius;
  56479. serializationObject.angle = this._angle;
  56480. serializationObject.directionRandomizer = this.directionRandomizer;
  56481. return serializationObject;
  56482. };
  56483. /**
  56484. * Parse properties from a JSON object
  56485. * @param serializationObject defines the JSON object
  56486. */
  56487. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56488. this.radius = serializationObject.radius;
  56489. this.angle = serializationObject.angle;
  56490. this.directionRandomizer = serializationObject.directionRandomizer;
  56491. };
  56492. return ConeParticleEmitter;
  56493. }());
  56494. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56495. })(BABYLON || (BABYLON = {}));
  56496. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56497. var BABYLON;
  56498. (function (BABYLON) {
  56499. /**
  56500. * Particle emitter emitting particles from the inside of a sphere.
  56501. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56502. */
  56503. var SphereParticleEmitter = /** @class */ (function () {
  56504. /**
  56505. * Creates a new instance SphereParticleEmitter
  56506. * @param radius the radius of the emission sphere (1 by default)
  56507. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56508. */
  56509. function SphereParticleEmitter(
  56510. /**
  56511. * The radius of the emission sphere.
  56512. */
  56513. radius,
  56514. /**
  56515. * How much to randomize the particle direction [0-1].
  56516. */
  56517. directionRandomizer) {
  56518. if (radius === void 0) { radius = 1; }
  56519. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56520. this.radius = radius;
  56521. this.directionRandomizer = directionRandomizer;
  56522. /**
  56523. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56524. */
  56525. this.radiusRange = 1;
  56526. }
  56527. /**
  56528. * Called by the particle System when the direction is computed for the created particle.
  56529. * @param worldMatrix is the world matrix of the particle system
  56530. * @param directionToUpdate is the direction vector to update with the result
  56531. * @param particle is the particle we are computed the direction for
  56532. */
  56533. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56534. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56535. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56536. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56537. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56538. direction.x += randX;
  56539. direction.y += randY;
  56540. direction.z += randZ;
  56541. direction.normalize();
  56542. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56543. };
  56544. /**
  56545. * Called by the particle System when the position is computed for the created particle.
  56546. * @param worldMatrix is the world matrix of the particle system
  56547. * @param positionToUpdate is the position vector to update with the result
  56548. * @param particle is the particle we are computed the position for
  56549. */
  56550. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56551. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56552. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56553. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56554. var theta = Math.acos(2 * v - 1);
  56555. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56556. var randY = randRadius * Math.cos(theta);
  56557. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56559. };
  56560. /**
  56561. * Clones the current emitter and returns a copy of it
  56562. * @returns the new emitter
  56563. */
  56564. SphereParticleEmitter.prototype.clone = function () {
  56565. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56566. BABYLON.Tools.DeepCopy(this, newOne);
  56567. return newOne;
  56568. };
  56569. /**
  56570. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56571. * @param effect defines the update shader
  56572. */
  56573. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56574. effect.setFloat("radius", this.radius);
  56575. effect.setFloat("radiusRange", this.radiusRange);
  56576. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56577. };
  56578. /**
  56579. * Returns a string to use to update the GPU particles update shader
  56580. * @returns a string containng the defines string
  56581. */
  56582. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56583. return "#define SPHEREEMITTER";
  56584. };
  56585. /**
  56586. * Returns the string "SphereParticleEmitter"
  56587. * @returns a string containing the class name
  56588. */
  56589. SphereParticleEmitter.prototype.getClassName = function () {
  56590. return "SphereParticleEmitter";
  56591. };
  56592. /**
  56593. * Serializes the particle system to a JSON object.
  56594. * @returns the JSON object
  56595. */
  56596. SphereParticleEmitter.prototype.serialize = function () {
  56597. var serializationObject = {};
  56598. serializationObject.type = this.getClassName();
  56599. serializationObject.radius = this.radius;
  56600. serializationObject.directionRandomizer = this.directionRandomizer;
  56601. return serializationObject;
  56602. };
  56603. /**
  56604. * Parse properties from a JSON object
  56605. * @param serializationObject defines the JSON object
  56606. */
  56607. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56608. this.radius = serializationObject.radius;
  56609. this.directionRandomizer = serializationObject.directionRandomizer;
  56610. };
  56611. return SphereParticleEmitter;
  56612. }());
  56613. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56614. /**
  56615. * Particle emitter emitting particles from the inside of a sphere.
  56616. * It emits the particles randomly between two vectors.
  56617. */
  56618. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56619. __extends(SphereDirectedParticleEmitter, _super);
  56620. /**
  56621. * Creates a new instance SphereDirectedParticleEmitter
  56622. * @param radius the radius of the emission sphere (1 by default)
  56623. * @param direction1 the min limit of the emission direction (up vector by default)
  56624. * @param direction2 the max limit of the emission direction (up vector by default)
  56625. */
  56626. function SphereDirectedParticleEmitter(radius,
  56627. /**
  56628. * The min limit of the emission direction.
  56629. */
  56630. direction1,
  56631. /**
  56632. * The max limit of the emission direction.
  56633. */
  56634. direction2) {
  56635. if (radius === void 0) { radius = 1; }
  56636. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56637. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56638. var _this = _super.call(this, radius) || this;
  56639. _this.direction1 = direction1;
  56640. _this.direction2 = direction2;
  56641. return _this;
  56642. }
  56643. /**
  56644. * Called by the particle System when the direction is computed for the created particle.
  56645. * @param worldMatrix is the world matrix of the particle system
  56646. * @param directionToUpdate is the direction vector to update with the result
  56647. * @param particle is the particle we are computed the direction for
  56648. */
  56649. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56650. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56651. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56652. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56653. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56654. };
  56655. /**
  56656. * Clones the current emitter and returns a copy of it
  56657. * @returns the new emitter
  56658. */
  56659. SphereDirectedParticleEmitter.prototype.clone = function () {
  56660. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56661. BABYLON.Tools.DeepCopy(this, newOne);
  56662. return newOne;
  56663. };
  56664. /**
  56665. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56666. * @param effect defines the update shader
  56667. */
  56668. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56669. effect.setFloat("radius", this.radius);
  56670. effect.setFloat("radiusRange", this.radiusRange);
  56671. effect.setVector3("direction1", this.direction1);
  56672. effect.setVector3("direction2", this.direction2);
  56673. };
  56674. /**
  56675. * Returns a string to use to update the GPU particles update shader
  56676. * @returns a string containng the defines string
  56677. */
  56678. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56679. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56680. };
  56681. /**
  56682. * Returns the string "SphereDirectedParticleEmitter"
  56683. * @returns a string containing the class name
  56684. */
  56685. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56686. return "SphereDirectedParticleEmitter";
  56687. };
  56688. /**
  56689. * Serializes the particle system to a JSON object.
  56690. * @returns the JSON object
  56691. */
  56692. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56693. var serializationObject = _super.prototype.serialize.call(this);
  56694. serializationObject.direction1 = this.direction1.asArray();
  56695. serializationObject.direction2 = this.direction2.asArray();
  56696. return serializationObject;
  56697. };
  56698. /**
  56699. * Parse properties from a JSON object
  56700. * @param serializationObject defines the JSON object
  56701. */
  56702. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56703. _super.prototype.parse.call(this, serializationObject);
  56704. this.direction1.copyFrom(serializationObject.direction1);
  56705. this.direction2.copyFrom(serializationObject.direction2);
  56706. };
  56707. return SphereDirectedParticleEmitter;
  56708. }(SphereParticleEmitter));
  56709. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56710. })(BABYLON || (BABYLON = {}));
  56711. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56712. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56713. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56714. s = arguments[i];
  56715. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56716. t[p] = s[p];
  56717. }
  56718. return t;
  56719. };
  56720. var BABYLON;
  56721. (function (BABYLON) {
  56722. /**
  56723. * This represents a GPU particle system in Babylon
  56724. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56725. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56726. */
  56727. var GPUParticleSystem = /** @class */ (function () {
  56728. /**
  56729. * Instantiates a GPU particle system.
  56730. * 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.
  56731. * @param name The name of the particle system
  56732. * @param capacity The max number of particles alive at the same time
  56733. * @param scene The scene the particle system belongs to
  56734. */
  56735. function GPUParticleSystem(name, options, scene) {
  56736. /**
  56737. * The emitter represents the Mesh or position we are attaching the particle system to.
  56738. */
  56739. this.emitter = null;
  56740. /**
  56741. * The rendering group used by the Particle system to chose when to render.
  56742. */
  56743. this.renderingGroupId = 0;
  56744. /**
  56745. * The layer mask we are rendering the particles through.
  56746. */
  56747. this.layerMask = 0x0FFFFFFF;
  56748. this._targetIndex = 0;
  56749. this._currentRenderId = -1;
  56750. this._started = false;
  56751. this._stopped = false;
  56752. this._timeDelta = 0;
  56753. this._attributesStrideSize = 18;
  56754. this._actualFrame = 0;
  56755. /**
  56756. * List of animations used by the particle system.
  56757. */
  56758. this.animations = [];
  56759. /**
  56760. * An event triggered when the system is disposed.
  56761. */
  56762. this.onDisposeObservable = new BABYLON.Observable();
  56763. /**
  56764. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56765. */
  56766. this.updateSpeed = 0.01;
  56767. /**
  56768. * The amount of time the particle system is running (depends of the overall update speed).
  56769. */
  56770. this.targetStopDuration = 0;
  56771. /**
  56772. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56773. */
  56774. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56775. /**
  56776. * Minimum life time of emitting particles.
  56777. */
  56778. this.minLifeTime = 1;
  56779. /**
  56780. * Maximum life time of emitting particles.
  56781. */
  56782. this.maxLifeTime = 1;
  56783. /**
  56784. * Minimum Size of emitting particles.
  56785. */
  56786. this.minSize = 1;
  56787. /**
  56788. * Maximum Size of emitting particles.
  56789. */
  56790. this.maxSize = 1;
  56791. /**
  56792. * Minimum scale of emitting particles on X axis.
  56793. */
  56794. this.minScaleX = 1;
  56795. /**
  56796. * Maximum scale of emitting particles on X axis.
  56797. */
  56798. this.maxScaleX = 1;
  56799. /**
  56800. * Minimum scale of emitting particles on Y axis.
  56801. */
  56802. this.minScaleY = 1;
  56803. /**
  56804. * Maximum scale of emitting particles on Y axis.
  56805. */
  56806. this.maxScaleY = 1;
  56807. /**
  56808. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56809. */
  56810. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56811. /**
  56812. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56813. */
  56814. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56815. /**
  56816. * Color the particle will have at the end of its lifetime.
  56817. */
  56818. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56819. /**
  56820. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56821. */
  56822. this.emitRate = 100;
  56823. /**
  56824. * You can use gravity if you want to give an orientation to your particles.
  56825. */
  56826. this.gravity = BABYLON.Vector3.Zero();
  56827. /**
  56828. * Minimum power of emitting particles.
  56829. */
  56830. this.minEmitPower = 1;
  56831. /**
  56832. * Maximum power of emitting particles.
  56833. */
  56834. this.maxEmitPower = 1;
  56835. /**
  56836. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56837. */
  56838. this.minAngularSpeed = 0;
  56839. /**
  56840. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56841. */
  56842. this.maxAngularSpeed = 0;
  56843. /**
  56844. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56845. * to override the particles.
  56846. */
  56847. this.forceDepthWrite = false;
  56848. this._isBillboardBased = true;
  56849. this.id = name;
  56850. this.name = name;
  56851. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56852. this._engine = this._scene.getEngine();
  56853. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56854. this._capacity = fullOptions.capacity;
  56855. this._activeCount = fullOptions.capacity;
  56856. this._currentActiveCount = 0;
  56857. this._scene.particleSystems.push(this);
  56858. this._updateEffectOptions = {
  56859. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle"],
  56860. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56861. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56862. "angleRange", "radiusRange"],
  56863. uniformBuffersNames: [],
  56864. samplers: ["randomSampler"],
  56865. defines: "",
  56866. fallbacks: null,
  56867. onCompiled: null,
  56868. onError: null,
  56869. indexParameters: null,
  56870. maxSimultaneousLights: 0,
  56871. transformFeedbackVaryings: []
  56872. };
  56873. // Random data
  56874. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56875. var d = [];
  56876. for (var i = 0; i < maxTextureSize; ++i) {
  56877. d.push(Math.random());
  56878. d.push(Math.random());
  56879. d.push(Math.random());
  56880. d.push(Math.random());
  56881. }
  56882. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56883. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56884. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56885. this._randomTextureSize = maxTextureSize;
  56886. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56887. }
  56888. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56889. /**
  56890. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56891. */
  56892. get: function () {
  56893. if (!BABYLON.Engine.LastCreatedEngine) {
  56894. return false;
  56895. }
  56896. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56897. },
  56898. enumerable: true,
  56899. configurable: true
  56900. });
  56901. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56902. /**
  56903. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56904. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56905. */
  56906. get: function () {
  56907. if (this.particleEmitterType.direction1) {
  56908. return this.particleEmitterType.direction1;
  56909. }
  56910. return BABYLON.Vector3.Zero();
  56911. },
  56912. set: function (value) {
  56913. if (this.particleEmitterType.direction1) {
  56914. this.particleEmitterType.direction1 = value;
  56915. }
  56916. },
  56917. enumerable: true,
  56918. configurable: true
  56919. });
  56920. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56921. /**
  56922. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56924. */
  56925. get: function () {
  56926. if (this.particleEmitterType.direction2) {
  56927. return this.particleEmitterType.direction2;
  56928. }
  56929. return BABYLON.Vector3.Zero();
  56930. },
  56931. set: function (value) {
  56932. if (this.particleEmitterType.direction2) {
  56933. this.particleEmitterType.direction2 = value;
  56934. }
  56935. },
  56936. enumerable: true,
  56937. configurable: true
  56938. });
  56939. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56940. /**
  56941. * 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.
  56942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56943. */
  56944. get: function () {
  56945. if (this.particleEmitterType.minEmitBox) {
  56946. return this.particleEmitterType.minEmitBox;
  56947. }
  56948. return BABYLON.Vector3.Zero();
  56949. },
  56950. set: function (value) {
  56951. if (this.particleEmitterType.minEmitBox) {
  56952. this.particleEmitterType.minEmitBox = value;
  56953. }
  56954. },
  56955. enumerable: true,
  56956. configurable: true
  56957. });
  56958. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56959. /**
  56960. * 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.
  56961. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56962. */
  56963. get: function () {
  56964. if (this.particleEmitterType.maxEmitBox) {
  56965. return this.particleEmitterType.maxEmitBox;
  56966. }
  56967. return BABYLON.Vector3.Zero();
  56968. },
  56969. set: function (value) {
  56970. if (this.particleEmitterType.maxEmitBox) {
  56971. this.particleEmitterType.maxEmitBox = value;
  56972. }
  56973. },
  56974. enumerable: true,
  56975. configurable: true
  56976. });
  56977. /**
  56978. * Gets the maximum number of particles active at the same time.
  56979. * @returns The max number of active particles.
  56980. */
  56981. GPUParticleSystem.prototype.getCapacity = function () {
  56982. return this._capacity;
  56983. };
  56984. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56985. /**
  56986. * Gets or set the number of active particles
  56987. */
  56988. get: function () {
  56989. return this._activeCount;
  56990. },
  56991. set: function (value) {
  56992. this._activeCount = Math.min(value, this._capacity);
  56993. },
  56994. enumerable: true,
  56995. configurable: true
  56996. });
  56997. /**
  56998. * Is this system ready to be used/rendered
  56999. * @return true if the system is ready
  57000. */
  57001. GPUParticleSystem.prototype.isReady = function () {
  57002. if (!this._updateEffect) {
  57003. this._recreateUpdateEffect();
  57004. this._recreateRenderEffect();
  57005. return false;
  57006. }
  57007. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57008. return false;
  57009. }
  57010. return true;
  57011. };
  57012. /**
  57013. * Gets Wether the system has been started.
  57014. * @returns True if it has been started, otherwise false.
  57015. */
  57016. GPUParticleSystem.prototype.isStarted = function () {
  57017. return this._started;
  57018. };
  57019. /**
  57020. * Starts the particle system and begins to emit.
  57021. */
  57022. GPUParticleSystem.prototype.start = function () {
  57023. this._started = true;
  57024. this._stopped = false;
  57025. };
  57026. /**
  57027. * Stops the particle system.
  57028. */
  57029. GPUParticleSystem.prototype.stop = function () {
  57030. this._stopped = true;
  57031. };
  57032. /**
  57033. * Remove all active particles
  57034. */
  57035. GPUParticleSystem.prototype.reset = function () {
  57036. this._releaseBuffers();
  57037. this._releaseVAOs();
  57038. this._currentActiveCount = 0;
  57039. this._targetIndex = 0;
  57040. };
  57041. /**
  57042. * Returns the string "GPUParticleSystem"
  57043. * @returns a string containing the class name
  57044. */
  57045. GPUParticleSystem.prototype.getClassName = function () {
  57046. return "GPUParticleSystem";
  57047. };
  57048. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57049. /**
  57050. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57051. */
  57052. get: function () {
  57053. return this._isBillboardBased;
  57054. },
  57055. set: function (value) {
  57056. if (this._isBillboardBased === value) {
  57057. return;
  57058. }
  57059. this._isBillboardBased = value;
  57060. this._releaseBuffers();
  57061. },
  57062. enumerable: true,
  57063. configurable: true
  57064. });
  57065. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57066. var updateVertexBuffers = {};
  57067. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57068. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57069. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57070. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57071. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  57072. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  57073. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  57074. var offset = 16;
  57075. if (!this._isBillboardBased) {
  57076. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57077. offset += 3;
  57078. }
  57079. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57080. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57081. this._engine.bindArrayBuffer(null);
  57082. return vao;
  57083. };
  57084. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57085. var renderVertexBuffers = {};
  57086. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57087. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57088. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57089. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  57090. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  57091. var offset = 16;
  57092. if (!this._isBillboardBased) {
  57093. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57094. offset += 3;
  57095. }
  57096. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57097. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57098. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57099. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57100. this._engine.bindArrayBuffer(null);
  57101. return vao;
  57102. };
  57103. GPUParticleSystem.prototype._initialize = function (force) {
  57104. if (force === void 0) { force = false; }
  57105. if (this._buffer0 && !force) {
  57106. return;
  57107. }
  57108. var engine = this._scene.getEngine();
  57109. var data = new Array();
  57110. if (!this.isBillboardBased) {
  57111. this._attributesStrideSize = 21;
  57112. }
  57113. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57114. // position
  57115. data.push(0.0);
  57116. data.push(0.0);
  57117. data.push(0.0);
  57118. // Age and life
  57119. data.push(0.0); // create the particle as a dead one to create a new one at start
  57120. data.push(0.0);
  57121. // Seed
  57122. data.push(Math.random());
  57123. // Size
  57124. data.push(0.0);
  57125. data.push(0.0);
  57126. data.push(0.0);
  57127. // color
  57128. data.push(0.0);
  57129. data.push(0.0);
  57130. data.push(0.0);
  57131. data.push(0.0);
  57132. // direction
  57133. data.push(0.0);
  57134. data.push(0.0);
  57135. data.push(0.0);
  57136. if (!this.isBillboardBased) {
  57137. // initialDirection
  57138. data.push(0.0);
  57139. data.push(0.0);
  57140. data.push(0.0);
  57141. }
  57142. // angle
  57143. data.push(0.0);
  57144. data.push(0.0);
  57145. }
  57146. // Sprite data
  57147. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57148. -0.5, 0.5, 0, 1,
  57149. -0.5, -0.5, 0, 0,
  57150. 0.5, -0.5, 1, 0]);
  57151. // Buffers
  57152. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57153. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57154. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57155. // Update VAO
  57156. this._updateVAO = [];
  57157. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57158. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57159. // Render VAO
  57160. this._renderVAO = [];
  57161. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57162. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57163. // Links
  57164. this._sourceBuffer = this._buffer0;
  57165. this._targetBuffer = this._buffer1;
  57166. };
  57167. /** @hidden */
  57168. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57169. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57170. if (this._isBillboardBased) {
  57171. defines += "\n#define BILLBOARD";
  57172. }
  57173. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57174. return;
  57175. }
  57176. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"];
  57177. if (!this._isBillboardBased) {
  57178. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57179. }
  57180. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57181. this._updateEffectOptions.defines = defines;
  57182. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57183. };
  57184. /** @hidden */
  57185. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57186. var defines = "";
  57187. if (this._scene.clipPlane) {
  57188. defines = "\n#define CLIPPLANE";
  57189. }
  57190. if (this._isBillboardBased) {
  57191. defines += "\n#define BILLBOARD";
  57192. }
  57193. if (this._renderEffect && this._renderEffect.defines === defines) {
  57194. return;
  57195. }
  57196. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57197. };
  57198. /**
  57199. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57200. */
  57201. GPUParticleSystem.prototype.animate = function () {
  57202. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57203. this._actualFrame += this._timeDelta;
  57204. if (!this._stopped) {
  57205. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57206. this.stop();
  57207. }
  57208. }
  57209. };
  57210. /**
  57211. * Renders the particle system in its current state.
  57212. * @returns the current number of particles
  57213. */
  57214. GPUParticleSystem.prototype.render = function () {
  57215. if (!this._started) {
  57216. return 0;
  57217. }
  57218. this._recreateUpdateEffect();
  57219. this._recreateRenderEffect();
  57220. if (!this.isReady()) {
  57221. return 0;
  57222. }
  57223. if (this._currentRenderId === this._scene.getRenderId()) {
  57224. return 0;
  57225. }
  57226. this._currentRenderId = this._scene.getRenderId();
  57227. // Get everything ready to render
  57228. this._initialize();
  57229. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57230. // Enable update effect
  57231. this._engine.enableEffect(this._updateEffect);
  57232. this._engine.setState(false);
  57233. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57234. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57235. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57236. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57237. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57238. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57239. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57240. this._updateEffect.setDirectColor4("color1", this.color1);
  57241. this._updateEffect.setDirectColor4("color2", this.color2);
  57242. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57243. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57244. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57245. this._updateEffect.setVector3("gravity", this.gravity);
  57246. if (this.particleEmitterType) {
  57247. this.particleEmitterType.applyToShader(this._updateEffect);
  57248. }
  57249. var emitterWM;
  57250. if (this.emitter.position) {
  57251. var emitterMesh = this.emitter;
  57252. emitterWM = emitterMesh.getWorldMatrix();
  57253. }
  57254. else {
  57255. var emitterPosition = this.emitter;
  57256. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57257. }
  57258. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57259. // Bind source VAO
  57260. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57261. // Update
  57262. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57263. this._engine.setRasterizerState(false);
  57264. this._engine.beginTransformFeedback();
  57265. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57266. this._engine.endTransformFeedback();
  57267. this._engine.setRasterizerState(true);
  57268. this._engine.bindTransformFeedbackBuffer(null);
  57269. // Enable render effect
  57270. this._engine.enableEffect(this._renderEffect);
  57271. var viewMatrix = this._scene.getViewMatrix();
  57272. this._renderEffect.setMatrix("view", viewMatrix);
  57273. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57274. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57275. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57276. if (this._scene.clipPlane) {
  57277. var clipPlane = this._scene.clipPlane;
  57278. var invView = viewMatrix.clone();
  57279. invView.invert();
  57280. this._renderEffect.setMatrix("invView", invView);
  57281. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57282. }
  57283. // Draw order
  57284. switch (this.blendMode) {
  57285. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57286. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57287. break;
  57288. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57289. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57290. break;
  57291. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57292. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57293. break;
  57294. }
  57295. if (this.forceDepthWrite) {
  57296. this._engine.setDepthWrite(true);
  57297. }
  57298. // Bind source VAO
  57299. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57300. // Render
  57301. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57302. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57303. // Switch VAOs
  57304. this._targetIndex++;
  57305. if (this._targetIndex === 2) {
  57306. this._targetIndex = 0;
  57307. }
  57308. // Switch buffers
  57309. var tmpBuffer = this._sourceBuffer;
  57310. this._sourceBuffer = this._targetBuffer;
  57311. this._targetBuffer = tmpBuffer;
  57312. return this._currentActiveCount;
  57313. };
  57314. /**
  57315. * Rebuilds the particle system
  57316. */
  57317. GPUParticleSystem.prototype.rebuild = function () {
  57318. this._initialize(true);
  57319. };
  57320. GPUParticleSystem.prototype._releaseBuffers = function () {
  57321. if (this._buffer0) {
  57322. this._buffer0.dispose();
  57323. this._buffer0 = null;
  57324. }
  57325. if (this._buffer1) {
  57326. this._buffer1.dispose();
  57327. this._buffer1 = null;
  57328. }
  57329. if (this._spriteBuffer) {
  57330. this._spriteBuffer.dispose();
  57331. this._spriteBuffer = null;
  57332. }
  57333. };
  57334. GPUParticleSystem.prototype._releaseVAOs = function () {
  57335. if (!this._updateVAO) {
  57336. return;
  57337. }
  57338. for (var index = 0; index < this._updateVAO.length; index++) {
  57339. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57340. }
  57341. this._updateVAO = [];
  57342. for (var index = 0; index < this._renderVAO.length; index++) {
  57343. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57344. }
  57345. this._renderVAO = [];
  57346. };
  57347. /**
  57348. * Disposes the particle system and free the associated resources
  57349. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57350. */
  57351. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57352. if (disposeTexture === void 0) { disposeTexture = true; }
  57353. var index = this._scene.particleSystems.indexOf(this);
  57354. if (index > -1) {
  57355. this._scene.particleSystems.splice(index, 1);
  57356. }
  57357. this._releaseBuffers();
  57358. this._releaseVAOs();
  57359. if (this._randomTexture) {
  57360. this._randomTexture.dispose();
  57361. this._randomTexture = null;
  57362. }
  57363. if (disposeTexture && this.particleTexture) {
  57364. this.particleTexture.dispose();
  57365. this.particleTexture = null;
  57366. }
  57367. // Callback
  57368. this.onDisposeObservable.notifyObservers(this);
  57369. this.onDisposeObservable.clear();
  57370. };
  57371. /**
  57372. * Clones the particle system.
  57373. * @param name The name of the cloned object
  57374. * @param newEmitter The new emitter to use
  57375. * @returns the cloned particle system
  57376. */
  57377. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57378. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57379. BABYLON.Tools.DeepCopy(this, result);
  57380. if (newEmitter === undefined) {
  57381. newEmitter = this.emitter;
  57382. }
  57383. result.emitter = newEmitter;
  57384. if (this.particleTexture) {
  57385. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57386. }
  57387. return result;
  57388. };
  57389. /**
  57390. * Serializes the particle system to a JSON object.
  57391. * @returns the JSON object
  57392. */
  57393. GPUParticleSystem.prototype.serialize = function () {
  57394. var serializationObject = {};
  57395. serializationObject.name = this.name;
  57396. serializationObject.id = this.id;
  57397. // Emitter
  57398. if (this.emitter.position) {
  57399. var emitterMesh = this.emitter;
  57400. serializationObject.emitterId = emitterMesh.id;
  57401. }
  57402. else {
  57403. var emitterPosition = this.emitter;
  57404. serializationObject.emitter = emitterPosition.asArray();
  57405. }
  57406. serializationObject.capacity = this.getCapacity();
  57407. if (this.particleTexture) {
  57408. serializationObject.textureName = this.particleTexture.name;
  57409. }
  57410. // Animations
  57411. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57412. // Particle system
  57413. serializationObject.activeParticleCount = this.activeParticleCount;
  57414. serializationObject.randomTextureSize = this._randomTextureSize;
  57415. serializationObject.minSize = this.minSize;
  57416. serializationObject.maxSize = this.maxSize;
  57417. serializationObject.minEmitPower = this.minEmitPower;
  57418. serializationObject.maxEmitPower = this.maxEmitPower;
  57419. serializationObject.minLifeTime = this.minLifeTime;
  57420. serializationObject.maxLifeTime = this.maxLifeTime;
  57421. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57422. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57423. serializationObject.emitRate = this.emitRate;
  57424. serializationObject.gravity = this.gravity.asArray();
  57425. serializationObject.color1 = this.color1.asArray();
  57426. serializationObject.color2 = this.color2.asArray();
  57427. serializationObject.colorDead = this.colorDead.asArray();
  57428. serializationObject.updateSpeed = this.updateSpeed;
  57429. serializationObject.targetStopDuration = this.targetStopDuration;
  57430. serializationObject.blendMode = this.blendMode;
  57431. // Emitter
  57432. if (this.particleEmitterType) {
  57433. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57434. }
  57435. return serializationObject;
  57436. };
  57437. /**
  57438. * Parses a JSON object to create a GPU particle system.
  57439. * @param parsedParticleSystem The JSON object to parse
  57440. * @param scene The scene to create the particle system in
  57441. * @param rootUrl The root url to use to load external dependencies like texture
  57442. * @returns the parsed GPU particle system
  57443. */
  57444. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57445. var name = parsedParticleSystem.name;
  57446. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57447. if (parsedParticleSystem.id) {
  57448. particleSystem.id = parsedParticleSystem.id;
  57449. }
  57450. // Texture
  57451. if (parsedParticleSystem.textureName) {
  57452. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57453. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57454. }
  57455. // Emitter
  57456. if (parsedParticleSystem.emitterId) {
  57457. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57458. }
  57459. else {
  57460. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57461. }
  57462. // Animations
  57463. if (parsedParticleSystem.animations) {
  57464. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57465. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57466. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57467. }
  57468. }
  57469. // Particle system
  57470. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57471. particleSystem.minSize = parsedParticleSystem.minSize;
  57472. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57473. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57474. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57475. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57476. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57477. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57478. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57479. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57480. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57481. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57482. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57483. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57484. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57485. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57486. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57487. // Emitter
  57488. if (parsedParticleSystem.particleEmitterType) {
  57489. var emitterType = void 0;
  57490. switch (parsedParticleSystem.particleEmitterType.type) {
  57491. case "SphereEmitter":
  57492. emitterType = new BABYLON.SphereParticleEmitter();
  57493. break;
  57494. case "SphereDirectedParticleEmitter":
  57495. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57496. break;
  57497. case "ConeEmitter":
  57498. emitterType = new BABYLON.ConeParticleEmitter();
  57499. break;
  57500. case "BoxEmitter":
  57501. default:
  57502. emitterType = new BABYLON.BoxParticleEmitter();
  57503. break;
  57504. }
  57505. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57506. particleSystem.particleEmitterType = emitterType;
  57507. }
  57508. return particleSystem;
  57509. };
  57510. return GPUParticleSystem;
  57511. }());
  57512. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57513. })(BABYLON || (BABYLON = {}));
  57514. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57515. var BABYLON;
  57516. (function (BABYLON) {
  57517. /**
  57518. * Represents one particle of a solid particle system.
  57519. */
  57520. var SolidParticle = /** @class */ (function () {
  57521. /**
  57522. * Creates a Solid Particle object.
  57523. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57524. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57525. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57526. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57527. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57528. * @param shapeId (integer) is the model shape identifier in the SPS.
  57529. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57530. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57531. */
  57532. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57533. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57534. /**
  57535. * particle global index
  57536. */
  57537. this.idx = 0;
  57538. /**
  57539. * The color of the particle
  57540. */
  57541. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57542. /**
  57543. * The world space position of the particle.
  57544. */
  57545. this.position = BABYLON.Vector3.Zero();
  57546. /**
  57547. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57548. */
  57549. this.rotation = BABYLON.Vector3.Zero();
  57550. /**
  57551. * The scaling of the particle.
  57552. */
  57553. this.scaling = BABYLON.Vector3.One();
  57554. /**
  57555. * The uvs of the particle.
  57556. */
  57557. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57558. /**
  57559. * The current speed of the particle.
  57560. */
  57561. this.velocity = BABYLON.Vector3.Zero();
  57562. /**
  57563. * The pivot point in the particle local space.
  57564. */
  57565. this.pivot = BABYLON.Vector3.Zero();
  57566. /**
  57567. * Must the particle be translated from its pivot point in its local space ?
  57568. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57569. * Default : false
  57570. */
  57571. this.translateFromPivot = false;
  57572. /**
  57573. * Is the particle active or not ?
  57574. */
  57575. this.alive = true;
  57576. /**
  57577. * Is the particle visible or not ?
  57578. */
  57579. this.isVisible = true;
  57580. /**
  57581. * Index of this particle in the global "positions" array (Internal use)
  57582. */
  57583. this._pos = 0;
  57584. /**
  57585. * Index of this particle in the global "indices" array (Internal use)
  57586. */
  57587. this._ind = 0;
  57588. /**
  57589. * ModelShape id of this particle
  57590. */
  57591. this.shapeId = 0;
  57592. /**
  57593. * Index of the particle in its shape id (Internal use)
  57594. */
  57595. this.idxInShape = 0;
  57596. /**
  57597. * Still set as invisible in order to skip useless computations (Internal use)
  57598. */
  57599. this._stillInvisible = false;
  57600. /**
  57601. * Last computed particle rotation matrix
  57602. */
  57603. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57604. /**
  57605. * Parent particle Id, if any.
  57606. * Default null.
  57607. */
  57608. this.parentId = null;
  57609. /**
  57610. * Internal global position in the SPS.
  57611. */
  57612. this._globalPosition = BABYLON.Vector3.Zero();
  57613. this.idx = particleIndex;
  57614. this._pos = positionIndex;
  57615. this._ind = indiceIndex;
  57616. this._model = model;
  57617. this.shapeId = shapeId;
  57618. this.idxInShape = idxInShape;
  57619. this._sps = sps;
  57620. if (modelBoundingInfo) {
  57621. this._modelBoundingInfo = modelBoundingInfo;
  57622. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57623. }
  57624. }
  57625. Object.defineProperty(SolidParticle.prototype, "scale", {
  57626. /**
  57627. * Legacy support, changed scale to scaling
  57628. */
  57629. get: function () {
  57630. return this.scaling;
  57631. },
  57632. /**
  57633. * Legacy support, changed scale to scaling
  57634. */
  57635. set: function (scale) {
  57636. this.scaling = scale;
  57637. },
  57638. enumerable: true,
  57639. configurable: true
  57640. });
  57641. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57642. /**
  57643. * Legacy support, changed quaternion to rotationQuaternion
  57644. */
  57645. get: function () {
  57646. return this.rotationQuaternion;
  57647. },
  57648. /**
  57649. * Legacy support, changed quaternion to rotationQuaternion
  57650. */
  57651. set: function (q) {
  57652. this.rotationQuaternion = q;
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. /**
  57658. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57659. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57660. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57661. * @returns true if it intersects
  57662. */
  57663. SolidParticle.prototype.intersectsMesh = function (target) {
  57664. if (!this._boundingInfo || !target._boundingInfo) {
  57665. return false;
  57666. }
  57667. if (this._sps._bSphereOnly) {
  57668. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57669. }
  57670. return this._boundingInfo.intersects(target._boundingInfo, false);
  57671. };
  57672. return SolidParticle;
  57673. }());
  57674. BABYLON.SolidParticle = SolidParticle;
  57675. /**
  57676. * Represents the shape of the model used by one particle of a solid particle system.
  57677. * SPS internal tool, don't use it manually.
  57678. */
  57679. var ModelShape = /** @class */ (function () {
  57680. /**
  57681. * 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.
  57682. * SPS internal tool, don't use it manually.
  57683. * @hidden
  57684. */
  57685. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57686. /**
  57687. * length of the shape in the model indices array (internal use)
  57688. */
  57689. this._indicesLength = 0;
  57690. this.shapeID = id;
  57691. this._shape = shape;
  57692. this._indicesLength = indicesLength;
  57693. this._shapeUV = shapeUV;
  57694. this._positionFunction = posFunction;
  57695. this._vertexFunction = vtxFunction;
  57696. }
  57697. return ModelShape;
  57698. }());
  57699. BABYLON.ModelShape = ModelShape;
  57700. /**
  57701. * Represents a Depth Sorted Particle in the solid particle system.
  57702. */
  57703. var DepthSortedParticle = /** @class */ (function () {
  57704. function DepthSortedParticle() {
  57705. /**
  57706. * Index of the particle in the "indices" array
  57707. */
  57708. this.ind = 0;
  57709. /**
  57710. * Length of the particle shape in the "indices" array
  57711. */
  57712. this.indicesLength = 0;
  57713. /**
  57714. * Squared distance from the particle to the camera
  57715. */
  57716. this.sqDistance = 0.0;
  57717. }
  57718. return DepthSortedParticle;
  57719. }());
  57720. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57721. })(BABYLON || (BABYLON = {}));
  57722. //# sourceMappingURL=babylon.solidParticle.js.map
  57723. var BABYLON;
  57724. (function (BABYLON) {
  57725. /**
  57726. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57727. *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.
  57728. * The SPS is also a particle system. It provides some methods to manage the particles.
  57729. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57730. *
  57731. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57732. */
  57733. var SolidParticleSystem = /** @class */ (function () {
  57734. /**
  57735. * Creates a SPS (Solid Particle System) object.
  57736. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57737. * @param scene (Scene) is the scene in which the SPS is added.
  57738. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57739. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57740. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57741. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57742. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57743. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57744. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57745. */
  57746. function SolidParticleSystem(name, scene, options) {
  57747. /**
  57748. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57749. * Example : var p = SPS.particles[i];
  57750. */
  57751. this.particles = new Array();
  57752. /**
  57753. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57754. */
  57755. this.nbParticles = 0;
  57756. /**
  57757. * If the particles must ever face the camera (default false). Useful for planar particles.
  57758. */
  57759. this.billboard = false;
  57760. /**
  57761. * Recompute normals when adding a shape
  57762. */
  57763. this.recomputeNormals = true;
  57764. /**
  57765. * This a counter ofr your own usage. It's not set by any SPS functions.
  57766. */
  57767. this.counter = 0;
  57768. /**
  57769. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57770. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57771. */
  57772. this.vars = {};
  57773. /**
  57774. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57775. */
  57776. this._bSphereOnly = false;
  57777. /**
  57778. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57779. */
  57780. this._bSphereRadiusFactor = 1.0;
  57781. this._positions = new Array();
  57782. this._indices = new Array();
  57783. this._normals = new Array();
  57784. this._colors = new Array();
  57785. this._uvs = new Array();
  57786. this._index = 0; // indices index
  57787. this._updatable = true;
  57788. this._pickable = false;
  57789. this._isVisibilityBoxLocked = false;
  57790. this._alwaysVisible = false;
  57791. this._depthSort = false;
  57792. this._shapeCounter = 0;
  57793. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57794. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57795. this._computeParticleColor = true;
  57796. this._computeParticleTexture = true;
  57797. this._computeParticleRotation = true;
  57798. this._computeParticleVertex = false;
  57799. this._computeBoundingBox = false;
  57800. this._depthSortParticles = true;
  57801. this._cam_axisZ = BABYLON.Vector3.Zero();
  57802. this._cam_axisY = BABYLON.Vector3.Zero();
  57803. this._cam_axisX = BABYLON.Vector3.Zero();
  57804. this._axisZ = BABYLON.Axis.Z;
  57805. this._camDir = BABYLON.Vector3.Zero();
  57806. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57807. this._rotMatrix = new BABYLON.Matrix();
  57808. this._invertMatrix = new BABYLON.Matrix();
  57809. this._rotated = BABYLON.Vector3.Zero();
  57810. this._quaternion = new BABYLON.Quaternion();
  57811. this._vertex = BABYLON.Vector3.Zero();
  57812. this._normal = BABYLON.Vector3.Zero();
  57813. this._yaw = 0.0;
  57814. this._pitch = 0.0;
  57815. this._roll = 0.0;
  57816. this._halfroll = 0.0;
  57817. this._halfpitch = 0.0;
  57818. this._halfyaw = 0.0;
  57819. this._sinRoll = 0.0;
  57820. this._cosRoll = 0.0;
  57821. this._sinPitch = 0.0;
  57822. this._cosPitch = 0.0;
  57823. this._sinYaw = 0.0;
  57824. this._cosYaw = 0.0;
  57825. this._mustUnrotateFixedNormals = false;
  57826. this._minimum = BABYLON.Vector3.Zero();
  57827. this._maximum = BABYLON.Vector3.Zero();
  57828. this._minBbox = BABYLON.Vector3.Zero();
  57829. this._maxBbox = BABYLON.Vector3.Zero();
  57830. this._particlesIntersect = false;
  57831. this._depthSortFunction = function (p1, p2) {
  57832. return (p2.sqDistance - p1.sqDistance);
  57833. };
  57834. this._needs32Bits = false;
  57835. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57836. this._scaledPivot = BABYLON.Vector3.Zero();
  57837. this._particleHasParent = false;
  57838. this.name = name;
  57839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57840. this._camera = scene.activeCamera;
  57841. this._pickable = options ? options.isPickable : false;
  57842. this._depthSort = options ? options.enableDepthSort : false;
  57843. this._particlesIntersect = options ? options.particleIntersection : false;
  57844. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57845. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57846. if (options && options.updatable !== undefined) {
  57847. this._updatable = options.updatable;
  57848. }
  57849. else {
  57850. this._updatable = true;
  57851. }
  57852. if (this._pickable) {
  57853. this.pickedParticles = [];
  57854. }
  57855. if (this._depthSort) {
  57856. this.depthSortedParticles = [];
  57857. }
  57858. }
  57859. /**
  57860. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57861. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57862. * @returns the created mesh
  57863. */
  57864. SolidParticleSystem.prototype.buildMesh = function () {
  57865. if (this.nbParticles === 0) {
  57866. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57867. this.addShape(triangle, 1);
  57868. triangle.dispose();
  57869. }
  57870. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57871. this._positions32 = new Float32Array(this._positions);
  57872. this._uvs32 = new Float32Array(this._uvs);
  57873. this._colors32 = new Float32Array(this._colors);
  57874. if (this.recomputeNormals) {
  57875. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57876. }
  57877. this._normals32 = new Float32Array(this._normals);
  57878. this._fixedNormal32 = new Float32Array(this._normals);
  57879. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57880. this._unrotateFixedNormals();
  57881. }
  57882. var vertexData = new BABYLON.VertexData();
  57883. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57884. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57885. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57886. if (this._uvs32.length > 0) {
  57887. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57888. }
  57889. if (this._colors32.length > 0) {
  57890. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57891. }
  57892. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57893. vertexData.applyToMesh(mesh, this._updatable);
  57894. this.mesh = mesh;
  57895. this.mesh.isPickable = this._pickable;
  57896. // free memory
  57897. if (!this._depthSort) {
  57898. this._indices = null;
  57899. }
  57900. this._positions = null;
  57901. this._normals = null;
  57902. this._uvs = null;
  57903. this._colors = null;
  57904. if (!this._updatable) {
  57905. this.particles.length = 0;
  57906. }
  57907. return mesh;
  57908. };
  57909. /**
  57910. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57911. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57912. * Thus the particles generated from `digest()` have their property `position` set yet.
  57913. * @param mesh ( Mesh ) is the mesh to be digested
  57914. * @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
  57915. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57916. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57917. * @returns the current SPS
  57918. */
  57919. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57920. var size = (options && options.facetNb) || 1;
  57921. var number = (options && options.number) || 0;
  57922. var delta = (options && options.delta) || 0;
  57923. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57924. var meshInd = mesh.getIndices();
  57925. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57926. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57927. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57928. var f = 0; // facet counter
  57929. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57930. // compute size from number
  57931. if (number) {
  57932. number = (number > totalFacets) ? totalFacets : number;
  57933. size = Math.round(totalFacets / number);
  57934. delta = 0;
  57935. }
  57936. else {
  57937. size = (size > totalFacets) ? totalFacets : size;
  57938. }
  57939. var facetPos = []; // submesh positions
  57940. var facetInd = []; // submesh indices
  57941. var facetUV = []; // submesh UV
  57942. var facetCol = []; // submesh colors
  57943. var barycenter = BABYLON.Vector3.Zero();
  57944. var sizeO = size;
  57945. while (f < totalFacets) {
  57946. size = sizeO + Math.floor((1 + delta) * Math.random());
  57947. if (f > totalFacets - size) {
  57948. size = totalFacets - f;
  57949. }
  57950. // reset temp arrays
  57951. facetPos.length = 0;
  57952. facetInd.length = 0;
  57953. facetUV.length = 0;
  57954. facetCol.length = 0;
  57955. // iterate over "size" facets
  57956. var fi = 0;
  57957. for (var j = f * 3; j < (f + size) * 3; j++) {
  57958. facetInd.push(fi);
  57959. var i = meshInd[j];
  57960. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57961. if (meshUV) {
  57962. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57963. }
  57964. if (meshCol) {
  57965. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57966. }
  57967. fi++;
  57968. }
  57969. // create a model shape for each single particle
  57970. var idx = this.nbParticles;
  57971. var shape = this._posToShape(facetPos);
  57972. var shapeUV = this._uvsToShapeUV(facetUV);
  57973. // compute the barycenter of the shape
  57974. var v;
  57975. for (v = 0; v < shape.length; v++) {
  57976. barycenter.addInPlace(shape[v]);
  57977. }
  57978. barycenter.scaleInPlace(1 / shape.length);
  57979. // shift the shape from its barycenter to the origin
  57980. for (v = 0; v < shape.length; v++) {
  57981. shape[v].subtractInPlace(barycenter);
  57982. }
  57983. var bInfo;
  57984. if (this._particlesIntersect) {
  57985. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57986. }
  57987. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57988. // add the particle in the SPS
  57989. var currentPos = this._positions.length;
  57990. var currentInd = this._indices.length;
  57991. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57992. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57993. // initialize the particle position
  57994. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57995. this._index += shape.length;
  57996. idx++;
  57997. this.nbParticles++;
  57998. this._shapeCounter++;
  57999. f += size;
  58000. }
  58001. return this;
  58002. };
  58003. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58004. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58005. var index = 0;
  58006. var idx = 0;
  58007. for (var p = 0; p < this.particles.length; p++) {
  58008. this._particle = this.particles[p];
  58009. this._shape = this._particle._model._shape;
  58010. if (this._particle.rotationQuaternion) {
  58011. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58012. }
  58013. else {
  58014. this._yaw = this._particle.rotation.y;
  58015. this._pitch = this._particle.rotation.x;
  58016. this._roll = this._particle.rotation.z;
  58017. this._quaternionRotationYPR();
  58018. }
  58019. this._quaternionToRotationMatrix();
  58020. this._rotMatrix.invertToRef(this._invertMatrix);
  58021. for (var pt = 0; pt < this._shape.length; pt++) {
  58022. idx = index + pt * 3;
  58023. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58024. this._fixedNormal32[idx] = this._normal.x;
  58025. this._fixedNormal32[idx + 1] = this._normal.y;
  58026. this._fixedNormal32[idx + 2] = this._normal.z;
  58027. }
  58028. index = idx + 3;
  58029. }
  58030. };
  58031. //reset copy
  58032. SolidParticleSystem.prototype._resetCopy = function () {
  58033. this._copy.position.x = 0;
  58034. this._copy.position.y = 0;
  58035. this._copy.position.z = 0;
  58036. this._copy.rotation.x = 0;
  58037. this._copy.rotation.y = 0;
  58038. this._copy.rotation.z = 0;
  58039. this._copy.rotationQuaternion = null;
  58040. this._copy.scaling.x = 1.0;
  58041. this._copy.scaling.y = 1.0;
  58042. this._copy.scaling.z = 1.0;
  58043. this._copy.uvs.x = 0;
  58044. this._copy.uvs.y = 0;
  58045. this._copy.uvs.z = 1.0;
  58046. this._copy.uvs.w = 1.0;
  58047. this._copy.color = null;
  58048. this._copy.translateFromPivot = false;
  58049. };
  58050. // _meshBuilder : inserts the shape model in the global SPS mesh
  58051. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58052. var i;
  58053. var u = 0;
  58054. var c = 0;
  58055. var n = 0;
  58056. this._resetCopy();
  58057. if (options && options.positionFunction) { // call to custom positionFunction
  58058. options.positionFunction(this._copy, idx, idxInShape);
  58059. this._mustUnrotateFixedNormals = true;
  58060. }
  58061. if (this._copy.rotationQuaternion) {
  58062. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58063. }
  58064. else {
  58065. this._yaw = this._copy.rotation.y;
  58066. this._pitch = this._copy.rotation.x;
  58067. this._roll = this._copy.rotation.z;
  58068. this._quaternionRotationYPR();
  58069. }
  58070. this._quaternionToRotationMatrix();
  58071. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58072. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58073. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58074. if (this._copy.translateFromPivot) {
  58075. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58076. }
  58077. else {
  58078. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58079. }
  58080. for (i = 0; i < shape.length; i++) {
  58081. this._vertex.x = shape[i].x;
  58082. this._vertex.y = shape[i].y;
  58083. this._vertex.z = shape[i].z;
  58084. if (options && options.vertexFunction) {
  58085. options.vertexFunction(this._copy, this._vertex, i);
  58086. }
  58087. this._vertex.x *= this._copy.scaling.x;
  58088. this._vertex.y *= this._copy.scaling.y;
  58089. this._vertex.z *= this._copy.scaling.z;
  58090. this._vertex.x -= this._scaledPivot.x;
  58091. this._vertex.y -= this._scaledPivot.y;
  58092. this._vertex.z -= this._scaledPivot.z;
  58093. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58094. this._rotated.addInPlace(this._pivotBackTranslation);
  58095. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58096. if (meshUV) {
  58097. 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);
  58098. u += 2;
  58099. }
  58100. if (this._copy.color) {
  58101. this._color = this._copy.color;
  58102. }
  58103. else if (meshCol && meshCol[c] !== undefined) {
  58104. this._color.r = meshCol[c];
  58105. this._color.g = meshCol[c + 1];
  58106. this._color.b = meshCol[c + 2];
  58107. this._color.a = meshCol[c + 3];
  58108. }
  58109. else {
  58110. this._color.r = 1.0;
  58111. this._color.g = 1.0;
  58112. this._color.b = 1.0;
  58113. this._color.a = 1.0;
  58114. }
  58115. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58116. c += 4;
  58117. if (!this.recomputeNormals && meshNor) {
  58118. this._normal.x = meshNor[n];
  58119. this._normal.y = meshNor[n + 1];
  58120. this._normal.z = meshNor[n + 2];
  58121. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58122. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58123. n += 3;
  58124. }
  58125. }
  58126. for (i = 0; i < meshInd.length; i++) {
  58127. var current_ind = p + meshInd[i];
  58128. indices.push(current_ind);
  58129. if (current_ind > 65535) {
  58130. this._needs32Bits = true;
  58131. }
  58132. }
  58133. if (this._pickable) {
  58134. var nbfaces = meshInd.length / 3;
  58135. for (i = 0; i < nbfaces; i++) {
  58136. this.pickedParticles.push({ idx: idx, faceId: i });
  58137. }
  58138. }
  58139. if (this._depthSort) {
  58140. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58141. }
  58142. return this._copy;
  58143. };
  58144. // returns a shape array from positions array
  58145. SolidParticleSystem.prototype._posToShape = function (positions) {
  58146. var shape = [];
  58147. for (var i = 0; i < positions.length; i += 3) {
  58148. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58149. }
  58150. return shape;
  58151. };
  58152. // returns a shapeUV array from a Vector4 uvs
  58153. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58154. var shapeUV = [];
  58155. if (uvs) {
  58156. for (var i = 0; i < uvs.length; i++)
  58157. shapeUV.push(uvs[i]);
  58158. }
  58159. return shapeUV;
  58160. };
  58161. // adds a new particle object in the particles array
  58162. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58163. if (bInfo === void 0) { bInfo = null; }
  58164. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58165. this.particles.push(sp);
  58166. return sp;
  58167. };
  58168. /**
  58169. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58170. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58171. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58172. * @param nb (positive integer) the number of particles to be created from this model
  58173. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58174. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58175. * @returns the number of shapes in the system
  58176. */
  58177. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58178. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58179. var meshInd = mesh.getIndices();
  58180. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58181. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58182. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58183. var bbInfo;
  58184. if (this._particlesIntersect) {
  58185. bbInfo = mesh.getBoundingInfo();
  58186. }
  58187. var shape = this._posToShape(meshPos);
  58188. var shapeUV = this._uvsToShapeUV(meshUV);
  58189. var posfunc = options ? options.positionFunction : null;
  58190. var vtxfunc = options ? options.vertexFunction : null;
  58191. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58192. // particles
  58193. var sp;
  58194. var currentCopy;
  58195. var idx = this.nbParticles;
  58196. for (var i = 0; i < nb; i++) {
  58197. var currentPos = this._positions.length;
  58198. var currentInd = this._indices.length;
  58199. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58200. if (this._updatable) {
  58201. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58202. sp.position.copyFrom(currentCopy.position);
  58203. sp.rotation.copyFrom(currentCopy.rotation);
  58204. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58205. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58206. }
  58207. if (currentCopy.color && sp.color) {
  58208. sp.color.copyFrom(currentCopy.color);
  58209. }
  58210. sp.scaling.copyFrom(currentCopy.scaling);
  58211. sp.uvs.copyFrom(currentCopy.uvs);
  58212. }
  58213. this._index += shape.length;
  58214. idx++;
  58215. }
  58216. this.nbParticles += nb;
  58217. this._shapeCounter++;
  58218. return this._shapeCounter - 1;
  58219. };
  58220. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58221. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58222. this._resetCopy();
  58223. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58224. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58225. }
  58226. if (this._copy.rotationQuaternion) {
  58227. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58228. }
  58229. else {
  58230. this._yaw = this._copy.rotation.y;
  58231. this._pitch = this._copy.rotation.x;
  58232. this._roll = this._copy.rotation.z;
  58233. this._quaternionRotationYPR();
  58234. }
  58235. this._quaternionToRotationMatrix();
  58236. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58237. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58238. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58239. if (this._copy.translateFromPivot) {
  58240. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58241. }
  58242. else {
  58243. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58244. }
  58245. this._shape = particle._model._shape;
  58246. for (var pt = 0; pt < this._shape.length; pt++) {
  58247. this._vertex.x = this._shape[pt].x;
  58248. this._vertex.y = this._shape[pt].y;
  58249. this._vertex.z = this._shape[pt].z;
  58250. if (particle._model._vertexFunction) {
  58251. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58252. }
  58253. this._vertex.x *= this._copy.scaling.x;
  58254. this._vertex.y *= this._copy.scaling.y;
  58255. this._vertex.z *= this._copy.scaling.z;
  58256. this._vertex.x -= this._scaledPivot.x;
  58257. this._vertex.y -= this._scaledPivot.y;
  58258. this._vertex.z -= this._scaledPivot.z;
  58259. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58260. this._rotated.addInPlace(this._pivotBackTranslation);
  58261. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58262. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58263. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58264. }
  58265. particle.position.x = 0.0;
  58266. particle.position.y = 0.0;
  58267. particle.position.z = 0.0;
  58268. particle.rotation.x = 0.0;
  58269. particle.rotation.y = 0.0;
  58270. particle.rotation.z = 0.0;
  58271. particle.rotationQuaternion = null;
  58272. particle.scaling.x = 1.0;
  58273. particle.scaling.y = 1.0;
  58274. particle.scaling.z = 1.0;
  58275. particle.uvs.x = 0.0;
  58276. particle.uvs.y = 0.0;
  58277. particle.uvs.z = 1.0;
  58278. particle.uvs.w = 1.0;
  58279. particle.pivot.x = 0.0;
  58280. particle.pivot.y = 0.0;
  58281. particle.pivot.z = 0.0;
  58282. particle.translateFromPivot = false;
  58283. particle.parentId = null;
  58284. };
  58285. /**
  58286. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58287. * @returns the SPS.
  58288. */
  58289. SolidParticleSystem.prototype.rebuildMesh = function () {
  58290. for (var p = 0; p < this.particles.length; p++) {
  58291. this._rebuildParticle(this.particles[p]);
  58292. }
  58293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58294. return this;
  58295. };
  58296. /**
  58297. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58298. * This method calls `updateParticle()` for each particle of the SPS.
  58299. * For an animated SPS, it is usually called within the render loop.
  58300. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58301. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58302. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58303. * @returns the SPS.
  58304. */
  58305. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58306. if (start === void 0) { start = 0; }
  58307. if (end === void 0) { end = this.nbParticles - 1; }
  58308. if (update === void 0) { update = true; }
  58309. if (!this._updatable) {
  58310. return this;
  58311. }
  58312. // custom beforeUpdate
  58313. this.beforeUpdateParticles(start, end, update);
  58314. this._cam_axisX.x = 1.0;
  58315. this._cam_axisX.y = 0.0;
  58316. this._cam_axisX.z = 0.0;
  58317. this._cam_axisY.x = 0.0;
  58318. this._cam_axisY.y = 1.0;
  58319. this._cam_axisY.z = 0.0;
  58320. this._cam_axisZ.x = 0.0;
  58321. this._cam_axisZ.y = 0.0;
  58322. this._cam_axisZ.z = 1.0;
  58323. // cases when the World Matrix is to be computed first
  58324. if (this.billboard || this._depthSort) {
  58325. this.mesh.computeWorldMatrix(true);
  58326. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58327. }
  58328. // if the particles will always face the camera
  58329. if (this.billboard) {
  58330. // compute the camera position and un-rotate it by the current mesh rotation
  58331. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58332. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58333. this._cam_axisZ.normalize();
  58334. // same for camera up vector extracted from the cam view matrix
  58335. var view = this._camera.getViewMatrix(true);
  58336. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58337. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58338. this._cam_axisY.normalize();
  58339. this._cam_axisX.normalize();
  58340. }
  58341. // if depthSort, compute the camera global position in the mesh local system
  58342. if (this._depthSort) {
  58343. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58344. }
  58345. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58346. var idx = 0; // current position index in the global array positions32
  58347. var index = 0; // position start index in the global array positions32 of the current particle
  58348. var colidx = 0; // current color index in the global array colors32
  58349. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58350. var uvidx = 0; // current uv index in the global array uvs32
  58351. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58352. var pt = 0; // current index in the particle model shape
  58353. if (this.mesh.isFacetDataEnabled) {
  58354. this._computeBoundingBox = true;
  58355. }
  58356. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58357. if (this._computeBoundingBox) {
  58358. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58359. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58360. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58361. }
  58362. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58363. if (this.mesh._boundingInfo) {
  58364. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58365. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58366. }
  58367. }
  58368. }
  58369. // particle loop
  58370. index = this.particles[start]._pos;
  58371. var vpos = (index / 3) | 0;
  58372. colorIndex = vpos * 4;
  58373. uvIndex = vpos * 2;
  58374. for (var p = start; p <= end; p++) {
  58375. this._particle = this.particles[p];
  58376. this._shape = this._particle._model._shape;
  58377. this._shapeUV = this._particle._model._shapeUV;
  58378. // call to custom user function to update the particle properties
  58379. this.updateParticle(this._particle);
  58380. // camera-particle distance for depth sorting
  58381. if (this._depthSort && this._depthSortParticles) {
  58382. var dsp = this.depthSortedParticles[p];
  58383. dsp.ind = this._particle._ind;
  58384. dsp.indicesLength = this._particle._model._indicesLength;
  58385. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58386. }
  58387. // skip the computations for inactive or already invisible particles
  58388. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58389. // increment indexes for the next particle
  58390. pt = this._shape.length;
  58391. index += pt * 3;
  58392. colorIndex += pt * 4;
  58393. uvIndex += pt * 2;
  58394. continue;
  58395. }
  58396. if (this._particle.isVisible) {
  58397. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58398. this._particleHasParent = (this._particle.parentId !== null);
  58399. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58400. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58401. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58402. // particle rotation matrix
  58403. if (this.billboard) {
  58404. this._particle.rotation.x = 0.0;
  58405. this._particle.rotation.y = 0.0;
  58406. }
  58407. if (this._computeParticleRotation || this.billboard) {
  58408. if (this._particle.rotationQuaternion) {
  58409. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58410. }
  58411. else {
  58412. this._yaw = this._particle.rotation.y;
  58413. this._pitch = this._particle.rotation.x;
  58414. this._roll = this._particle.rotation.z;
  58415. this._quaternionRotationYPR();
  58416. }
  58417. this._quaternionToRotationMatrix();
  58418. }
  58419. if (this._particleHasParent) {
  58420. this._parent = this.particles[this._particle.parentId];
  58421. 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];
  58422. 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];
  58423. 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];
  58424. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58425. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58426. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58427. if (this._computeParticleRotation || this.billboard) {
  58428. 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];
  58429. 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];
  58430. 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];
  58431. 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];
  58432. 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];
  58433. 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];
  58434. 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];
  58435. 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];
  58436. 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];
  58437. }
  58438. }
  58439. else {
  58440. this._particle._globalPosition.x = this._particle.position.x;
  58441. this._particle._globalPosition.y = this._particle.position.y;
  58442. this._particle._globalPosition.z = this._particle.position.z;
  58443. if (this._computeParticleRotation || this.billboard) {
  58444. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58445. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58446. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58447. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58448. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58449. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58450. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58451. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58452. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58453. }
  58454. }
  58455. if (this._particle.translateFromPivot) {
  58456. this._pivotBackTranslation.x = 0.0;
  58457. this._pivotBackTranslation.y = 0.0;
  58458. this._pivotBackTranslation.z = 0.0;
  58459. }
  58460. else {
  58461. this._pivotBackTranslation.x = this._scaledPivot.x;
  58462. this._pivotBackTranslation.y = this._scaledPivot.y;
  58463. this._pivotBackTranslation.z = this._scaledPivot.z;
  58464. }
  58465. // particle vertex loop
  58466. for (pt = 0; pt < this._shape.length; pt++) {
  58467. idx = index + pt * 3;
  58468. colidx = colorIndex + pt * 4;
  58469. uvidx = uvIndex + pt * 2;
  58470. this._vertex.x = this._shape[pt].x;
  58471. this._vertex.y = this._shape[pt].y;
  58472. this._vertex.z = this._shape[pt].z;
  58473. if (this._computeParticleVertex) {
  58474. this.updateParticleVertex(this._particle, this._vertex, pt);
  58475. }
  58476. // positions
  58477. this._vertex.x *= this._particle.scaling.x;
  58478. this._vertex.y *= this._particle.scaling.y;
  58479. this._vertex.z *= this._particle.scaling.z;
  58480. this._vertex.x -= this._scaledPivot.x;
  58481. this._vertex.y -= this._scaledPivot.y;
  58482. this._vertex.z -= this._scaledPivot.z;
  58483. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58484. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58485. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58486. this._rotated.x += this._pivotBackTranslation.x;
  58487. this._rotated.y += this._pivotBackTranslation.y;
  58488. this._rotated.z += this._pivotBackTranslation.z;
  58489. 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;
  58490. 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;
  58491. 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;
  58492. if (this._computeBoundingBox) {
  58493. if (this._positions32[idx] < this._minimum.x) {
  58494. this._minimum.x = this._positions32[idx];
  58495. }
  58496. if (this._positions32[idx] > this._maximum.x) {
  58497. this._maximum.x = this._positions32[idx];
  58498. }
  58499. if (this._positions32[idx + 1] < this._minimum.y) {
  58500. this._minimum.y = this._positions32[idx + 1];
  58501. }
  58502. if (this._positions32[idx + 1] > this._maximum.y) {
  58503. this._maximum.y = this._positions32[idx + 1];
  58504. }
  58505. if (this._positions32[idx + 2] < this._minimum.z) {
  58506. this._minimum.z = this._positions32[idx + 2];
  58507. }
  58508. if (this._positions32[idx + 2] > this._maximum.z) {
  58509. this._maximum.z = this._positions32[idx + 2];
  58510. }
  58511. }
  58512. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58513. if (!this._computeParticleVertex) {
  58514. this._normal.x = this._fixedNormal32[idx];
  58515. this._normal.y = this._fixedNormal32[idx + 1];
  58516. this._normal.z = this._fixedNormal32[idx + 2];
  58517. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58518. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58519. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58520. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58521. 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;
  58522. 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;
  58523. }
  58524. if (this._computeParticleColor && this._particle.color) {
  58525. this._colors32[colidx] = this._particle.color.r;
  58526. this._colors32[colidx + 1] = this._particle.color.g;
  58527. this._colors32[colidx + 2] = this._particle.color.b;
  58528. this._colors32[colidx + 3] = this._particle.color.a;
  58529. }
  58530. if (this._computeParticleTexture) {
  58531. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58532. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58533. }
  58534. }
  58535. }
  58536. // particle just set invisible : scaled to zero and positioned at the origin
  58537. else {
  58538. this._particle._stillInvisible = true; // mark the particle as invisible
  58539. for (pt = 0; pt < this._shape.length; pt++) {
  58540. idx = index + pt * 3;
  58541. colidx = colorIndex + pt * 4;
  58542. uvidx = uvIndex + pt * 2;
  58543. this._positions32[idx] = 0.0;
  58544. this._positions32[idx + 1] = 0.0;
  58545. this._positions32[idx + 2] = 0.0;
  58546. this._normals32[idx] = 0.0;
  58547. this._normals32[idx + 1] = 0.0;
  58548. this._normals32[idx + 2] = 0.0;
  58549. if (this._computeParticleColor && this._particle.color) {
  58550. this._colors32[colidx] = this._particle.color.r;
  58551. this._colors32[colidx + 1] = this._particle.color.g;
  58552. this._colors32[colidx + 2] = this._particle.color.b;
  58553. this._colors32[colidx + 3] = this._particle.color.a;
  58554. }
  58555. if (this._computeParticleTexture) {
  58556. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58557. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58558. }
  58559. }
  58560. }
  58561. // if the particle intersections must be computed : update the bbInfo
  58562. if (this._particlesIntersect) {
  58563. var bInfo = this._particle._boundingInfo;
  58564. var bBox = bInfo.boundingBox;
  58565. var bSphere = bInfo.boundingSphere;
  58566. if (!this._bSphereOnly) {
  58567. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58568. for (var b = 0; b < bBox.vectors.length; b++) {
  58569. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58570. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58571. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58572. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58573. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58574. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58575. 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;
  58576. 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;
  58577. 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;
  58578. }
  58579. bBox._update(this.mesh._worldMatrix);
  58580. }
  58581. // place and scale the particle bouding sphere in the SPS local system, then update it
  58582. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58583. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58584. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58585. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58586. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58587. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58588. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58589. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58590. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58591. 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));
  58592. bSphere._update(this.mesh._worldMatrix);
  58593. }
  58594. // increment indexes for the next particle
  58595. index = idx + 3;
  58596. colorIndex = colidx + 4;
  58597. uvIndex = uvidx + 2;
  58598. }
  58599. // if the VBO must be updated
  58600. if (update) {
  58601. if (this._computeParticleColor) {
  58602. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58603. }
  58604. if (this._computeParticleTexture) {
  58605. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58606. }
  58607. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58608. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58609. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58610. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58611. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58612. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58613. for (var i = 0; i < this._normals32.length; i++) {
  58614. this._fixedNormal32[i] = this._normals32[i];
  58615. }
  58616. }
  58617. if (!this.mesh.areNormalsFrozen) {
  58618. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58619. }
  58620. }
  58621. if (this._depthSort && this._depthSortParticles) {
  58622. this.depthSortedParticles.sort(this._depthSortFunction);
  58623. var dspl = this.depthSortedParticles.length;
  58624. var sorted = 0;
  58625. var lind = 0;
  58626. var sind = 0;
  58627. var sid = 0;
  58628. for (sorted = 0; sorted < dspl; sorted++) {
  58629. lind = this.depthSortedParticles[sorted].indicesLength;
  58630. sind = this.depthSortedParticles[sorted].ind;
  58631. for (var i = 0; i < lind; i++) {
  58632. this._indices32[sid] = this._indices[sind + i];
  58633. sid++;
  58634. }
  58635. }
  58636. this.mesh.updateIndices(this._indices32);
  58637. }
  58638. }
  58639. if (this._computeBoundingBox) {
  58640. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58641. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58642. }
  58643. this.afterUpdateParticles(start, end, update);
  58644. return this;
  58645. };
  58646. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58647. this._halfroll = this._roll * 0.5;
  58648. this._halfpitch = this._pitch * 0.5;
  58649. this._halfyaw = this._yaw * 0.5;
  58650. this._sinRoll = Math.sin(this._halfroll);
  58651. this._cosRoll = Math.cos(this._halfroll);
  58652. this._sinPitch = Math.sin(this._halfpitch);
  58653. this._cosPitch = Math.cos(this._halfpitch);
  58654. this._sinYaw = Math.sin(this._halfyaw);
  58655. this._cosYaw = Math.cos(this._halfyaw);
  58656. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58657. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58658. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58659. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58660. };
  58661. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58662. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58663. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58664. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58665. this._rotMatrix.m[3] = 0;
  58666. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58667. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58668. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58669. this._rotMatrix.m[7] = 0;
  58670. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58671. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58672. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58673. this._rotMatrix.m[11] = 0;
  58674. this._rotMatrix.m[12] = 0;
  58675. this._rotMatrix.m[13] = 0;
  58676. this._rotMatrix.m[14] = 0;
  58677. this._rotMatrix.m[15] = 1.0;
  58678. };
  58679. /**
  58680. * Disposes the SPS.
  58681. */
  58682. SolidParticleSystem.prototype.dispose = function () {
  58683. this.mesh.dispose();
  58684. this.vars = null;
  58685. // drop references to internal big arrays for the GC
  58686. this._positions = null;
  58687. this._indices = null;
  58688. this._normals = null;
  58689. this._uvs = null;
  58690. this._colors = null;
  58691. this._indices32 = null;
  58692. this._positions32 = null;
  58693. this._normals32 = null;
  58694. this._fixedNormal32 = null;
  58695. this._uvs32 = null;
  58696. this._colors32 = null;
  58697. this.pickedParticles = null;
  58698. };
  58699. /**
  58700. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58702. * @returns the SPS.
  58703. */
  58704. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58705. if (!this._isVisibilityBoxLocked) {
  58706. this.mesh.refreshBoundingInfo();
  58707. }
  58708. return this;
  58709. };
  58710. /**
  58711. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58712. * @param size the size (float) of the visibility box
  58713. * note : this doesn't lock the SPS mesh bounding box.
  58714. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58715. */
  58716. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58717. var vis = size / 2;
  58718. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58719. };
  58720. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58721. /**
  58722. * Gets whether the SPS as always visible or not
  58723. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58724. */
  58725. get: function () {
  58726. return this._alwaysVisible;
  58727. },
  58728. /**
  58729. * Sets the SPS as always visible or not
  58730. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58731. */
  58732. set: function (val) {
  58733. this._alwaysVisible = val;
  58734. this.mesh.alwaysSelectAsActiveMesh = val;
  58735. },
  58736. enumerable: true,
  58737. configurable: true
  58738. });
  58739. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58740. /**
  58741. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58742. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58743. */
  58744. get: function () {
  58745. return this._isVisibilityBoxLocked;
  58746. },
  58747. /**
  58748. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58749. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58750. */
  58751. set: function (val) {
  58752. this._isVisibilityBoxLocked = val;
  58753. var boundingInfo = this.mesh.getBoundingInfo();
  58754. boundingInfo.isLocked = val;
  58755. },
  58756. enumerable: true,
  58757. configurable: true
  58758. });
  58759. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58760. /**
  58761. * Gets if `setParticles()` computes the particle rotations or not.
  58762. * Default value : true. The SPS is faster when it's set to false.
  58763. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58764. */
  58765. get: function () {
  58766. return this._computeParticleRotation;
  58767. },
  58768. /**
  58769. * Tells to `setParticles()` to compute the particle rotations or not.
  58770. * Default value : true. The SPS is faster when it's set to false.
  58771. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58772. */
  58773. set: function (val) {
  58774. this._computeParticleRotation = val;
  58775. },
  58776. enumerable: true,
  58777. configurable: true
  58778. });
  58779. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58780. /**
  58781. * Gets if `setParticles()` computes the particle colors or not.
  58782. * Default value : true. The SPS is faster when it's set to false.
  58783. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58784. */
  58785. get: function () {
  58786. return this._computeParticleColor;
  58787. },
  58788. /**
  58789. * Tells to `setParticles()` to compute the particle colors or not.
  58790. * Default value : true. The SPS is faster when it's set to false.
  58791. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58792. */
  58793. set: function (val) {
  58794. this._computeParticleColor = val;
  58795. },
  58796. enumerable: true,
  58797. configurable: true
  58798. });
  58799. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58800. /**
  58801. * Gets if `setParticles()` computes the particle textures or not.
  58802. * Default value : true. The SPS is faster when it's set to false.
  58803. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58804. */
  58805. get: function () {
  58806. return this._computeParticleTexture;
  58807. },
  58808. set: function (val) {
  58809. this._computeParticleTexture = val;
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58815. /**
  58816. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58817. * Default value : false. The SPS is faster when it's set to false.
  58818. * Note : the particle custom vertex positions aren't stored values.
  58819. */
  58820. get: function () {
  58821. return this._computeParticleVertex;
  58822. },
  58823. /**
  58824. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58825. * Default value : false. The SPS is faster when it's set to false.
  58826. * Note : the particle custom vertex positions aren't stored values.
  58827. */
  58828. set: function (val) {
  58829. this._computeParticleVertex = val;
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58835. /**
  58836. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58837. */
  58838. get: function () {
  58839. return this._computeBoundingBox;
  58840. },
  58841. /**
  58842. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58843. */
  58844. set: function (val) {
  58845. this._computeBoundingBox = val;
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58851. /**
  58852. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58853. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58854. * Default : `true`
  58855. */
  58856. get: function () {
  58857. return this._depthSortParticles;
  58858. },
  58859. /**
  58860. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58861. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58862. * Default : `true`
  58863. */
  58864. set: function (val) {
  58865. this._depthSortParticles = val;
  58866. },
  58867. enumerable: true,
  58868. configurable: true
  58869. });
  58870. // =======================================================================
  58871. // Particle behavior logic
  58872. // these following methods may be overwritten by the user to fit his needs
  58873. /**
  58874. * This function does nothing. It may be overwritten to set all the particle first values.
  58875. * The SPS doesn't call this function, you may have to call it by your own.
  58876. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58877. */
  58878. SolidParticleSystem.prototype.initParticles = function () {
  58879. };
  58880. /**
  58881. * This function does nothing. It may be overwritten to recycle a particle.
  58882. * The SPS doesn't call this function, you may have to call it by your own.
  58883. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58884. * @param particle The particle to recycle
  58885. * @returns the recycled particle
  58886. */
  58887. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58888. return particle;
  58889. };
  58890. /**
  58891. * Updates a particle : this function should be overwritten by the user.
  58892. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58893. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58894. * @example : just set a particle position or velocity and recycle conditions
  58895. * @param particle The particle to update
  58896. * @returns the updated particle
  58897. */
  58898. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58899. return particle;
  58900. };
  58901. /**
  58902. * Updates a vertex of a particle : it can be overwritten by the user.
  58903. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58904. * @param particle the current particle
  58905. * @param vertex the current index of the current particle
  58906. * @param pt the index of the current vertex in the particle shape
  58907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58908. * @example : just set a vertex particle position
  58909. * @returns the updated vertex
  58910. */
  58911. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58912. return vertex;
  58913. };
  58914. /**
  58915. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58916. * This does nothing and may be overwritten by the user.
  58917. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58918. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58919. * @param update the boolean update value actually passed to setParticles()
  58920. */
  58921. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58922. };
  58923. /**
  58924. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58925. * This will be passed three parameters.
  58926. * This does nothing and may be overwritten by the user.
  58927. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58928. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58929. * @param update the boolean update value actually passed to setParticles()
  58930. */
  58931. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58932. };
  58933. return SolidParticleSystem;
  58934. }());
  58935. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58936. })(BABYLON || (BABYLON = {}));
  58937. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58938. var BABYLON;
  58939. (function (BABYLON) {
  58940. var ShaderMaterial = /** @class */ (function (_super) {
  58941. __extends(ShaderMaterial, _super);
  58942. function ShaderMaterial(name, scene, shaderPath, options) {
  58943. var _this = _super.call(this, name, scene) || this;
  58944. _this._textures = {};
  58945. _this._textureArrays = {};
  58946. _this._floats = {};
  58947. _this._ints = {};
  58948. _this._floatsArrays = {};
  58949. _this._colors3 = {};
  58950. _this._colors3Arrays = {};
  58951. _this._colors4 = {};
  58952. _this._vectors2 = {};
  58953. _this._vectors3 = {};
  58954. _this._vectors4 = {};
  58955. _this._matrices = {};
  58956. _this._matrices3x3 = {};
  58957. _this._matrices2x2 = {};
  58958. _this._vectors2Arrays = {};
  58959. _this._vectors3Arrays = {};
  58960. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58961. _this._shaderPath = shaderPath;
  58962. options.needAlphaBlending = options.needAlphaBlending || false;
  58963. options.needAlphaTesting = options.needAlphaTesting || false;
  58964. options.attributes = options.attributes || ["position", "normal", "uv"];
  58965. options.uniforms = options.uniforms || ["worldViewProjection"];
  58966. options.uniformBuffers = options.uniformBuffers || [];
  58967. options.samplers = options.samplers || [];
  58968. options.defines = options.defines || [];
  58969. _this._options = options;
  58970. return _this;
  58971. }
  58972. ShaderMaterial.prototype.getClassName = function () {
  58973. return "ShaderMaterial";
  58974. };
  58975. ShaderMaterial.prototype.needAlphaBlending = function () {
  58976. return this._options.needAlphaBlending;
  58977. };
  58978. ShaderMaterial.prototype.needAlphaTesting = function () {
  58979. return this._options.needAlphaTesting;
  58980. };
  58981. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58982. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58983. this._options.uniforms.push(uniformName);
  58984. }
  58985. };
  58986. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58987. if (this._options.samplers.indexOf(name) === -1) {
  58988. this._options.samplers.push(name);
  58989. }
  58990. this._textures[name] = texture;
  58991. return this;
  58992. };
  58993. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58994. if (this._options.samplers.indexOf(name) === -1) {
  58995. this._options.samplers.push(name);
  58996. }
  58997. this._checkUniform(name);
  58998. this._textureArrays[name] = textures;
  58999. return this;
  59000. };
  59001. ShaderMaterial.prototype.setFloat = function (name, value) {
  59002. this._checkUniform(name);
  59003. this._floats[name] = value;
  59004. return this;
  59005. };
  59006. ShaderMaterial.prototype.setInt = function (name, value) {
  59007. this._checkUniform(name);
  59008. this._ints[name] = value;
  59009. return this;
  59010. };
  59011. ShaderMaterial.prototype.setFloats = function (name, value) {
  59012. this._checkUniform(name);
  59013. this._floatsArrays[name] = value;
  59014. return this;
  59015. };
  59016. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59017. this._checkUniform(name);
  59018. this._colors3[name] = value;
  59019. return this;
  59020. };
  59021. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59022. this._checkUniform(name);
  59023. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59024. color.toArray(arr, arr.length);
  59025. return arr;
  59026. }, []);
  59027. return this;
  59028. };
  59029. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59030. this._checkUniform(name);
  59031. this._colors4[name] = value;
  59032. return this;
  59033. };
  59034. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59035. this._checkUniform(name);
  59036. this._vectors2[name] = value;
  59037. return this;
  59038. };
  59039. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59040. this._checkUniform(name);
  59041. this._vectors3[name] = value;
  59042. return this;
  59043. };
  59044. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59045. this._checkUniform(name);
  59046. this._vectors4[name] = value;
  59047. return this;
  59048. };
  59049. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59050. this._checkUniform(name);
  59051. this._matrices[name] = value;
  59052. return this;
  59053. };
  59054. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59055. this._checkUniform(name);
  59056. this._matrices3x3[name] = value;
  59057. return this;
  59058. };
  59059. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59060. this._checkUniform(name);
  59061. this._matrices2x2[name] = value;
  59062. return this;
  59063. };
  59064. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59065. this._checkUniform(name);
  59066. this._vectors2Arrays[name] = value;
  59067. return this;
  59068. };
  59069. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59070. this._checkUniform(name);
  59071. this._vectors3Arrays[name] = value;
  59072. return this;
  59073. };
  59074. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59075. if (!mesh) {
  59076. return true;
  59077. }
  59078. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59079. return false;
  59080. }
  59081. return false;
  59082. };
  59083. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59084. var scene = this.getScene();
  59085. var engine = scene.getEngine();
  59086. if (!this.checkReadyOnEveryCall) {
  59087. if (this._renderId === scene.getRenderId()) {
  59088. if (this._checkCache(scene, mesh, useInstances)) {
  59089. return true;
  59090. }
  59091. }
  59092. }
  59093. // Instances
  59094. var defines = [];
  59095. var attribs = [];
  59096. var fallbacks = new BABYLON.EffectFallbacks();
  59097. if (useInstances) {
  59098. defines.push("#define INSTANCES");
  59099. }
  59100. for (var index = 0; index < this._options.defines.length; index++) {
  59101. defines.push(this._options.defines[index]);
  59102. }
  59103. for (var index = 0; index < this._options.attributes.length; index++) {
  59104. attribs.push(this._options.attributes[index]);
  59105. }
  59106. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59107. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59108. defines.push("#define VERTEXCOLOR");
  59109. }
  59110. // Bones
  59111. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59114. if (mesh.numBoneInfluencers > 4) {
  59115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59117. }
  59118. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59119. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59120. fallbacks.addCPUSkinningFallback(0, mesh);
  59121. if (this._options.uniforms.indexOf("mBones") === -1) {
  59122. this._options.uniforms.push("mBones");
  59123. }
  59124. }
  59125. else {
  59126. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59127. }
  59128. // Textures
  59129. for (var name in this._textures) {
  59130. if (!this._textures[name].isReady()) {
  59131. return false;
  59132. }
  59133. }
  59134. // Alpha test
  59135. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59136. defines.push("#define ALPHATEST");
  59137. }
  59138. var previousEffect = this._effect;
  59139. var join = defines.join("\n");
  59140. this._effect = engine.createEffect(this._shaderPath, {
  59141. attributes: attribs,
  59142. uniformsNames: this._options.uniforms,
  59143. uniformBuffersNames: this._options.uniformBuffers,
  59144. samplers: this._options.samplers,
  59145. defines: join,
  59146. fallbacks: fallbacks,
  59147. onCompiled: this.onCompiled,
  59148. onError: this.onError
  59149. }, engine);
  59150. if (!this._effect.isReady()) {
  59151. return false;
  59152. }
  59153. if (previousEffect !== this._effect) {
  59154. scene.resetCachedMaterial();
  59155. }
  59156. this._renderId = scene.getRenderId();
  59157. return true;
  59158. };
  59159. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59160. var scene = this.getScene();
  59161. if (!this._effect) {
  59162. return;
  59163. }
  59164. if (this._options.uniforms.indexOf("world") !== -1) {
  59165. this._effect.setMatrix("world", world);
  59166. }
  59167. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59168. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59169. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59170. }
  59171. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59172. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59173. }
  59174. };
  59175. ShaderMaterial.prototype.bind = function (world, mesh) {
  59176. // Std values
  59177. this.bindOnlyWorldMatrix(world);
  59178. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59179. if (this._options.uniforms.indexOf("view") !== -1) {
  59180. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59181. }
  59182. if (this._options.uniforms.indexOf("projection") !== -1) {
  59183. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59184. }
  59185. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59186. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59187. }
  59188. // Bones
  59189. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59190. var name;
  59191. // Texture
  59192. for (name in this._textures) {
  59193. this._effect.setTexture(name, this._textures[name]);
  59194. }
  59195. // Texture arrays
  59196. for (name in this._textureArrays) {
  59197. this._effect.setTextureArray(name, this._textureArrays[name]);
  59198. }
  59199. // Int
  59200. for (name in this._ints) {
  59201. this._effect.setInt(name, this._ints[name]);
  59202. }
  59203. // Float
  59204. for (name in this._floats) {
  59205. this._effect.setFloat(name, this._floats[name]);
  59206. }
  59207. // Floats
  59208. for (name in this._floatsArrays) {
  59209. this._effect.setArray(name, this._floatsArrays[name]);
  59210. }
  59211. // Color3
  59212. for (name in this._colors3) {
  59213. this._effect.setColor3(name, this._colors3[name]);
  59214. }
  59215. for (name in this._colors3Arrays) {
  59216. this._effect.setArray3(name, this._colors3Arrays[name]);
  59217. }
  59218. // Color4
  59219. for (name in this._colors4) {
  59220. var color = this._colors4[name];
  59221. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59222. }
  59223. // Vector2
  59224. for (name in this._vectors2) {
  59225. this._effect.setVector2(name, this._vectors2[name]);
  59226. }
  59227. // Vector3
  59228. for (name in this._vectors3) {
  59229. this._effect.setVector3(name, this._vectors3[name]);
  59230. }
  59231. // Vector4
  59232. for (name in this._vectors4) {
  59233. this._effect.setVector4(name, this._vectors4[name]);
  59234. }
  59235. // Matrix
  59236. for (name in this._matrices) {
  59237. this._effect.setMatrix(name, this._matrices[name]);
  59238. }
  59239. // Matrix 3x3
  59240. for (name in this._matrices3x3) {
  59241. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59242. }
  59243. // Matrix 2x2
  59244. for (name in this._matrices2x2) {
  59245. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59246. }
  59247. // Vector2Array
  59248. for (name in this._vectors2Arrays) {
  59249. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59250. }
  59251. // Vector3Array
  59252. for (name in this._vectors3Arrays) {
  59253. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59254. }
  59255. }
  59256. this._afterBind(mesh);
  59257. };
  59258. ShaderMaterial.prototype.getActiveTextures = function () {
  59259. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59260. for (var name in this._textures) {
  59261. activeTextures.push(this._textures[name]);
  59262. }
  59263. for (var name in this._textureArrays) {
  59264. var array = this._textureArrays[name];
  59265. for (var index = 0; index < array.length; index++) {
  59266. activeTextures.push(array[index]);
  59267. }
  59268. }
  59269. return activeTextures;
  59270. };
  59271. ShaderMaterial.prototype.hasTexture = function (texture) {
  59272. if (_super.prototype.hasTexture.call(this, texture)) {
  59273. return true;
  59274. }
  59275. for (var name in this._textures) {
  59276. if (this._textures[name] === texture) {
  59277. return true;
  59278. }
  59279. }
  59280. for (var name in this._textureArrays) {
  59281. var array = this._textureArrays[name];
  59282. for (var index = 0; index < array.length; index++) {
  59283. if (array[index] === texture) {
  59284. return true;
  59285. }
  59286. }
  59287. }
  59288. return false;
  59289. };
  59290. ShaderMaterial.prototype.clone = function (name) {
  59291. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59292. return newShaderMaterial;
  59293. };
  59294. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59295. if (forceDisposeTextures) {
  59296. var name;
  59297. for (name in this._textures) {
  59298. this._textures[name].dispose();
  59299. }
  59300. for (name in this._textureArrays) {
  59301. var array = this._textureArrays[name];
  59302. for (var index = 0; index < array.length; index++) {
  59303. array[index].dispose();
  59304. }
  59305. }
  59306. }
  59307. this._textures = {};
  59308. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59309. };
  59310. ShaderMaterial.prototype.serialize = function () {
  59311. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59312. serializationObject.customType = "BABYLON.ShaderMaterial";
  59313. serializationObject.options = this._options;
  59314. serializationObject.shaderPath = this._shaderPath;
  59315. var name;
  59316. // Texture
  59317. serializationObject.textures = {};
  59318. for (name in this._textures) {
  59319. serializationObject.textures[name] = this._textures[name].serialize();
  59320. }
  59321. // Texture arrays
  59322. serializationObject.textureArrays = {};
  59323. for (name in this._textureArrays) {
  59324. serializationObject.textureArrays[name] = [];
  59325. var array = this._textureArrays[name];
  59326. for (var index = 0; index < array.length; index++) {
  59327. serializationObject.textureArrays[name].push(array[index].serialize());
  59328. }
  59329. }
  59330. // Float
  59331. serializationObject.floats = {};
  59332. for (name in this._floats) {
  59333. serializationObject.floats[name] = this._floats[name];
  59334. }
  59335. // Float s
  59336. serializationObject.FloatArrays = {};
  59337. for (name in this._floatsArrays) {
  59338. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59339. }
  59340. // Color3
  59341. serializationObject.colors3 = {};
  59342. for (name in this._colors3) {
  59343. serializationObject.colors3[name] = this._colors3[name].asArray();
  59344. }
  59345. // Color3 array
  59346. serializationObject.colors3Arrays = {};
  59347. for (name in this._colors3Arrays) {
  59348. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59349. }
  59350. // Color4
  59351. serializationObject.colors4 = {};
  59352. for (name in this._colors4) {
  59353. serializationObject.colors4[name] = this._colors4[name].asArray();
  59354. }
  59355. // Vector2
  59356. serializationObject.vectors2 = {};
  59357. for (name in this._vectors2) {
  59358. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59359. }
  59360. // Vector3
  59361. serializationObject.vectors3 = {};
  59362. for (name in this._vectors3) {
  59363. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59364. }
  59365. // Vector4
  59366. serializationObject.vectors4 = {};
  59367. for (name in this._vectors4) {
  59368. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59369. }
  59370. // Matrix
  59371. serializationObject.matrices = {};
  59372. for (name in this._matrices) {
  59373. serializationObject.matrices[name] = this._matrices[name].asArray();
  59374. }
  59375. // Matrix 3x3
  59376. serializationObject.matrices3x3 = {};
  59377. for (name in this._matrices3x3) {
  59378. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59379. }
  59380. // Matrix 2x2
  59381. serializationObject.matrices2x2 = {};
  59382. for (name in this._matrices2x2) {
  59383. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59384. }
  59385. // Vector2Array
  59386. serializationObject.vectors2Arrays = {};
  59387. for (name in this._vectors2Arrays) {
  59388. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59389. }
  59390. // Vector3Array
  59391. serializationObject.vectors3Arrays = {};
  59392. for (name in this._vectors3Arrays) {
  59393. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59394. }
  59395. return serializationObject;
  59396. };
  59397. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59398. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59399. var name;
  59400. // Texture
  59401. for (name in source.textures) {
  59402. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59403. }
  59404. // Texture arrays
  59405. for (name in source.textureArrays) {
  59406. var array = source.textureArrays[name];
  59407. var textureArray = new Array();
  59408. for (var index = 0; index < array.length; index++) {
  59409. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59410. }
  59411. material.setTextureArray(name, textureArray);
  59412. }
  59413. // Float
  59414. for (name in source.floats) {
  59415. material.setFloat(name, source.floats[name]);
  59416. }
  59417. // Float s
  59418. for (name in source.floatsArrays) {
  59419. material.setFloats(name, source.floatsArrays[name]);
  59420. }
  59421. // Color3
  59422. for (name in source.colors3) {
  59423. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59424. }
  59425. // Color3 arrays
  59426. for (name in source.colors3Arrays) {
  59427. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59428. if (i % 3 === 0) {
  59429. arr.push([num]);
  59430. }
  59431. else {
  59432. arr[arr.length - 1].push(num);
  59433. }
  59434. return arr;
  59435. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59436. material.setColor3Array(name, colors);
  59437. }
  59438. // Color4
  59439. for (name in source.colors4) {
  59440. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59441. }
  59442. // Vector2
  59443. for (name in source.vectors2) {
  59444. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59445. }
  59446. // Vector3
  59447. for (name in source.vectors3) {
  59448. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59449. }
  59450. // Vector4
  59451. for (name in source.vectors4) {
  59452. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59453. }
  59454. // Matrix
  59455. for (name in source.matrices) {
  59456. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59457. }
  59458. // Matrix 3x3
  59459. for (name in source.matrices3x3) {
  59460. material.setMatrix3x3(name, source.matrices3x3[name]);
  59461. }
  59462. // Matrix 2x2
  59463. for (name in source.matrices2x2) {
  59464. material.setMatrix2x2(name, source.matrices2x2[name]);
  59465. }
  59466. // Vector2Array
  59467. for (name in source.vectors2Arrays) {
  59468. material.setArray2(name, source.vectors2Arrays[name]);
  59469. }
  59470. // Vector3Array
  59471. for (name in source.vectors3Arrays) {
  59472. material.setArray3(name, source.vectors3Arrays[name]);
  59473. }
  59474. return material;
  59475. };
  59476. return ShaderMaterial;
  59477. }(BABYLON.Material));
  59478. BABYLON.ShaderMaterial = ShaderMaterial;
  59479. })(BABYLON || (BABYLON = {}));
  59480. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59481. var BABYLON;
  59482. (function (BABYLON) {
  59483. var GroundMesh = /** @class */ (function (_super) {
  59484. __extends(GroundMesh, _super);
  59485. function GroundMesh(name, scene) {
  59486. var _this = _super.call(this, name, scene) || this;
  59487. _this.generateOctree = false;
  59488. return _this;
  59489. }
  59490. GroundMesh.prototype.getClassName = function () {
  59491. return "GroundMesh";
  59492. };
  59493. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59494. get: function () {
  59495. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59496. },
  59497. enumerable: true,
  59498. configurable: true
  59499. });
  59500. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59501. get: function () {
  59502. return this._subdivisionsX;
  59503. },
  59504. enumerable: true,
  59505. configurable: true
  59506. });
  59507. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59508. get: function () {
  59509. return this._subdivisionsY;
  59510. },
  59511. enumerable: true,
  59512. configurable: true
  59513. });
  59514. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59515. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59516. this._subdivisionsX = chunksCount;
  59517. this._subdivisionsY = chunksCount;
  59518. this.subdivide(chunksCount);
  59519. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59520. };
  59521. /**
  59522. * Returns a height (y) value in the Worl system :
  59523. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59524. * Returns the ground y position if (x, z) are outside the ground surface.
  59525. */
  59526. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59527. var world = this.getWorldMatrix();
  59528. var invMat = BABYLON.Tmp.Matrix[5];
  59529. world.invertToRef(invMat);
  59530. var tmpVect = BABYLON.Tmp.Vector3[8];
  59531. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59532. x = tmpVect.x;
  59533. z = tmpVect.z;
  59534. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59535. return this.position.y;
  59536. }
  59537. if (!this._heightQuads || this._heightQuads.length == 0) {
  59538. this._initHeightQuads();
  59539. this._computeHeightQuads();
  59540. }
  59541. var facet = this._getFacetAt(x, z);
  59542. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59543. // return y in the World system
  59544. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59545. return tmpVect.y;
  59546. };
  59547. /**
  59548. * Returns a normalized vector (Vector3) orthogonal to the ground
  59549. * at the ground coordinates (x, z) expressed in the World system.
  59550. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59551. */
  59552. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59553. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59554. this.getNormalAtCoordinatesToRef(x, z, normal);
  59555. return normal;
  59556. };
  59557. /**
  59558. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59559. * at the ground coordinates (x, z) expressed in the World system.
  59560. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59561. * Returns the GroundMesh.
  59562. */
  59563. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59564. var world = this.getWorldMatrix();
  59565. var tmpMat = BABYLON.Tmp.Matrix[5];
  59566. world.invertToRef(tmpMat);
  59567. var tmpVect = BABYLON.Tmp.Vector3[8];
  59568. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59569. x = tmpVect.x;
  59570. z = tmpVect.z;
  59571. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59572. return this;
  59573. }
  59574. if (!this._heightQuads || this._heightQuads.length == 0) {
  59575. this._initHeightQuads();
  59576. this._computeHeightQuads();
  59577. }
  59578. var facet = this._getFacetAt(x, z);
  59579. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59580. return this;
  59581. };
  59582. /**
  59583. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59584. * if the ground has been updated.
  59585. * This can be used in the render loop.
  59586. * Returns the GroundMesh.
  59587. */
  59588. GroundMesh.prototype.updateCoordinateHeights = function () {
  59589. if (!this._heightQuads || this._heightQuads.length == 0) {
  59590. this._initHeightQuads();
  59591. }
  59592. this._computeHeightQuads();
  59593. return this;
  59594. };
  59595. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59596. GroundMesh.prototype._getFacetAt = function (x, z) {
  59597. // retrieve col and row from x, z coordinates in the ground local system
  59598. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59599. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59600. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59601. var facet;
  59602. if (z < quad.slope.x * x + quad.slope.y) {
  59603. facet = quad.facet1;
  59604. }
  59605. else {
  59606. facet = quad.facet2;
  59607. }
  59608. return facet;
  59609. };
  59610. // Creates and populates the heightMap array with "facet" elements :
  59611. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59612. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59613. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59614. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59615. // Returns the GroundMesh.
  59616. GroundMesh.prototype._initHeightQuads = function () {
  59617. var subdivisionsX = this._subdivisionsX;
  59618. var subdivisionsY = this._subdivisionsY;
  59619. this._heightQuads = new Array();
  59620. for (var row = 0; row < subdivisionsY; row++) {
  59621. for (var col = 0; col < subdivisionsX; col++) {
  59622. 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) };
  59623. this._heightQuads[row * subdivisionsX + col] = quad;
  59624. }
  59625. }
  59626. return this;
  59627. };
  59628. // Compute each quad element values and update the the heightMap array :
  59629. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59630. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59631. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59632. // Returns the GroundMesh.
  59633. GroundMesh.prototype._computeHeightQuads = function () {
  59634. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59635. if (!positions) {
  59636. return this;
  59637. }
  59638. var v1 = BABYLON.Tmp.Vector3[3];
  59639. var v2 = BABYLON.Tmp.Vector3[2];
  59640. var v3 = BABYLON.Tmp.Vector3[1];
  59641. var v4 = BABYLON.Tmp.Vector3[0];
  59642. var v1v2 = BABYLON.Tmp.Vector3[4];
  59643. var v1v3 = BABYLON.Tmp.Vector3[5];
  59644. var v1v4 = BABYLON.Tmp.Vector3[6];
  59645. var norm1 = BABYLON.Tmp.Vector3[7];
  59646. var norm2 = BABYLON.Tmp.Vector3[8];
  59647. var i = 0;
  59648. var j = 0;
  59649. var k = 0;
  59650. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59651. var h = 0;
  59652. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59653. var d2 = 0;
  59654. var subdivisionsX = this._subdivisionsX;
  59655. var subdivisionsY = this._subdivisionsY;
  59656. for (var row = 0; row < subdivisionsY; row++) {
  59657. for (var col = 0; col < subdivisionsX; col++) {
  59658. i = col * 3;
  59659. j = row * (subdivisionsX + 1) * 3;
  59660. k = (row + 1) * (subdivisionsX + 1) * 3;
  59661. v1.x = positions[j + i];
  59662. v1.y = positions[j + i + 1];
  59663. v1.z = positions[j + i + 2];
  59664. v2.x = positions[j + i + 3];
  59665. v2.y = positions[j + i + 4];
  59666. v2.z = positions[j + i + 5];
  59667. v3.x = positions[k + i];
  59668. v3.y = positions[k + i + 1];
  59669. v3.z = positions[k + i + 2];
  59670. v4.x = positions[k + i + 3];
  59671. v4.y = positions[k + i + 4];
  59672. v4.z = positions[k + i + 5];
  59673. // 2D slope V1V4
  59674. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59675. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59676. // facet equations :
  59677. // we compute each facet normal vector
  59678. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59679. // we compute the value d by applying the equation to v1 which belongs to the plane
  59680. // then we store the facet equation in a Vector4
  59681. v2.subtractToRef(v1, v1v2);
  59682. v3.subtractToRef(v1, v1v3);
  59683. v4.subtractToRef(v1, v1v4);
  59684. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59685. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59686. norm1.normalize();
  59687. norm2.normalize();
  59688. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59689. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59690. var quad = this._heightQuads[row * subdivisionsX + col];
  59691. quad.slope.copyFromFloats(cd, h);
  59692. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59693. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59694. }
  59695. }
  59696. return this;
  59697. };
  59698. GroundMesh.prototype.serialize = function (serializationObject) {
  59699. _super.prototype.serialize.call(this, serializationObject);
  59700. serializationObject.subdivisionsX = this._subdivisionsX;
  59701. serializationObject.subdivisionsY = this._subdivisionsY;
  59702. serializationObject.minX = this._minX;
  59703. serializationObject.maxX = this._maxX;
  59704. serializationObject.minZ = this._minZ;
  59705. serializationObject.maxZ = this._maxZ;
  59706. serializationObject.width = this._width;
  59707. serializationObject.height = this._height;
  59708. };
  59709. GroundMesh.Parse = function (parsedMesh, scene) {
  59710. var result = new GroundMesh(parsedMesh.name, scene);
  59711. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59712. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59713. result._minX = parsedMesh.minX;
  59714. result._maxX = parsedMesh.maxX;
  59715. result._minZ = parsedMesh.minZ;
  59716. result._maxZ = parsedMesh.maxZ;
  59717. result._width = parsedMesh.width;
  59718. result._height = parsedMesh.height;
  59719. return result;
  59720. };
  59721. return GroundMesh;
  59722. }(BABYLON.Mesh));
  59723. BABYLON.GroundMesh = GroundMesh;
  59724. })(BABYLON || (BABYLON = {}));
  59725. //# sourceMappingURL=babylon.groundMesh.js.map
  59726. var BABYLON;
  59727. (function (BABYLON) {
  59728. /**
  59729. * Creates an instance based on a source mesh.
  59730. */
  59731. var InstancedMesh = /** @class */ (function (_super) {
  59732. __extends(InstancedMesh, _super);
  59733. function InstancedMesh(name, source) {
  59734. var _this = _super.call(this, name, source.getScene()) || this;
  59735. source.instances.push(_this);
  59736. _this._sourceMesh = source;
  59737. _this.position.copyFrom(source.position);
  59738. _this.rotation.copyFrom(source.rotation);
  59739. _this.scaling.copyFrom(source.scaling);
  59740. if (source.rotationQuaternion) {
  59741. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59742. }
  59743. _this.infiniteDistance = source.infiniteDistance;
  59744. _this.setPivotMatrix(source.getPivotMatrix());
  59745. _this.refreshBoundingInfo();
  59746. _this._syncSubMeshes();
  59747. return _this;
  59748. }
  59749. /**
  59750. * Returns the string "InstancedMesh".
  59751. */
  59752. InstancedMesh.prototype.getClassName = function () {
  59753. return "InstancedMesh";
  59754. };
  59755. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59756. // Methods
  59757. get: function () {
  59758. return this._sourceMesh.receiveShadows;
  59759. },
  59760. enumerable: true,
  59761. configurable: true
  59762. });
  59763. Object.defineProperty(InstancedMesh.prototype, "material", {
  59764. get: function () {
  59765. return this._sourceMesh.material;
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59771. get: function () {
  59772. return this._sourceMesh.visibility;
  59773. },
  59774. enumerable: true,
  59775. configurable: true
  59776. });
  59777. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59778. get: function () {
  59779. return this._sourceMesh.skeleton;
  59780. },
  59781. enumerable: true,
  59782. configurable: true
  59783. });
  59784. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59785. get: function () {
  59786. return this._sourceMesh.renderingGroupId;
  59787. },
  59788. set: function (value) {
  59789. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59790. return;
  59791. }
  59792. //no-op with warning
  59793. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. /**
  59799. * Returns the total number of vertices (integer).
  59800. */
  59801. InstancedMesh.prototype.getTotalVertices = function () {
  59802. return this._sourceMesh.getTotalVertices();
  59803. };
  59804. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59805. get: function () {
  59806. return this._sourceMesh;
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. /**
  59812. * Is this node ready to be used/rendered
  59813. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59814. * @return {boolean} is it ready
  59815. */
  59816. InstancedMesh.prototype.isReady = function (completeCheck) {
  59817. if (completeCheck === void 0) { completeCheck = false; }
  59818. return this._sourceMesh.isReady(completeCheck, true);
  59819. };
  59820. /**
  59821. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59822. */
  59823. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59824. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59825. };
  59826. /**
  59827. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59828. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59829. * The `data` are either a numeric array either a Float32Array.
  59830. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59831. * 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).
  59832. * Note that a new underlying VertexBuffer object is created each call.
  59833. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59834. *
  59835. * Possible `kind` values :
  59836. * - BABYLON.VertexBuffer.PositionKind
  59837. * - BABYLON.VertexBuffer.UVKind
  59838. * - BABYLON.VertexBuffer.UV2Kind
  59839. * - BABYLON.VertexBuffer.UV3Kind
  59840. * - BABYLON.VertexBuffer.UV4Kind
  59841. * - BABYLON.VertexBuffer.UV5Kind
  59842. * - BABYLON.VertexBuffer.UV6Kind
  59843. * - BABYLON.VertexBuffer.ColorKind
  59844. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59845. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59846. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59847. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59848. *
  59849. * Returns the Mesh.
  59850. */
  59851. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59852. if (this.sourceMesh) {
  59853. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59854. }
  59855. return this.sourceMesh;
  59856. };
  59857. /**
  59858. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59859. * If the mesh has no geometry, it is simply returned as it is.
  59860. * The `data` are either a numeric array either a Float32Array.
  59861. * No new underlying VertexBuffer object is created.
  59862. * 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.
  59863. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59864. *
  59865. * Possible `kind` values :
  59866. * - BABYLON.VertexBuffer.PositionKind
  59867. * - BABYLON.VertexBuffer.UVKind
  59868. * - BABYLON.VertexBuffer.UV2Kind
  59869. * - BABYLON.VertexBuffer.UV3Kind
  59870. * - BABYLON.VertexBuffer.UV4Kind
  59871. * - BABYLON.VertexBuffer.UV5Kind
  59872. * - BABYLON.VertexBuffer.UV6Kind
  59873. * - BABYLON.VertexBuffer.ColorKind
  59874. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59875. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59876. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59877. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59878. *
  59879. * Returns the Mesh.
  59880. */
  59881. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59882. if (this.sourceMesh) {
  59883. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59884. }
  59885. return this.sourceMesh;
  59886. };
  59887. /**
  59888. * Sets the mesh indices.
  59889. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59890. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59891. * This method creates a new index buffer each call.
  59892. * Returns the Mesh.
  59893. */
  59894. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59895. if (totalVertices === void 0) { totalVertices = null; }
  59896. if (this.sourceMesh) {
  59897. this.sourceMesh.setIndices(indices, totalVertices);
  59898. }
  59899. return this.sourceMesh;
  59900. };
  59901. /**
  59902. * Boolean : True if the mesh owns the requested kind of data.
  59903. */
  59904. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59905. return this._sourceMesh.isVerticesDataPresent(kind);
  59906. };
  59907. /**
  59908. * Returns an array of indices (IndicesArray).
  59909. */
  59910. InstancedMesh.prototype.getIndices = function () {
  59911. return this._sourceMesh.getIndices();
  59912. };
  59913. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59914. get: function () {
  59915. return this._sourceMesh._positions;
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. /**
  59921. * Sets a new updated BoundingInfo to the mesh.
  59922. * Returns the mesh.
  59923. */
  59924. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59925. var meshBB = this._sourceMesh.getBoundingInfo();
  59926. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59927. this._updateBoundingInfo();
  59928. return this;
  59929. };
  59930. InstancedMesh.prototype._preActivate = function () {
  59931. if (this._currentLOD) {
  59932. this._currentLOD._preActivate();
  59933. }
  59934. return this;
  59935. };
  59936. InstancedMesh.prototype._activate = function (renderId) {
  59937. if (this._currentLOD) {
  59938. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59939. }
  59940. return this;
  59941. };
  59942. /**
  59943. * Returns the current associated LOD AbstractMesh.
  59944. */
  59945. InstancedMesh.prototype.getLOD = function (camera) {
  59946. if (!camera) {
  59947. return this;
  59948. }
  59949. var boundingInfo = this.getBoundingInfo();
  59950. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59951. if (this._currentLOD === this.sourceMesh) {
  59952. return this;
  59953. }
  59954. return this._currentLOD;
  59955. };
  59956. InstancedMesh.prototype._syncSubMeshes = function () {
  59957. this.releaseSubMeshes();
  59958. if (this._sourceMesh.subMeshes) {
  59959. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59960. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59961. }
  59962. }
  59963. return this;
  59964. };
  59965. InstancedMesh.prototype._generatePointsArray = function () {
  59966. return this._sourceMesh._generatePointsArray();
  59967. };
  59968. /**
  59969. * Creates a new InstancedMesh from the current mesh.
  59970. * - name (string) : the cloned mesh name
  59971. * - newParent (optional Node) : the optional Node to parent the clone to.
  59972. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59973. *
  59974. * Returns the clone.
  59975. */
  59976. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59977. var result = this._sourceMesh.createInstance(name);
  59978. // Deep copy
  59979. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59980. // Bounding info
  59981. this.refreshBoundingInfo();
  59982. // Parent
  59983. if (newParent) {
  59984. result.parent = newParent;
  59985. }
  59986. if (!doNotCloneChildren) {
  59987. // Children
  59988. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59989. var mesh = this.getScene().meshes[index];
  59990. if (mesh.parent === this) {
  59991. mesh.clone(mesh.name, result);
  59992. }
  59993. }
  59994. }
  59995. result.computeWorldMatrix(true);
  59996. return result;
  59997. };
  59998. /**
  59999. * Disposes the InstancedMesh.
  60000. * Returns nothing.
  60001. */
  60002. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60003. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60004. // Remove from mesh
  60005. var index = this._sourceMesh.instances.indexOf(this);
  60006. this._sourceMesh.instances.splice(index, 1);
  60007. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60008. };
  60009. return InstancedMesh;
  60010. }(BABYLON.AbstractMesh));
  60011. BABYLON.InstancedMesh = InstancedMesh;
  60012. })(BABYLON || (BABYLON = {}));
  60013. //# sourceMappingURL=babylon.instancedMesh.js.map
  60014. var BABYLON;
  60015. (function (BABYLON) {
  60016. var LinesMesh = /** @class */ (function (_super) {
  60017. __extends(LinesMesh, _super);
  60018. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60019. if (scene === void 0) { scene = null; }
  60020. if (parent === void 0) { parent = null; }
  60021. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60022. _this.useVertexColor = useVertexColor;
  60023. _this.useVertexAlpha = useVertexAlpha;
  60024. _this.color = new BABYLON.Color3(1, 1, 1);
  60025. _this.alpha = 1;
  60026. if (source) {
  60027. _this.color = source.color.clone();
  60028. _this.alpha = source.alpha;
  60029. _this.useVertexColor = source.useVertexColor;
  60030. _this.useVertexAlpha = source.useVertexAlpha;
  60031. }
  60032. _this._intersectionThreshold = 0.1;
  60033. var defines = [];
  60034. var options = {
  60035. attributes: [BABYLON.VertexBuffer.PositionKind],
  60036. uniforms: ["world", "viewProjection"],
  60037. needAlphaBlending: true,
  60038. defines: defines
  60039. };
  60040. if (useVertexAlpha === false) {
  60041. options.needAlphaBlending = false;
  60042. }
  60043. if (!useVertexColor) {
  60044. options.uniforms.push("color");
  60045. }
  60046. else {
  60047. options.defines.push("#define VERTEXCOLOR");
  60048. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60049. }
  60050. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60051. return _this;
  60052. }
  60053. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60054. /**
  60055. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60056. * This margin is expressed in world space coordinates, so its value may vary.
  60057. * Default value is 0.1
  60058. * @returns the intersection Threshold value.
  60059. */
  60060. get: function () {
  60061. return this._intersectionThreshold;
  60062. },
  60063. /**
  60064. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60065. * This margin is expressed in world space coordinates, so its value may vary.
  60066. * @param value the new threshold to apply
  60067. */
  60068. set: function (value) {
  60069. if (this._intersectionThreshold === value) {
  60070. return;
  60071. }
  60072. this._intersectionThreshold = value;
  60073. if (this.geometry) {
  60074. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60075. }
  60076. },
  60077. enumerable: true,
  60078. configurable: true
  60079. });
  60080. /**
  60081. * Returns the string "LineMesh"
  60082. */
  60083. LinesMesh.prototype.getClassName = function () {
  60084. return "LinesMesh";
  60085. };
  60086. Object.defineProperty(LinesMesh.prototype, "material", {
  60087. get: function () {
  60088. return this._colorShader;
  60089. },
  60090. set: function (value) {
  60091. // Do nothing
  60092. },
  60093. enumerable: true,
  60094. configurable: true
  60095. });
  60096. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60097. get: function () {
  60098. return false;
  60099. },
  60100. enumerable: true,
  60101. configurable: true
  60102. });
  60103. LinesMesh.prototype.createInstance = function (name) {
  60104. throw new Error("LinesMeshes do not support createInstance.");
  60105. };
  60106. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60107. if (!this._geometry) {
  60108. return this;
  60109. }
  60110. // VBOs
  60111. this._geometry._bind(this._colorShader.getEffect());
  60112. // Color
  60113. if (!this.useVertexColor) {
  60114. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60115. }
  60116. return this;
  60117. };
  60118. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60119. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60120. return this;
  60121. }
  60122. var engine = this.getScene().getEngine();
  60123. // Draw order
  60124. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60125. return this;
  60126. };
  60127. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60128. this._colorShader.dispose();
  60129. _super.prototype.dispose.call(this, doNotRecurse);
  60130. };
  60131. /**
  60132. * Returns a new LineMesh object cloned from the current one.
  60133. */
  60134. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60135. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60136. };
  60137. return LinesMesh;
  60138. }(BABYLON.Mesh));
  60139. BABYLON.LinesMesh = LinesMesh;
  60140. })(BABYLON || (BABYLON = {}));
  60141. //# sourceMappingURL=babylon.linesMesh.js.map
  60142. var BABYLON;
  60143. (function (BABYLON) {
  60144. /**
  60145. * Class containing static functions to help procedurally build meshes
  60146. */
  60147. var MeshBuilder = /** @class */ (function () {
  60148. function MeshBuilder() {
  60149. }
  60150. MeshBuilder.updateSideOrientation = function (orientation) {
  60151. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60152. return BABYLON.Mesh.DOUBLESIDE;
  60153. }
  60154. if (orientation === undefined || orientation === null) {
  60155. return BABYLON.Mesh.FRONTSIDE;
  60156. }
  60157. return orientation;
  60158. };
  60159. /**
  60160. * Creates a box mesh
  60161. * * The parameter `size` sets the size (float) of each box side (default 1)
  60162. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60163. * * 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)
  60164. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60165. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60166. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60167. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60168. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60169. * @param name defines the name of the mesh
  60170. * @param options defines the options used to create the mesh
  60171. * @param scene defines the hosting scene
  60172. * @returns the box mesh
  60173. */
  60174. MeshBuilder.CreateBox = function (name, options, scene) {
  60175. if (scene === void 0) { scene = null; }
  60176. var box = new BABYLON.Mesh(name, scene);
  60177. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60178. box._originalBuilderSideOrientation = options.sideOrientation;
  60179. var vertexData = BABYLON.VertexData.CreateBox(options);
  60180. vertexData.applyToMesh(box, options.updatable);
  60181. return box;
  60182. };
  60183. /**
  60184. * Creates a sphere mesh
  60185. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60186. * * 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`)
  60187. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60188. * * 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
  60189. * * 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)
  60190. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60191. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60193. * @param name defines the name of the mesh
  60194. * @param options defines the options used to create the mesh
  60195. * @param scene defines the hosting scene
  60196. * @returns the sphere mesh
  60197. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60198. */
  60199. MeshBuilder.CreateSphere = function (name, options, scene) {
  60200. var sphere = new BABYLON.Mesh(name, scene);
  60201. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60202. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60203. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60204. vertexData.applyToMesh(sphere, options.updatable);
  60205. return sphere;
  60206. };
  60207. /**
  60208. * Creates a plane polygonal mesh. By default, this is a disc
  60209. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60210. * * 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
  60211. * * 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
  60212. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60213. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60214. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60215. * @param name defines the name of the mesh
  60216. * @param options defines the options used to create the mesh
  60217. * @param scene defines the hosting scene
  60218. * @returns the plane polygonal mesh
  60219. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60220. */
  60221. MeshBuilder.CreateDisc = function (name, options, scene) {
  60222. if (scene === void 0) { scene = null; }
  60223. var disc = new BABYLON.Mesh(name, scene);
  60224. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60225. disc._originalBuilderSideOrientation = options.sideOrientation;
  60226. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60227. vertexData.applyToMesh(disc, options.updatable);
  60228. return disc;
  60229. };
  60230. /**
  60231. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60232. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60233. * * 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`)
  60234. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60235. * * 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
  60236. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60237. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60238. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60239. * @param name defines the name of the mesh
  60240. * @param options defines the options used to create the mesh
  60241. * @param scene defines the hosting scene
  60242. * @returns the icosahedron mesh
  60243. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60244. */
  60245. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60246. var sphere = new BABYLON.Mesh(name, scene);
  60247. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60248. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60249. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60250. vertexData.applyToMesh(sphere, options.updatable);
  60251. return sphere;
  60252. };
  60253. ;
  60254. /**
  60255. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60256. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60257. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60258. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60259. * * 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
  60260. * * 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
  60261. * * 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
  60262. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60263. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60264. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60265. * * 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
  60266. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60267. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60268. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60270. * @param name defines the name of the mesh
  60271. * @param options defines the options used to create the mesh
  60272. * @param scene defines the hosting scene
  60273. * @returns the ribbon mesh
  60274. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60275. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60276. */
  60277. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60278. if (scene === void 0) { scene = null; }
  60279. var pathArray = options.pathArray;
  60280. var closeArray = options.closeArray;
  60281. var closePath = options.closePath;
  60282. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60283. var instance = options.instance;
  60284. var updatable = options.updatable;
  60285. if (instance) { // existing ribbon instance update
  60286. // positionFunction : ribbon case
  60287. // only pathArray and sideOrientation parameters are taken into account for positions update
  60288. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60289. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60290. var positionFunction = function (positions) {
  60291. var minlg = pathArray[0].length;
  60292. var i = 0;
  60293. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60294. for (var si = 1; si <= ns; si++) {
  60295. for (var p = 0; p < pathArray.length; p++) {
  60296. var path = pathArray[p];
  60297. var l = path.length;
  60298. minlg = (minlg < l) ? minlg : l;
  60299. var j = 0;
  60300. while (j < minlg) {
  60301. positions[i] = path[j].x;
  60302. positions[i + 1] = path[j].y;
  60303. positions[i + 2] = path[j].z;
  60304. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60305. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60306. }
  60307. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60308. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60309. }
  60310. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60311. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60312. }
  60313. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60314. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60315. }
  60316. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60317. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60318. }
  60319. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60320. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60321. }
  60322. j++;
  60323. i += 3;
  60324. }
  60325. if (instance._closePath) {
  60326. positions[i] = path[0].x;
  60327. positions[i + 1] = path[0].y;
  60328. positions[i + 2] = path[0].z;
  60329. i += 3;
  60330. }
  60331. }
  60332. }
  60333. };
  60334. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60335. positionFunction(positions);
  60336. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60337. instance._boundingInfo.update(instance._worldMatrix);
  60338. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60339. if (options.colors) {
  60340. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60341. for (var c = 0; c < options.colors.length; c++) {
  60342. colors[c * 4] = options.colors[c].r;
  60343. colors[c * 4 + 1] = options.colors[c].g;
  60344. colors[c * 4 + 2] = options.colors[c].b;
  60345. colors[c * 4 + 3] = options.colors[c].a;
  60346. }
  60347. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60348. }
  60349. if (options.uvs) {
  60350. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60351. for (var i = 0; i < options.uvs.length; i++) {
  60352. uvs[i * 2] = options.uvs[i].x;
  60353. uvs[i * 2 + 1] = options.uvs[i].y;
  60354. }
  60355. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60356. }
  60357. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60358. var indices = instance.getIndices();
  60359. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60360. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60361. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60362. if (instance._closePath) {
  60363. var indexFirst = 0;
  60364. var indexLast = 0;
  60365. for (var p = 0; p < pathArray.length; p++) {
  60366. indexFirst = instance._idx[p] * 3;
  60367. if (p + 1 < pathArray.length) {
  60368. indexLast = (instance._idx[p + 1] - 1) * 3;
  60369. }
  60370. else {
  60371. indexLast = normals.length - 3;
  60372. }
  60373. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60374. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60375. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60376. normals[indexLast] = normals[indexFirst];
  60377. normals[indexLast + 1] = normals[indexFirst + 1];
  60378. normals[indexLast + 2] = normals[indexFirst + 2];
  60379. }
  60380. }
  60381. if (!(instance.areNormalsFrozen)) {
  60382. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60383. }
  60384. }
  60385. return instance;
  60386. }
  60387. else { // new ribbon creation
  60388. var ribbon = new BABYLON.Mesh(name, scene);
  60389. ribbon._originalBuilderSideOrientation = sideOrientation;
  60390. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60391. if (closePath) {
  60392. ribbon._idx = vertexData._idx;
  60393. }
  60394. ribbon._closePath = closePath;
  60395. ribbon._closeArray = closeArray;
  60396. vertexData.applyToMesh(ribbon, updatable);
  60397. return ribbon;
  60398. }
  60399. };
  60400. /**
  60401. * Creates a cylinder or a cone mesh
  60402. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60403. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60404. * * 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.
  60405. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60406. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60407. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60408. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60409. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60410. * * 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).
  60411. * * 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
  60412. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60413. * * 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
  60414. * * 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.
  60415. * * If `enclose` is false, a ring surface is one element.
  60416. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60417. * * 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
  60418. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60419. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60420. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60421. * @param name defines the name of the mesh
  60422. * @param options defines the options used to create the mesh
  60423. * @param scene defines the hosting scene
  60424. * @returns the cylinder mesh
  60425. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60426. */
  60427. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60428. var cylinder = new BABYLON.Mesh(name, scene);
  60429. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60430. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60431. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60432. vertexData.applyToMesh(cylinder, options.updatable);
  60433. return cylinder;
  60434. };
  60435. /**
  60436. * Creates a torus mesh
  60437. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60438. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60439. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60440. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60441. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60442. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60443. * @param name defines the name of the mesh
  60444. * @param options defines the options used to create the mesh
  60445. * @param scene defines the hosting scene
  60446. * @returns the torus mesh
  60447. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60448. */
  60449. MeshBuilder.CreateTorus = function (name, options, scene) {
  60450. var torus = new BABYLON.Mesh(name, scene);
  60451. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60452. torus._originalBuilderSideOrientation = options.sideOrientation;
  60453. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60454. vertexData.applyToMesh(torus, options.updatable);
  60455. return torus;
  60456. };
  60457. /**
  60458. * Creates a torus knot mesh
  60459. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60460. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60461. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60462. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60463. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60464. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60465. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60466. * @param name defines the name of the mesh
  60467. * @param options defines the options used to create the mesh
  60468. * @param scene defines the hosting scene
  60469. * @returns the torus knot mesh
  60470. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60471. */
  60472. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60473. var torusKnot = new BABYLON.Mesh(name, scene);
  60474. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60475. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60476. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60477. vertexData.applyToMesh(torusKnot, options.updatable);
  60478. return torusKnot;
  60479. };
  60480. /**
  60481. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60482. * * 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
  60483. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60484. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60485. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60486. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60487. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60488. * * 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
  60489. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60490. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60491. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60492. * @param name defines the name of the new line system
  60493. * @param options defines the options used to create the line system
  60494. * @param scene defines the hosting scene
  60495. * @returns a new line system mesh
  60496. */
  60497. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60498. var instance = options.instance;
  60499. var lines = options.lines;
  60500. var colors = options.colors;
  60501. if (instance) { // lines update
  60502. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60503. var vertexColor;
  60504. var lineColors;
  60505. if (colors) {
  60506. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60507. }
  60508. var i = 0;
  60509. var c = 0;
  60510. for (var l = 0; l < lines.length; l++) {
  60511. var points = lines[l];
  60512. for (var p = 0; p < points.length; p++) {
  60513. positions[i] = points[p].x;
  60514. positions[i + 1] = points[p].y;
  60515. positions[i + 2] = points[p].z;
  60516. if (colors && vertexColor) {
  60517. lineColors = colors[l];
  60518. vertexColor[c] = lineColors[p].r;
  60519. vertexColor[c + 1] = lineColors[p].g;
  60520. vertexColor[c + 2] = lineColors[p].b;
  60521. vertexColor[c + 3] = lineColors[p].a;
  60522. c += 4;
  60523. }
  60524. i += 3;
  60525. }
  60526. }
  60527. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60528. if (colors && vertexColor) {
  60529. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60530. }
  60531. return instance;
  60532. }
  60533. // line system creation
  60534. var useVertexColor = (colors) ? true : false;
  60535. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60536. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60537. vertexData.applyToMesh(lineSystem, options.updatable);
  60538. return lineSystem;
  60539. };
  60540. /**
  60541. * Creates a line mesh
  60542. * 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
  60543. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60544. * * The parameter `points` is an array successive Vector3
  60545. * * 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
  60546. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60547. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60548. * * When updating an instance, remember that only point positions can change, not the number of points
  60549. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60550. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60551. * @param name defines the name of the new line system
  60552. * @param options defines the options used to create the line system
  60553. * @param scene defines the hosting scene
  60554. * @returns a new line mesh
  60555. */
  60556. MeshBuilder.CreateLines = function (name, options, scene) {
  60557. if (scene === void 0) { scene = null; }
  60558. var colors = (options.colors) ? [options.colors] : null;
  60559. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60560. return lines;
  60561. };
  60562. /**
  60563. * Creates a dashed line mesh
  60564. * * 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
  60565. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60566. * * The parameter `points` is an array successive Vector3
  60567. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60568. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60569. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60570. * * 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
  60571. * * When updating an instance, remember that only point positions can change, not the number of points
  60572. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60573. * @param name defines the name of the mesh
  60574. * @param options defines the options used to create the mesh
  60575. * @param scene defines the hosting scene
  60576. * @returns the dashed line mesh
  60577. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60578. */
  60579. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60580. if (scene === void 0) { scene = null; }
  60581. var points = options.points;
  60582. var instance = options.instance;
  60583. var gapSize = options.gapSize || 1;
  60584. var dashSize = options.dashSize || 3;
  60585. if (instance) { // dashed lines update
  60586. var positionFunction = function (positions) {
  60587. var curvect = BABYLON.Vector3.Zero();
  60588. var nbSeg = positions.length / 6;
  60589. var lg = 0;
  60590. var nb = 0;
  60591. var shft = 0;
  60592. var dashshft = 0;
  60593. var curshft = 0;
  60594. var p = 0;
  60595. var i = 0;
  60596. var j = 0;
  60597. for (i = 0; i < points.length - 1; i++) {
  60598. points[i + 1].subtractToRef(points[i], curvect);
  60599. lg += curvect.length();
  60600. }
  60601. shft = lg / nbSeg;
  60602. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60603. for (i = 0; i < points.length - 1; i++) {
  60604. points[i + 1].subtractToRef(points[i], curvect);
  60605. nb = Math.floor(curvect.length() / shft);
  60606. curvect.normalize();
  60607. j = 0;
  60608. while (j < nb && p < positions.length) {
  60609. curshft = shft * j;
  60610. positions[p] = points[i].x + curshft * curvect.x;
  60611. positions[p + 1] = points[i].y + curshft * curvect.y;
  60612. positions[p + 2] = points[i].z + curshft * curvect.z;
  60613. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60614. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60615. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60616. p += 6;
  60617. j++;
  60618. }
  60619. }
  60620. while (p < positions.length) {
  60621. positions[p] = points[i].x;
  60622. positions[p + 1] = points[i].y;
  60623. positions[p + 2] = points[i].z;
  60624. p += 3;
  60625. }
  60626. };
  60627. instance.updateMeshPositions(positionFunction, false);
  60628. return instance;
  60629. }
  60630. // dashed lines creation
  60631. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60632. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60633. vertexData.applyToMesh(dashedLines, options.updatable);
  60634. dashedLines.dashSize = dashSize;
  60635. dashedLines.gapSize = gapSize;
  60636. return dashedLines;
  60637. };
  60638. /**
  60639. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60640. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60641. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60642. * * 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.
  60643. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60644. * * 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
  60645. * * 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
  60646. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60647. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60648. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60649. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60650. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60651. * @param name defines the name of the mesh
  60652. * @param options defines the options used to create the mesh
  60653. * @param scene defines the hosting scene
  60654. * @returns the extruded shape mesh
  60655. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60656. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60657. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60658. */
  60659. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60660. if (scene === void 0) { scene = null; }
  60661. var path = options.path;
  60662. var shape = options.shape;
  60663. var scale = options.scale || 1;
  60664. var rotation = options.rotation || 0;
  60665. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60666. var updatable = options.updatable;
  60667. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60668. var instance = options.instance || null;
  60669. var invertUV = options.invertUV || false;
  60670. 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);
  60671. };
  60672. /**
  60673. * Creates an custom extruded shape mesh.
  60674. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60675. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60676. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60677. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60678. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60679. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60680. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60681. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60682. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60683. * * 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
  60684. * * 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
  60685. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60686. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60687. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60688. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60689. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60690. * @param name defines the name of the mesh
  60691. * @param options defines the options used to create the mesh
  60692. * @param scene defines the hosting scene
  60693. * @returns the custom extruded shape mesh
  60694. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60695. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60696. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60697. */
  60698. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60699. var path = options.path;
  60700. var shape = options.shape;
  60701. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60702. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60703. var ribbonCloseArray = options.ribbonCloseArray || false;
  60704. var ribbonClosePath = options.ribbonClosePath || false;
  60705. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60706. var updatable = options.updatable;
  60707. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60708. var instance = options.instance;
  60709. var invertUV = options.invertUV || false;
  60710. 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);
  60711. };
  60712. /**
  60713. * Creates lathe mesh.
  60714. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60715. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60716. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60717. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60718. * * 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
  60719. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60720. * * 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
  60721. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60722. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60723. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60724. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60725. * @param name defines the name of the mesh
  60726. * @param options defines the options used to create the mesh
  60727. * @param scene defines the hosting scene
  60728. * @returns the lathe mesh
  60729. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60730. */
  60731. MeshBuilder.CreateLathe = function (name, options, scene) {
  60732. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60733. var closed = (options.closed === undefined) ? true : options.closed;
  60734. var shape = options.shape;
  60735. var radius = options.radius || 1;
  60736. var tessellation = options.tessellation || 64;
  60737. var updatable = options.updatable;
  60738. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60739. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60740. var pi2 = Math.PI * 2;
  60741. var paths = new Array();
  60742. var invertUV = options.invertUV || false;
  60743. var i = 0;
  60744. var p = 0;
  60745. var step = pi2 / tessellation * arc;
  60746. var rotated;
  60747. var path = new Array();
  60748. for (i = 0; i <= tessellation; i++) {
  60749. var path = [];
  60750. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60751. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60752. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60753. }
  60754. for (p = 0; p < shape.length; p++) {
  60755. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60756. path.push(rotated);
  60757. }
  60758. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60759. 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));
  60760. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60761. }
  60762. paths.push(path);
  60763. }
  60764. // lathe ribbon
  60765. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60766. return lathe;
  60767. };
  60768. /**
  60769. * Creates a plane mesh
  60770. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60771. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60772. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60773. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60774. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60775. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60776. * @param name defines the name of the mesh
  60777. * @param options defines the options used to create the mesh
  60778. * @param scene defines the hosting scene
  60779. * @returns the plane mesh
  60780. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60781. */
  60782. MeshBuilder.CreatePlane = function (name, options, scene) {
  60783. var plane = new BABYLON.Mesh(name, scene);
  60784. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60785. plane._originalBuilderSideOrientation = options.sideOrientation;
  60786. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60787. vertexData.applyToMesh(plane, options.updatable);
  60788. if (options.sourcePlane) {
  60789. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60790. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60791. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60792. plane.rotate(vectorProduct, product);
  60793. }
  60794. return plane;
  60795. };
  60796. /**
  60797. * Creates a ground mesh
  60798. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60799. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60801. * @param name defines the name of the mesh
  60802. * @param options defines the options used to create the mesh
  60803. * @param scene defines the hosting scene
  60804. * @returns the ground mesh
  60805. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60806. */
  60807. MeshBuilder.CreateGround = function (name, options, scene) {
  60808. var ground = new BABYLON.GroundMesh(name, scene);
  60809. ground._setReady(false);
  60810. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60811. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60812. ground._width = options.width || 1;
  60813. ground._height = options.height || 1;
  60814. ground._maxX = ground._width / 2;
  60815. ground._maxZ = ground._height / 2;
  60816. ground._minX = -ground._maxX;
  60817. ground._minZ = -ground._maxZ;
  60818. var vertexData = BABYLON.VertexData.CreateGround(options);
  60819. vertexData.applyToMesh(ground, options.updatable);
  60820. ground._setReady(true);
  60821. return ground;
  60822. };
  60823. /**
  60824. * Creates a tiled ground mesh
  60825. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60826. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60827. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  60828. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  60829. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60830. * @param name defines the name of the mesh
  60831. * @param options defines the options used to create the mesh
  60832. * @param scene defines the hosting scene
  60833. * @returns the tiled ground mesh
  60834. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60835. */
  60836. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60837. var tiledGround = new BABYLON.Mesh(name, scene);
  60838. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60839. vertexData.applyToMesh(tiledGround, options.updatable);
  60840. return tiledGround;
  60841. };
  60842. /**
  60843. * Creates a ground mesh from a height map
  60844. * * The parameter `url` sets the URL of the height map image resource.
  60845. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60846. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60847. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60848. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60849. * * 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.
  60850. * * 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).
  60851. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60852. * @param name defines the name of the mesh
  60853. * @param url defines the url to the height map
  60854. * @param options defines the options used to create the mesh
  60855. * @param scene defines the hosting scene
  60856. * @returns the ground mesh
  60857. * @see http://doc.babylonjs.com/babylon101/height_map
  60858. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60859. */
  60860. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60861. var width = options.width || 10.0;
  60862. var height = options.height || 10.0;
  60863. var subdivisions = options.subdivisions || 1 | 0;
  60864. var minHeight = options.minHeight || 0.0;
  60865. var maxHeight = options.maxHeight || 1.0;
  60866. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60867. var updatable = options.updatable;
  60868. var onReady = options.onReady;
  60869. var ground = new BABYLON.GroundMesh(name, scene);
  60870. ground._subdivisionsX = subdivisions;
  60871. ground._subdivisionsY = subdivisions;
  60872. ground._width = width;
  60873. ground._height = height;
  60874. ground._maxX = ground._width / 2.0;
  60875. ground._maxZ = ground._height / 2.0;
  60876. ground._minX = -ground._maxX;
  60877. ground._minZ = -ground._maxZ;
  60878. ground._setReady(false);
  60879. var onload = function (img) {
  60880. // Getting height map data
  60881. var canvas = document.createElement("canvas");
  60882. var context = canvas.getContext("2d");
  60883. if (!context) {
  60884. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60885. }
  60886. if (scene.isDisposed) {
  60887. return;
  60888. }
  60889. var bufferWidth = img.width;
  60890. var bufferHeight = img.height;
  60891. canvas.width = bufferWidth;
  60892. canvas.height = bufferHeight;
  60893. context.drawImage(img, 0, 0);
  60894. // Create VertexData from map data
  60895. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60896. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60897. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60898. width: width, height: height,
  60899. subdivisions: subdivisions,
  60900. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60901. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60902. });
  60903. vertexData.applyToMesh(ground, updatable);
  60904. //execute ready callback, if set
  60905. if (onReady) {
  60906. onReady(ground);
  60907. }
  60908. ground._setReady(true);
  60909. };
  60910. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60911. return ground;
  60912. };
  60913. /**
  60914. * Creates a polygon mesh
  60915. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60916. * * 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
  60917. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60918. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60919. * * 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)
  60920. * * Remember you can only change the shape positions, not their number when updating a polygon
  60921. * @param name defines the name of the mesh
  60922. * @param options defines the options used to create the mesh
  60923. * @param scene defines the hosting scene
  60924. * @returns the polygon mesh
  60925. */
  60926. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60928. var shape = options.shape;
  60929. var holes = options.holes || [];
  60930. var depth = options.depth || 0;
  60931. var contours = [];
  60932. var hole = [];
  60933. for (var i = 0; i < shape.length; i++) {
  60934. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60935. }
  60936. var epsilon = 0.00000001;
  60937. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60938. contours.pop();
  60939. }
  60940. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60941. for (var hNb = 0; hNb < holes.length; hNb++) {
  60942. hole = [];
  60943. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60944. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60945. }
  60946. polygonTriangulation.addHole(hole);
  60947. }
  60948. var polygon = polygonTriangulation.build(options.updatable, depth);
  60949. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60950. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60951. vertexData.applyToMesh(polygon, options.updatable);
  60952. return polygon;
  60953. };
  60954. ;
  60955. /**
  60956. * Creates an extruded polygon mesh, with depth in the Y direction.
  60957. * * 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)
  60958. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60959. * @param name defines the name of the mesh
  60960. * @param options defines the options used to create the mesh
  60961. * @param scene defines the hosting scene
  60962. * @returns the polygon mesh
  60963. */
  60964. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60965. return MeshBuilder.CreatePolygon(name, options, scene);
  60966. };
  60967. ;
  60968. /**
  60969. * Creates a tube mesh.
  60970. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60971. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60972. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60973. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60974. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60975. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  60976. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60977. * * 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
  60978. * * 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
  60979. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60980. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60981. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60982. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60983. * @param name defines the name of the mesh
  60984. * @param options defines the options used to create the mesh
  60985. * @param scene defines the hosting scene
  60986. * @returns the tube mesh
  60987. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60988. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60989. */
  60990. MeshBuilder.CreateTube = function (name, options, scene) {
  60991. var path = options.path;
  60992. var instance = options.instance;
  60993. var radius = 1.0;
  60994. if (instance) {
  60995. radius = instance.radius;
  60996. }
  60997. if (options.radius !== undefined) {
  60998. radius = options.radius;
  60999. }
  61000. ;
  61001. var tessellation = options.tessellation || 64 | 0;
  61002. var radiusFunction = options.radiusFunction || null;
  61003. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61004. var invertUV = options.invertUV || false;
  61005. var updatable = options.updatable;
  61006. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61007. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61008. // tube geometry
  61009. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61010. var tangents = path3D.getTangents();
  61011. var normals = path3D.getNormals();
  61012. var distances = path3D.getDistances();
  61013. var pi2 = Math.PI * 2;
  61014. var step = pi2 / tessellation * arc;
  61015. var returnRadius = function () { return radius; };
  61016. var radiusFunctionFinal = radiusFunction || returnRadius;
  61017. var circlePath;
  61018. var rad;
  61019. var normal;
  61020. var rotated;
  61021. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61022. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61023. for (var i = 0; i < path.length; i++) {
  61024. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61025. circlePath = Array(); // current circle array
  61026. normal = normals[i]; // current normal
  61027. for (var t = 0; t < tessellation; t++) {
  61028. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61029. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61030. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61031. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61032. circlePath[t] = rotated;
  61033. }
  61034. circlePaths[index] = circlePath;
  61035. index++;
  61036. }
  61037. // cap
  61038. var capPath = function (nbPoints, pathIndex) {
  61039. var pointCap = Array();
  61040. for (var i = 0; i < nbPoints; i++) {
  61041. pointCap.push(path[pathIndex]);
  61042. }
  61043. return pointCap;
  61044. };
  61045. switch (cap) {
  61046. case BABYLON.Mesh.NO_CAP:
  61047. break;
  61048. case BABYLON.Mesh.CAP_START:
  61049. circlePaths[0] = capPath(tessellation, 0);
  61050. circlePaths[1] = circlePaths[2].slice(0);
  61051. break;
  61052. case BABYLON.Mesh.CAP_END:
  61053. circlePaths[index] = circlePaths[index - 1].slice(0);
  61054. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61055. break;
  61056. case BABYLON.Mesh.CAP_ALL:
  61057. circlePaths[0] = capPath(tessellation, 0);
  61058. circlePaths[1] = circlePaths[2].slice(0);
  61059. circlePaths[index] = circlePaths[index - 1].slice(0);
  61060. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61061. break;
  61062. default:
  61063. break;
  61064. }
  61065. return circlePaths;
  61066. };
  61067. var path3D;
  61068. var pathArray;
  61069. if (instance) { // tube update
  61070. var arc = options.arc || instance.arc;
  61071. path3D = (instance.path3D).update(path);
  61072. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61073. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61074. instance.path3D = path3D;
  61075. instance.pathArray = pathArray;
  61076. instance.arc = arc;
  61077. instance.radius = radius;
  61078. return instance;
  61079. }
  61080. // tube creation
  61081. path3D = new BABYLON.Path3D(path);
  61082. var newPathArray = new Array();
  61083. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61084. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61085. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61086. tube.pathArray = pathArray;
  61087. tube.path3D = path3D;
  61088. tube.tessellation = tessellation;
  61089. tube.cap = cap;
  61090. tube.arc = options.arc;
  61091. tube.radius = radius;
  61092. return tube;
  61093. };
  61094. /**
  61095. * Creates a polyhedron mesh
  61096. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61097. * * The parameter `size` (positive float, default 1) sets the polygon size
  61098. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61099. * * 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`
  61100. * * 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
  61101. * * 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)`)
  61102. * * 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
  61103. * * 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
  61104. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61105. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61106. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61107. * @param name defines the name of the mesh
  61108. * @param options defines the options used to create the mesh
  61109. * @param scene defines the hosting scene
  61110. * @returns the polyhedron mesh
  61111. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61112. */
  61113. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61114. var polyhedron = new BABYLON.Mesh(name, scene);
  61115. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61116. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61117. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61118. vertexData.applyToMesh(polyhedron, options.updatable);
  61119. return polyhedron;
  61120. };
  61121. /**
  61122. * Creates a decal mesh.
  61123. * 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
  61124. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61125. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61126. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61127. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61128. * @param name defines the name of the mesh
  61129. * @param sourceMesh defines the mesh where the decal must be applied
  61130. * @param options defines the options used to create the mesh
  61131. * @param scene defines the hosting scene
  61132. * @returns the decal mesh
  61133. * @see http://doc.babylonjs.com/how_to/decals
  61134. */
  61135. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61136. var indices = sourceMesh.getIndices();
  61137. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61138. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61139. var position = options.position || BABYLON.Vector3.Zero();
  61140. var normal = options.normal || BABYLON.Vector3.Up();
  61141. var size = options.size || BABYLON.Vector3.One();
  61142. var angle = options.angle || 0;
  61143. // Getting correct rotation
  61144. if (!normal) {
  61145. var target = new BABYLON.Vector3(0, 0, 1);
  61146. var camera = sourceMesh.getScene().activeCamera;
  61147. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61148. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61149. }
  61150. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61151. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61152. var pitch = Math.atan2(normal.y, len);
  61153. // Matrix
  61154. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61155. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61156. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61157. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61158. var vertexData = new BABYLON.VertexData();
  61159. vertexData.indices = [];
  61160. vertexData.positions = [];
  61161. vertexData.normals = [];
  61162. vertexData.uvs = [];
  61163. var currentVertexDataIndex = 0;
  61164. var extractDecalVector3 = function (indexId) {
  61165. var result = new BABYLON.PositionNormalVertex();
  61166. if (!indices || !positions || !normals) {
  61167. return result;
  61168. }
  61169. var vertexId = indices[indexId];
  61170. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61171. // Send vector to decal local world
  61172. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61173. // Get normal
  61174. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61175. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61176. return result;
  61177. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61178. var clip = function (vertices, axis) {
  61179. if (vertices.length === 0) {
  61180. return vertices;
  61181. }
  61182. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61183. var clipVertices = function (v0, v1) {
  61184. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61185. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61186. };
  61187. var result = new Array();
  61188. for (var index = 0; index < vertices.length; index += 3) {
  61189. var v1Out;
  61190. var v2Out;
  61191. var v3Out;
  61192. var total = 0;
  61193. var nV1 = null;
  61194. var nV2 = null;
  61195. var nV3 = null;
  61196. var nV4 = null;
  61197. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61198. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61199. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61200. v1Out = d1 > 0;
  61201. v2Out = d2 > 0;
  61202. v3Out = d3 > 0;
  61203. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61204. switch (total) {
  61205. case 0:
  61206. result.push(vertices[index]);
  61207. result.push(vertices[index + 1]);
  61208. result.push(vertices[index + 2]);
  61209. break;
  61210. case 1:
  61211. if (v1Out) {
  61212. nV1 = vertices[index + 1];
  61213. nV2 = vertices[index + 2];
  61214. nV3 = clipVertices(vertices[index], nV1);
  61215. nV4 = clipVertices(vertices[index], nV2);
  61216. }
  61217. if (v2Out) {
  61218. nV1 = vertices[index];
  61219. nV2 = vertices[index + 2];
  61220. nV3 = clipVertices(vertices[index + 1], nV1);
  61221. nV4 = clipVertices(vertices[index + 1], nV2);
  61222. result.push(nV3);
  61223. result.push(nV2.clone());
  61224. result.push(nV1.clone());
  61225. result.push(nV2.clone());
  61226. result.push(nV3.clone());
  61227. result.push(nV4);
  61228. break;
  61229. }
  61230. if (v3Out) {
  61231. nV1 = vertices[index];
  61232. nV2 = vertices[index + 1];
  61233. nV3 = clipVertices(vertices[index + 2], nV1);
  61234. nV4 = clipVertices(vertices[index + 2], nV2);
  61235. }
  61236. if (nV1 && nV2 && nV3 && nV4) {
  61237. result.push(nV1.clone());
  61238. result.push(nV2.clone());
  61239. result.push(nV3);
  61240. result.push(nV4);
  61241. result.push(nV3.clone());
  61242. result.push(nV2.clone());
  61243. }
  61244. break;
  61245. case 2:
  61246. if (!v1Out) {
  61247. nV1 = vertices[index].clone();
  61248. nV2 = clipVertices(nV1, vertices[index + 1]);
  61249. nV3 = clipVertices(nV1, vertices[index + 2]);
  61250. result.push(nV1);
  61251. result.push(nV2);
  61252. result.push(nV3);
  61253. }
  61254. if (!v2Out) {
  61255. nV1 = vertices[index + 1].clone();
  61256. nV2 = clipVertices(nV1, vertices[index + 2]);
  61257. nV3 = clipVertices(nV1, vertices[index]);
  61258. result.push(nV1);
  61259. result.push(nV2);
  61260. result.push(nV3);
  61261. }
  61262. if (!v3Out) {
  61263. nV1 = vertices[index + 2].clone();
  61264. nV2 = clipVertices(nV1, vertices[index]);
  61265. nV3 = clipVertices(nV1, vertices[index + 1]);
  61266. result.push(nV1);
  61267. result.push(nV2);
  61268. result.push(nV3);
  61269. }
  61270. break;
  61271. case 3:
  61272. break;
  61273. }
  61274. }
  61275. return result;
  61276. };
  61277. for (var index = 0; index < indices.length; index += 3) {
  61278. var faceVertices = new Array();
  61279. faceVertices.push(extractDecalVector3(index));
  61280. faceVertices.push(extractDecalVector3(index + 1));
  61281. faceVertices.push(extractDecalVector3(index + 2));
  61282. // Clip
  61283. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61284. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61285. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61286. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61287. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61288. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61289. if (faceVertices.length === 0) {
  61290. continue;
  61291. }
  61292. // Add UVs and get back to world
  61293. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61294. var vertex = faceVertices[vIndex];
  61295. //TODO check for Int32Array | Uint32Array | Uint16Array
  61296. vertexData.indices.push(currentVertexDataIndex);
  61297. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61298. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61299. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61300. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61301. currentVertexDataIndex++;
  61302. }
  61303. }
  61304. // Return mesh
  61305. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61306. vertexData.applyToMesh(decal);
  61307. decal.position = position.clone();
  61308. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61309. return decal;
  61310. };
  61311. // Privates
  61312. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61313. // extrusion geometry
  61314. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61315. var tangents = path3D.getTangents();
  61316. var normals = path3D.getNormals();
  61317. var binormals = path3D.getBinormals();
  61318. var distances = path3D.getDistances();
  61319. var angle = 0;
  61320. var returnScale = function () { return scale !== null ? scale : 1; };
  61321. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61322. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61323. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61324. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61325. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61326. for (var i = 0; i < curve.length; i++) {
  61327. var shapePath = new Array();
  61328. var angleStep = rotate(i, distances[i]);
  61329. var scaleRatio = scl(i, distances[i]);
  61330. for (var p = 0; p < shape.length; p++) {
  61331. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61332. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61333. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61334. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61335. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61336. shapePath[p] = rotated;
  61337. }
  61338. shapePaths[index] = shapePath;
  61339. angle += angleStep;
  61340. index++;
  61341. }
  61342. // cap
  61343. var capPath = function (shapePath) {
  61344. var pointCap = Array();
  61345. var barycenter = BABYLON.Vector3.Zero();
  61346. var i;
  61347. for (i = 0; i < shapePath.length; i++) {
  61348. barycenter.addInPlace(shapePath[i]);
  61349. }
  61350. barycenter.scaleInPlace(1.0 / shapePath.length);
  61351. for (i = 0; i < shapePath.length; i++) {
  61352. pointCap.push(barycenter);
  61353. }
  61354. return pointCap;
  61355. };
  61356. switch (cap) {
  61357. case BABYLON.Mesh.NO_CAP:
  61358. break;
  61359. case BABYLON.Mesh.CAP_START:
  61360. shapePaths[0] = capPath(shapePaths[2]);
  61361. shapePaths[1] = shapePaths[2];
  61362. break;
  61363. case BABYLON.Mesh.CAP_END:
  61364. shapePaths[index] = shapePaths[index - 1];
  61365. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61366. break;
  61367. case BABYLON.Mesh.CAP_ALL:
  61368. shapePaths[0] = capPath(shapePaths[2]);
  61369. shapePaths[1] = shapePaths[2];
  61370. shapePaths[index] = shapePaths[index - 1];
  61371. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61372. break;
  61373. default:
  61374. break;
  61375. }
  61376. return shapePaths;
  61377. };
  61378. var path3D;
  61379. var pathArray;
  61380. if (instance) { // instance update
  61381. path3D = (instance.path3D).update(curve);
  61382. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61383. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61384. return instance;
  61385. }
  61386. // extruded shape creation
  61387. path3D = new BABYLON.Path3D(curve);
  61388. var newShapePaths = new Array();
  61389. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61390. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61391. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61392. extrudedGeneric.pathArray = pathArray;
  61393. extrudedGeneric.path3D = path3D;
  61394. extrudedGeneric.cap = cap;
  61395. return extrudedGeneric;
  61396. };
  61397. return MeshBuilder;
  61398. }());
  61399. BABYLON.MeshBuilder = MeshBuilder;
  61400. })(BABYLON || (BABYLON = {}));
  61401. //# sourceMappingURL=babylon.meshBuilder.js.map
  61402. var BABYLON;
  61403. (function (BABYLON) {
  61404. /**
  61405. * Draco compression (https://google.github.io/draco/)
  61406. *
  61407. * This class wraps the Draco module.
  61408. *
  61409. * **Encoder**
  61410. *
  61411. * The encoder is not currently implemented.
  61412. *
  61413. * **Decoder**
  61414. *
  61415. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61416. *
  61417. * To update the configuration, use the following code:
  61418. * ```javascript
  61419. * BABYLON.DracoCompression.Configuration = {
  61420. * decoder: {
  61421. * wasmUrl: "<url to the WebAssembly library>",
  61422. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61423. * fallbackUrl: "<url to the fallback JavaScript library>",
  61424. * }
  61425. * };
  61426. * ```
  61427. *
  61428. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  61429. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61430. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61431. *
  61432. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61433. * ```javascript
  61434. * var dracoCompression = new BABYLON.DracoCompression();
  61435. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61436. * [BABYLON.VertexBuffer.PositionKind]: 0
  61437. * });
  61438. * ```
  61439. *
  61440. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61441. */
  61442. var DracoCompression = /** @class */ (function () {
  61443. /**
  61444. * Constructor
  61445. */
  61446. function DracoCompression() {
  61447. }
  61448. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61449. /**
  61450. * Returns true if the decoder is available.
  61451. */
  61452. get: function () {
  61453. if (typeof DracoDecoderModule !== "undefined") {
  61454. return true;
  61455. }
  61456. var decoder = DracoCompression.Configuration.decoder;
  61457. if (decoder) {
  61458. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61459. return true;
  61460. }
  61461. if (decoder.fallbackUrl) {
  61462. return true;
  61463. }
  61464. }
  61465. return false;
  61466. },
  61467. enumerable: true,
  61468. configurable: true
  61469. });
  61470. /**
  61471. * Stop all async operations and release resources.
  61472. */
  61473. DracoCompression.prototype.dispose = function () {
  61474. };
  61475. /**
  61476. * Decode Draco compressed mesh data to vertex data.
  61477. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61478. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61479. * @returns A promise that resolves with the decoded vertex data
  61480. */
  61481. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61482. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61483. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61484. var module = wrappedModule.module;
  61485. var vertexData = new BABYLON.VertexData();
  61486. var buffer = new module.DecoderBuffer();
  61487. buffer.Init(dataView, dataView.byteLength);
  61488. var decoder = new module.Decoder();
  61489. var geometry;
  61490. var status;
  61491. try {
  61492. var type = decoder.GetEncodedGeometryType(buffer);
  61493. switch (type) {
  61494. case module.TRIANGULAR_MESH:
  61495. geometry = new module.Mesh();
  61496. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61497. break;
  61498. case module.POINT_CLOUD:
  61499. geometry = new module.PointCloud();
  61500. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61501. break;
  61502. default:
  61503. throw new Error("Invalid geometry type " + type);
  61504. }
  61505. if (!status.ok() || !geometry.ptr) {
  61506. throw new Error(status.error_msg());
  61507. }
  61508. var numPoints = geometry.num_points();
  61509. if (type === module.TRIANGULAR_MESH) {
  61510. var numFaces = geometry.num_faces();
  61511. var faceIndices = new module.DracoInt32Array();
  61512. try {
  61513. var indices = new Uint32Array(numFaces * 3);
  61514. for (var i = 0; i < numFaces; i++) {
  61515. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61516. var offset = i * 3;
  61517. indices[offset + 0] = faceIndices.GetValue(0);
  61518. indices[offset + 1] = faceIndices.GetValue(1);
  61519. indices[offset + 2] = faceIndices.GetValue(2);
  61520. }
  61521. vertexData.indices = indices;
  61522. }
  61523. finally {
  61524. module.destroy(faceIndices);
  61525. }
  61526. }
  61527. for (var kind in attributes) {
  61528. var uniqueId = attributes[kind];
  61529. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61530. var dracoData = new module.DracoFloat32Array();
  61531. try {
  61532. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61533. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61534. for (var i = 0; i < babylonData.length; i++) {
  61535. babylonData[i] = dracoData.GetValue(i);
  61536. }
  61537. vertexData.set(babylonData, kind);
  61538. }
  61539. finally {
  61540. module.destroy(dracoData);
  61541. }
  61542. }
  61543. }
  61544. finally {
  61545. if (geometry) {
  61546. module.destroy(geometry);
  61547. }
  61548. module.destroy(decoder);
  61549. module.destroy(buffer);
  61550. }
  61551. return vertexData;
  61552. });
  61553. };
  61554. DracoCompression._GetDecoderModule = function () {
  61555. if (!DracoCompression._DecoderModulePromise) {
  61556. var promise = null;
  61557. var config_1 = {};
  61558. if (typeof DracoDecoderModule !== "undefined") {
  61559. promise = Promise.resolve();
  61560. }
  61561. else {
  61562. var decoder = DracoCompression.Configuration.decoder;
  61563. if (decoder) {
  61564. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61565. promise = Promise.all([
  61566. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61567. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61568. config_1.wasmBinary = data;
  61569. })
  61570. ]);
  61571. }
  61572. else if (decoder.fallbackUrl) {
  61573. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61574. }
  61575. }
  61576. }
  61577. if (!promise) {
  61578. throw new Error("Draco decoder module is not available");
  61579. }
  61580. DracoCompression._DecoderModulePromise = promise.then(function () {
  61581. return new Promise(function (resolve) {
  61582. config_1.onModuleLoaded = function (decoderModule) {
  61583. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61584. resolve({ module: decoderModule });
  61585. };
  61586. DracoDecoderModule(config_1);
  61587. });
  61588. });
  61589. }
  61590. return DracoCompression._DecoderModulePromise;
  61591. };
  61592. DracoCompression._LoadScriptAsync = function (url) {
  61593. return new Promise(function (resolve, reject) {
  61594. BABYLON.Tools.LoadScript(url, function () {
  61595. resolve();
  61596. }, function (message) {
  61597. reject(new Error(message));
  61598. });
  61599. });
  61600. };
  61601. DracoCompression._LoadFileAsync = function (url) {
  61602. return new Promise(function (resolve, reject) {
  61603. BABYLON.Tools.LoadFile(url, function (data) {
  61604. resolve(data);
  61605. }, undefined, undefined, true, function (request, exception) {
  61606. reject(exception);
  61607. });
  61608. });
  61609. };
  61610. /**
  61611. * The configuration. Defaults to the following urls:
  61612. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61613. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61614. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61615. */
  61616. DracoCompression.Configuration = {
  61617. decoder: {
  61618. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61619. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61620. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61621. }
  61622. };
  61623. return DracoCompression;
  61624. }());
  61625. BABYLON.DracoCompression = DracoCompression;
  61626. })(BABYLON || (BABYLON = {}));
  61627. //# sourceMappingURL=babylon.dracoCompression.js.map
  61628. var BABYLON;
  61629. (function (BABYLON) {
  61630. var AudioEngine = /** @class */ (function () {
  61631. function AudioEngine() {
  61632. this._audioContext = null;
  61633. this._audioContextInitialized = false;
  61634. this.canUseWebAudio = false;
  61635. this.WarnedWebAudioUnsupported = false;
  61636. this.unlocked = false;
  61637. this.isMP3supported = false;
  61638. this.isOGGsupported = false;
  61639. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61640. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61641. this.canUseWebAudio = true;
  61642. }
  61643. var audioElem = document.createElement('audio');
  61644. try {
  61645. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61646. this.isMP3supported = true;
  61647. }
  61648. }
  61649. catch (e) {
  61650. // protect error during capability check.
  61651. }
  61652. try {
  61653. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61654. this.isOGGsupported = true;
  61655. }
  61656. }
  61657. catch (e) {
  61658. // protect error during capability check.
  61659. }
  61660. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61661. this._unlockiOSaudio();
  61662. }
  61663. else {
  61664. this.unlocked = true;
  61665. }
  61666. }
  61667. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61668. get: function () {
  61669. if (!this._audioContextInitialized) {
  61670. this._initializeAudioContext();
  61671. }
  61672. return this._audioContext;
  61673. },
  61674. enumerable: true,
  61675. configurable: true
  61676. });
  61677. AudioEngine.prototype._unlockiOSaudio = function () {
  61678. var _this = this;
  61679. var unlockaudio = function () {
  61680. if (!_this.audioContext) {
  61681. return;
  61682. }
  61683. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61684. var source = _this.audioContext.createBufferSource();
  61685. source.buffer = buffer;
  61686. source.connect(_this.audioContext.destination);
  61687. source.start(0);
  61688. setTimeout(function () {
  61689. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61690. _this.unlocked = true;
  61691. window.removeEventListener('touchend', unlockaudio, false);
  61692. if (_this.onAudioUnlocked) {
  61693. _this.onAudioUnlocked();
  61694. }
  61695. }
  61696. }, 0);
  61697. };
  61698. window.addEventListener('touchend', unlockaudio, false);
  61699. };
  61700. AudioEngine.prototype._initializeAudioContext = function () {
  61701. try {
  61702. if (this.canUseWebAudio) {
  61703. this._audioContext = new AudioContext();
  61704. // create a global volume gain node
  61705. this.masterGain = this._audioContext.createGain();
  61706. this.masterGain.gain.value = 1;
  61707. this.masterGain.connect(this._audioContext.destination);
  61708. this._audioContextInitialized = true;
  61709. }
  61710. }
  61711. catch (e) {
  61712. this.canUseWebAudio = false;
  61713. BABYLON.Tools.Error("Web Audio: " + e.message);
  61714. }
  61715. };
  61716. AudioEngine.prototype.dispose = function () {
  61717. if (this.canUseWebAudio && this._audioContextInitialized) {
  61718. if (this._connectedAnalyser && this._audioContext) {
  61719. this._connectedAnalyser.stopDebugCanvas();
  61720. this._connectedAnalyser.dispose();
  61721. this.masterGain.disconnect();
  61722. this.masterGain.connect(this._audioContext.destination);
  61723. this._connectedAnalyser = null;
  61724. }
  61725. this.masterGain.gain.value = 1;
  61726. }
  61727. this.WarnedWebAudioUnsupported = false;
  61728. };
  61729. AudioEngine.prototype.getGlobalVolume = function () {
  61730. if (this.canUseWebAudio && this._audioContextInitialized) {
  61731. return this.masterGain.gain.value;
  61732. }
  61733. else {
  61734. return -1;
  61735. }
  61736. };
  61737. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61738. if (this.canUseWebAudio && this._audioContextInitialized) {
  61739. this.masterGain.gain.value = newVolume;
  61740. }
  61741. };
  61742. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61743. if (this._connectedAnalyser) {
  61744. this._connectedAnalyser.stopDebugCanvas();
  61745. }
  61746. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61747. this._connectedAnalyser = analyser;
  61748. this.masterGain.disconnect();
  61749. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61750. }
  61751. };
  61752. return AudioEngine;
  61753. }());
  61754. BABYLON.AudioEngine = AudioEngine;
  61755. })(BABYLON || (BABYLON = {}));
  61756. //# sourceMappingURL=babylon.audioEngine.js.map
  61757. var BABYLON;
  61758. (function (BABYLON) {
  61759. var Sound = /** @class */ (function () {
  61760. /**
  61761. * Create a sound and attach it to a scene
  61762. * @param name Name of your sound
  61763. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  61764. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61765. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61766. */
  61767. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61768. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61769. var _this = this;
  61770. this.autoplay = false;
  61771. this.loop = false;
  61772. this.useCustomAttenuation = false;
  61773. this.spatialSound = false;
  61774. this.refDistance = 1;
  61775. this.rolloffFactor = 1;
  61776. this.maxDistance = 100;
  61777. this.distanceModel = "linear";
  61778. this._panningModel = "equalpower";
  61779. this._playbackRate = 1;
  61780. this._streaming = false;
  61781. this._startTime = 0;
  61782. this._startOffset = 0;
  61783. this._position = BABYLON.Vector3.Zero();
  61784. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61785. this._volume = 1;
  61786. this._isReadyToPlay = false;
  61787. this.isPlaying = false;
  61788. this.isPaused = false;
  61789. this._isDirectional = false;
  61790. // Used if you'd like to create a directional sound.
  61791. // If not set, the sound will be omnidirectional
  61792. this._coneInnerAngle = 360;
  61793. this._coneOuterAngle = 360;
  61794. this._coneOuterGain = 0;
  61795. this._isOutputConnected = false;
  61796. this._urlType = "Unknown";
  61797. this.name = name;
  61798. this._scene = scene;
  61799. this._readyToPlayCallback = readyToPlayCallback;
  61800. // Default custom attenuation function is a linear attenuation
  61801. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61802. if (currentDistance < maxDistance) {
  61803. return currentVolume * (1 - currentDistance / maxDistance);
  61804. }
  61805. else {
  61806. return 0;
  61807. }
  61808. };
  61809. if (options) {
  61810. this.autoplay = options.autoplay || false;
  61811. this.loop = options.loop || false;
  61812. // if volume === 0, we need another way to check this option
  61813. if (options.volume !== undefined) {
  61814. this._volume = options.volume;
  61815. }
  61816. this.spatialSound = options.spatialSound || false;
  61817. this.maxDistance = options.maxDistance || 100;
  61818. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61819. this.rolloffFactor = options.rolloffFactor || 1;
  61820. this.refDistance = options.refDistance || 1;
  61821. this.distanceModel = options.distanceModel || "linear";
  61822. this._playbackRate = options.playbackRate || 1;
  61823. this._streaming = options.streaming || false;
  61824. }
  61825. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61826. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61827. this._soundGain.gain.value = this._volume;
  61828. this._inputAudioNode = this._soundGain;
  61829. this._ouputAudioNode = this._soundGain;
  61830. if (this.spatialSound) {
  61831. this._createSpatialParameters();
  61832. }
  61833. this._scene.mainSoundTrack.AddSound(this);
  61834. var validParameter = true;
  61835. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61836. if (urlOrArrayBuffer) {
  61837. try {
  61838. if (typeof (urlOrArrayBuffer) === "string") {
  61839. this._urlType = "String";
  61840. }
  61841. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  61842. this._urlType = "ArrayBuffer";
  61843. }
  61844. else if (urlOrArrayBuffer instanceof MediaStream) {
  61845. this._urlType = "MediaStream";
  61846. }
  61847. else if (Array.isArray(urlOrArrayBuffer)) {
  61848. this._urlType = "Array";
  61849. }
  61850. var urls = [];
  61851. var codecSupportedFound = false;
  61852. switch (this._urlType) {
  61853. case "MediaStream":
  61854. this._streaming = true;
  61855. this._isReadyToPlay = true;
  61856. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  61857. if (this.autoplay) {
  61858. this.play();
  61859. }
  61860. if (this._readyToPlayCallback) {
  61861. this._readyToPlayCallback();
  61862. }
  61863. break;
  61864. case "ArrayBuffer":
  61865. if (urlOrArrayBuffer.byteLength > 0) {
  61866. codecSupportedFound = true;
  61867. this._soundLoaded(urlOrArrayBuffer);
  61868. }
  61869. break;
  61870. case "String":
  61871. urls.push(urlOrArrayBuffer);
  61872. case "Array":
  61873. if (urls.length === 0)
  61874. urls = urlOrArrayBuffer;
  61875. // If we found a supported format, we load it immediately and stop the loop
  61876. for (var i = 0; i < urls.length; i++) {
  61877. var url = urls[i];
  61878. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61879. codecSupportedFound = true;
  61880. }
  61881. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61882. codecSupportedFound = true;
  61883. }
  61884. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61885. codecSupportedFound = true;
  61886. }
  61887. if (url.indexOf("blob:") !== -1) {
  61888. codecSupportedFound = true;
  61889. }
  61890. if (codecSupportedFound) {
  61891. // Loading sound using XHR2
  61892. if (!this._streaming) {
  61893. this._scene._loadFile(url, function (data) {
  61894. _this._soundLoaded(data);
  61895. }, undefined, true, true, function (exception) {
  61896. if (exception) {
  61897. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61898. }
  61899. BABYLON.Tools.Error("Sound creation aborted.");
  61900. _this._scene.mainSoundTrack.RemoveSound(_this);
  61901. });
  61902. }
  61903. // Streaming sound using HTML5 Audio tag
  61904. else {
  61905. this._htmlAudioElement = new Audio(url);
  61906. this._htmlAudioElement.controls = false;
  61907. this._htmlAudioElement.loop = this.loop;
  61908. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61909. this._htmlAudioElement.preload = "auto";
  61910. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61911. _this._isReadyToPlay = true;
  61912. if (_this.autoplay) {
  61913. _this.play();
  61914. }
  61915. if (_this._readyToPlayCallback) {
  61916. _this._readyToPlayCallback();
  61917. }
  61918. });
  61919. document.body.appendChild(this._htmlAudioElement);
  61920. }
  61921. break;
  61922. }
  61923. }
  61924. break;
  61925. default:
  61926. validParameter = false;
  61927. break;
  61928. }
  61929. if (!validParameter) {
  61930. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61931. }
  61932. else {
  61933. if (!codecSupportedFound) {
  61934. this._isReadyToPlay = true;
  61935. // Simulating a ready to play event to avoid breaking code path
  61936. if (this._readyToPlayCallback) {
  61937. window.setTimeout(function () {
  61938. if (_this._readyToPlayCallback) {
  61939. _this._readyToPlayCallback();
  61940. }
  61941. }, 1000);
  61942. }
  61943. }
  61944. }
  61945. }
  61946. catch (ex) {
  61947. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61948. this._scene.mainSoundTrack.RemoveSound(this);
  61949. }
  61950. }
  61951. }
  61952. else {
  61953. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61954. this._scene.mainSoundTrack.AddSound(this);
  61955. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61956. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61957. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61958. }
  61959. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61960. if (this._readyToPlayCallback) {
  61961. window.setTimeout(function () {
  61962. if (_this._readyToPlayCallback) {
  61963. _this._readyToPlayCallback();
  61964. }
  61965. }, 1000);
  61966. }
  61967. }
  61968. }
  61969. Sound.prototype.dispose = function () {
  61970. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61971. if (this.isPlaying) {
  61972. this.stop();
  61973. }
  61974. this._isReadyToPlay = false;
  61975. if (this.soundTrackId === -1) {
  61976. this._scene.mainSoundTrack.RemoveSound(this);
  61977. }
  61978. else {
  61979. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61980. }
  61981. if (this._soundGain) {
  61982. this._soundGain.disconnect();
  61983. this._soundGain = null;
  61984. }
  61985. if (this._soundPanner) {
  61986. this._soundPanner.disconnect();
  61987. this._soundPanner = null;
  61988. }
  61989. if (this._soundSource) {
  61990. this._soundSource.disconnect();
  61991. this._soundSource = null;
  61992. }
  61993. this._audioBuffer = null;
  61994. if (this._htmlAudioElement) {
  61995. this._htmlAudioElement.pause();
  61996. this._htmlAudioElement.src = "";
  61997. document.body.removeChild(this._htmlAudioElement);
  61998. }
  61999. if (this._streamingSource) {
  62000. this._streamingSource.disconnect();
  62001. }
  62002. if (this._connectedMesh && this._registerFunc) {
  62003. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62004. this._connectedMesh = null;
  62005. }
  62006. }
  62007. };
  62008. Sound.prototype.isReady = function () {
  62009. return this._isReadyToPlay;
  62010. };
  62011. Sound.prototype._soundLoaded = function (audioData) {
  62012. var _this = this;
  62013. if (!BABYLON.Engine.audioEngine.audioContext) {
  62014. return;
  62015. }
  62016. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62017. _this._audioBuffer = buffer;
  62018. _this._isReadyToPlay = true;
  62019. if (_this.autoplay) {
  62020. _this.play();
  62021. }
  62022. if (_this._readyToPlayCallback) {
  62023. _this._readyToPlayCallback();
  62024. }
  62025. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62026. };
  62027. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62028. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62029. this._audioBuffer = audioBuffer;
  62030. this._isReadyToPlay = true;
  62031. }
  62032. };
  62033. Sound.prototype.updateOptions = function (options) {
  62034. if (options) {
  62035. this.loop = options.loop || this.loop;
  62036. this.maxDistance = options.maxDistance || this.maxDistance;
  62037. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62038. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62039. this.refDistance = options.refDistance || this.refDistance;
  62040. this.distanceModel = options.distanceModel || this.distanceModel;
  62041. this._playbackRate = options.playbackRate || this._playbackRate;
  62042. this._updateSpatialParameters();
  62043. if (this.isPlaying) {
  62044. if (this._streaming && this._htmlAudioElement) {
  62045. this._htmlAudioElement.playbackRate = this._playbackRate;
  62046. }
  62047. else {
  62048. if (this._soundSource) {
  62049. this._soundSource.playbackRate.value = this._playbackRate;
  62050. }
  62051. }
  62052. }
  62053. }
  62054. };
  62055. Sound.prototype._createSpatialParameters = function () {
  62056. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62057. if (this._scene.headphone) {
  62058. this._panningModel = "HRTF";
  62059. }
  62060. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62061. this._updateSpatialParameters();
  62062. this._soundPanner.connect(this._ouputAudioNode);
  62063. this._inputAudioNode = this._soundPanner;
  62064. }
  62065. };
  62066. Sound.prototype._updateSpatialParameters = function () {
  62067. if (this.spatialSound && this._soundPanner) {
  62068. if (this.useCustomAttenuation) {
  62069. // Tricks to disable in a way embedded Web Audio attenuation
  62070. this._soundPanner.distanceModel = "linear";
  62071. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62072. this._soundPanner.refDistance = 1;
  62073. this._soundPanner.rolloffFactor = 1;
  62074. this._soundPanner.panningModel = this._panningModel;
  62075. }
  62076. else {
  62077. this._soundPanner.distanceModel = this.distanceModel;
  62078. this._soundPanner.maxDistance = this.maxDistance;
  62079. this._soundPanner.refDistance = this.refDistance;
  62080. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62081. this._soundPanner.panningModel = this._panningModel;
  62082. }
  62083. }
  62084. };
  62085. Sound.prototype.switchPanningModelToHRTF = function () {
  62086. this._panningModel = "HRTF";
  62087. this._switchPanningModel();
  62088. };
  62089. Sound.prototype.switchPanningModelToEqualPower = function () {
  62090. this._panningModel = "equalpower";
  62091. this._switchPanningModel();
  62092. };
  62093. Sound.prototype._switchPanningModel = function () {
  62094. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62095. this._soundPanner.panningModel = this._panningModel;
  62096. }
  62097. };
  62098. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62100. if (this._isOutputConnected) {
  62101. this._ouputAudioNode.disconnect();
  62102. }
  62103. this._ouputAudioNode.connect(soundTrackAudioNode);
  62104. this._isOutputConnected = true;
  62105. }
  62106. };
  62107. /**
  62108. * Transform this sound into a directional source
  62109. * @param coneInnerAngle Size of the inner cone in degree
  62110. * @param coneOuterAngle Size of the outer cone in degree
  62111. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62112. */
  62113. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62114. if (coneOuterAngle < coneInnerAngle) {
  62115. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62116. return;
  62117. }
  62118. this._coneInnerAngle = coneInnerAngle;
  62119. this._coneOuterAngle = coneOuterAngle;
  62120. this._coneOuterGain = coneOuterGain;
  62121. this._isDirectional = true;
  62122. if (this.isPlaying && this.loop) {
  62123. this.stop();
  62124. this.play();
  62125. }
  62126. };
  62127. Sound.prototype.setPosition = function (newPosition) {
  62128. this._position = newPosition;
  62129. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62130. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62131. }
  62132. };
  62133. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62134. this._localDirection = newLocalDirection;
  62135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62136. this._updateDirection();
  62137. }
  62138. };
  62139. Sound.prototype._updateDirection = function () {
  62140. if (!this._connectedMesh || !this._soundPanner) {
  62141. return;
  62142. }
  62143. var mat = this._connectedMesh.getWorldMatrix();
  62144. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62145. direction.normalize();
  62146. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62147. };
  62148. Sound.prototype.updateDistanceFromListener = function () {
  62149. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62150. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62151. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62152. }
  62153. };
  62154. Sound.prototype.setAttenuationFunction = function (callback) {
  62155. this._customAttenuationFunction = callback;
  62156. };
  62157. /**
  62158. * Play the sound
  62159. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62160. * @param offset (optional) Start the sound setting it at a specific time
  62161. */
  62162. Sound.prototype.play = function (time, offset) {
  62163. var _this = this;
  62164. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62165. try {
  62166. if (this._startOffset < 0) {
  62167. time = -this._startOffset;
  62168. this._startOffset = 0;
  62169. }
  62170. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62171. if (!this._soundSource || !this._streamingSource) {
  62172. if (this.spatialSound && this._soundPanner) {
  62173. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62174. if (this._isDirectional) {
  62175. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62176. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62177. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62178. if (this._connectedMesh) {
  62179. this._updateDirection();
  62180. }
  62181. else {
  62182. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62183. }
  62184. }
  62185. }
  62186. }
  62187. if (this._streaming) {
  62188. if (!this._streamingSource) {
  62189. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62190. this._htmlAudioElement.onended = function () { _this._onended(); };
  62191. this._htmlAudioElement.playbackRate = this._playbackRate;
  62192. }
  62193. this._streamingSource.disconnect();
  62194. this._streamingSource.connect(this._inputAudioNode);
  62195. if (this._htmlAudioElement) {
  62196. this._htmlAudioElement.play();
  62197. }
  62198. }
  62199. else {
  62200. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62201. this._soundSource.buffer = this._audioBuffer;
  62202. this._soundSource.connect(this._inputAudioNode);
  62203. this._soundSource.loop = this.loop;
  62204. this._soundSource.playbackRate.value = this._playbackRate;
  62205. this._soundSource.onended = function () { _this._onended(); };
  62206. if (this._soundSource.buffer) {
  62207. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62208. }
  62209. }
  62210. this._startTime = startTime;
  62211. this.isPlaying = true;
  62212. this.isPaused = false;
  62213. }
  62214. catch (ex) {
  62215. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62216. }
  62217. }
  62218. };
  62219. Sound.prototype._onended = function () {
  62220. this.isPlaying = false;
  62221. if (this.onended) {
  62222. this.onended();
  62223. }
  62224. };
  62225. /**
  62226. * Stop the sound
  62227. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62228. */
  62229. Sound.prototype.stop = function (time) {
  62230. if (this.isPlaying) {
  62231. if (this._streaming) {
  62232. if (this._htmlAudioElement) {
  62233. this._htmlAudioElement.pause();
  62234. // Test needed for Firefox or it will generate an Invalid State Error
  62235. if (this._htmlAudioElement.currentTime > 0) {
  62236. this._htmlAudioElement.currentTime = 0;
  62237. }
  62238. }
  62239. else {
  62240. this._streamingSource.disconnect();
  62241. }
  62242. }
  62243. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62244. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62245. this._soundSource.stop(stopTime);
  62246. this._soundSource.onended = function () { };
  62247. if (!this.isPaused) {
  62248. this._startOffset = 0;
  62249. }
  62250. }
  62251. this.isPlaying = false;
  62252. }
  62253. };
  62254. Sound.prototype.pause = function () {
  62255. if (this.isPlaying) {
  62256. this.isPaused = true;
  62257. if (this._streaming) {
  62258. if (this._htmlAudioElement) {
  62259. this._htmlAudioElement.pause();
  62260. }
  62261. else {
  62262. this._streamingSource.disconnect();
  62263. }
  62264. }
  62265. else if (BABYLON.Engine.audioEngine.audioContext) {
  62266. this.stop(0);
  62267. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62268. }
  62269. }
  62270. };
  62271. Sound.prototype.setVolume = function (newVolume, time) {
  62272. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62273. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62274. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62275. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62276. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62277. }
  62278. else {
  62279. this._soundGain.gain.value = newVolume;
  62280. }
  62281. }
  62282. this._volume = newVolume;
  62283. };
  62284. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62285. this._playbackRate = newPlaybackRate;
  62286. if (this.isPlaying) {
  62287. if (this._streaming && this._htmlAudioElement) {
  62288. this._htmlAudioElement.playbackRate = this._playbackRate;
  62289. }
  62290. else if (this._soundSource) {
  62291. this._soundSource.playbackRate.value = this._playbackRate;
  62292. }
  62293. }
  62294. };
  62295. Sound.prototype.getVolume = function () {
  62296. return this._volume;
  62297. };
  62298. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62299. var _this = this;
  62300. if (this._connectedMesh && this._registerFunc) {
  62301. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62302. this._registerFunc = null;
  62303. }
  62304. this._connectedMesh = meshToConnectTo;
  62305. if (!this.spatialSound) {
  62306. this.spatialSound = true;
  62307. this._createSpatialParameters();
  62308. if (this.isPlaying && this.loop) {
  62309. this.stop();
  62310. this.play();
  62311. }
  62312. }
  62313. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62314. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62315. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62316. };
  62317. Sound.prototype.detachFromMesh = function () {
  62318. if (this._connectedMesh && this._registerFunc) {
  62319. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62320. this._registerFunc = null;
  62321. this._connectedMesh = null;
  62322. }
  62323. };
  62324. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62325. if (!node.getBoundingInfo) {
  62326. return;
  62327. }
  62328. var mesh = node;
  62329. var boundingInfo = mesh.getBoundingInfo();
  62330. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62331. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62332. this._updateDirection();
  62333. }
  62334. };
  62335. Sound.prototype.clone = function () {
  62336. var _this = this;
  62337. if (!this._streaming) {
  62338. var setBufferAndRun = function () {
  62339. if (_this._isReadyToPlay) {
  62340. clonedSound._audioBuffer = _this.getAudioBuffer();
  62341. clonedSound._isReadyToPlay = true;
  62342. if (clonedSound.autoplay) {
  62343. clonedSound.play();
  62344. }
  62345. }
  62346. else {
  62347. window.setTimeout(setBufferAndRun, 300);
  62348. }
  62349. };
  62350. var currentOptions = {
  62351. autoplay: this.autoplay, loop: this.loop,
  62352. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62353. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62354. refDistance: this.refDistance, distanceModel: this.distanceModel
  62355. };
  62356. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62357. if (this.useCustomAttenuation) {
  62358. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62359. }
  62360. clonedSound.setPosition(this._position);
  62361. clonedSound.setPlaybackRate(this._playbackRate);
  62362. setBufferAndRun();
  62363. return clonedSound;
  62364. }
  62365. // Can't clone a streaming sound
  62366. else {
  62367. return null;
  62368. }
  62369. };
  62370. Sound.prototype.getAudioBuffer = function () {
  62371. return this._audioBuffer;
  62372. };
  62373. Sound.prototype.serialize = function () {
  62374. var serializationObject = {
  62375. name: this.name,
  62376. url: this.name,
  62377. autoplay: this.autoplay,
  62378. loop: this.loop,
  62379. volume: this._volume,
  62380. spatialSound: this.spatialSound,
  62381. maxDistance: this.maxDistance,
  62382. rolloffFactor: this.rolloffFactor,
  62383. refDistance: this.refDistance,
  62384. distanceModel: this.distanceModel,
  62385. playbackRate: this._playbackRate,
  62386. panningModel: this._panningModel,
  62387. soundTrackId: this.soundTrackId
  62388. };
  62389. if (this.spatialSound) {
  62390. if (this._connectedMesh)
  62391. serializationObject.connectedMeshId = this._connectedMesh.id;
  62392. serializationObject.position = this._position.asArray();
  62393. serializationObject.refDistance = this.refDistance;
  62394. serializationObject.distanceModel = this.distanceModel;
  62395. serializationObject.isDirectional = this._isDirectional;
  62396. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62397. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62398. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62399. serializationObject.coneOuterGain = this._coneOuterGain;
  62400. }
  62401. return serializationObject;
  62402. };
  62403. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62404. var soundName = parsedSound.name;
  62405. var soundUrl;
  62406. if (parsedSound.url) {
  62407. soundUrl = rootUrl + parsedSound.url;
  62408. }
  62409. else {
  62410. soundUrl = rootUrl + soundName;
  62411. }
  62412. var options = {
  62413. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62414. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62415. rolloffFactor: parsedSound.rolloffFactor,
  62416. refDistance: parsedSound.refDistance,
  62417. distanceModel: parsedSound.distanceModel,
  62418. playbackRate: parsedSound.playbackRate
  62419. };
  62420. var newSound;
  62421. if (!sourceSound) {
  62422. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62423. scene._addPendingData(newSound);
  62424. }
  62425. else {
  62426. var setBufferAndRun = function () {
  62427. if (sourceSound._isReadyToPlay) {
  62428. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62429. newSound._isReadyToPlay = true;
  62430. if (newSound.autoplay) {
  62431. newSound.play();
  62432. }
  62433. }
  62434. else {
  62435. window.setTimeout(setBufferAndRun, 300);
  62436. }
  62437. };
  62438. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62439. setBufferAndRun();
  62440. }
  62441. if (parsedSound.position) {
  62442. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62443. newSound.setPosition(soundPosition);
  62444. }
  62445. if (parsedSound.isDirectional) {
  62446. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62447. if (parsedSound.localDirectionToMesh) {
  62448. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62449. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62450. }
  62451. }
  62452. if (parsedSound.connectedMeshId) {
  62453. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62454. if (connectedMesh) {
  62455. newSound.attachToMesh(connectedMesh);
  62456. }
  62457. }
  62458. return newSound;
  62459. };
  62460. return Sound;
  62461. }());
  62462. BABYLON.Sound = Sound;
  62463. })(BABYLON || (BABYLON = {}));
  62464. //# sourceMappingURL=babylon.sound.js.map
  62465. var BABYLON;
  62466. (function (BABYLON) {
  62467. var SoundTrack = /** @class */ (function () {
  62468. function SoundTrack(scene, options) {
  62469. this.id = -1;
  62470. this._isMainTrack = false;
  62471. this._isInitialized = false;
  62472. this._scene = scene;
  62473. this.soundCollection = new Array();
  62474. this._options = options;
  62475. if (!this._isMainTrack) {
  62476. this._scene.soundTracks.push(this);
  62477. this.id = this._scene.soundTracks.length - 1;
  62478. }
  62479. }
  62480. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62481. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62482. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62483. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62484. if (this._options) {
  62485. if (this._options.volume) {
  62486. this._outputAudioNode.gain.value = this._options.volume;
  62487. }
  62488. if (this._options.mainTrack) {
  62489. this._isMainTrack = this._options.mainTrack;
  62490. }
  62491. }
  62492. this._isInitialized = true;
  62493. }
  62494. };
  62495. SoundTrack.prototype.dispose = function () {
  62496. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62497. if (this._connectedAnalyser) {
  62498. this._connectedAnalyser.stopDebugCanvas();
  62499. }
  62500. while (this.soundCollection.length) {
  62501. this.soundCollection[0].dispose();
  62502. }
  62503. if (this._outputAudioNode) {
  62504. this._outputAudioNode.disconnect();
  62505. }
  62506. this._outputAudioNode = null;
  62507. }
  62508. };
  62509. SoundTrack.prototype.AddSound = function (sound) {
  62510. if (!this._isInitialized) {
  62511. this._initializeSoundTrackAudioGraph();
  62512. }
  62513. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62514. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62515. }
  62516. if (sound.soundTrackId) {
  62517. if (sound.soundTrackId === -1) {
  62518. this._scene.mainSoundTrack.RemoveSound(sound);
  62519. }
  62520. else {
  62521. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62522. }
  62523. }
  62524. this.soundCollection.push(sound);
  62525. sound.soundTrackId = this.id;
  62526. };
  62527. SoundTrack.prototype.RemoveSound = function (sound) {
  62528. var index = this.soundCollection.indexOf(sound);
  62529. if (index !== -1) {
  62530. this.soundCollection.splice(index, 1);
  62531. }
  62532. };
  62533. SoundTrack.prototype.setVolume = function (newVolume) {
  62534. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62535. this._outputAudioNode.gain.value = newVolume;
  62536. }
  62537. };
  62538. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62539. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62540. for (var i = 0; i < this.soundCollection.length; i++) {
  62541. this.soundCollection[i].switchPanningModelToHRTF();
  62542. }
  62543. }
  62544. };
  62545. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62546. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62547. for (var i = 0; i < this.soundCollection.length; i++) {
  62548. this.soundCollection[i].switchPanningModelToEqualPower();
  62549. }
  62550. }
  62551. };
  62552. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62553. if (this._connectedAnalyser) {
  62554. this._connectedAnalyser.stopDebugCanvas();
  62555. }
  62556. this._connectedAnalyser = analyser;
  62557. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62558. this._outputAudioNode.disconnect();
  62559. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62560. }
  62561. };
  62562. return SoundTrack;
  62563. }());
  62564. BABYLON.SoundTrack = SoundTrack;
  62565. })(BABYLON || (BABYLON = {}));
  62566. //# sourceMappingURL=babylon.soundtrack.js.map
  62567. var BABYLON;
  62568. (function (BABYLON) {
  62569. /**
  62570. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62571. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62572. */
  62573. var Analyser = /** @class */ (function () {
  62574. /**
  62575. * Creates a new analyser
  62576. * @param scene defines hosting scene
  62577. */
  62578. function Analyser(scene) {
  62579. /**
  62580. * Gets or sets the smoothing
  62581. * @ignorenaming
  62582. */
  62583. this.SMOOTHING = 0.75;
  62584. /**
  62585. * Gets or sets the FFT table size
  62586. * @ignorenaming
  62587. */
  62588. this.FFT_SIZE = 512;
  62589. /**
  62590. * Gets or sets the bar graph amplitude
  62591. * @ignorenaming
  62592. */
  62593. this.BARGRAPHAMPLITUDE = 256;
  62594. /**
  62595. * Gets or sets the position of the debug canvas
  62596. * @ignorenaming
  62597. */
  62598. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62599. /**
  62600. * Gets or sets the debug canvas size
  62601. * @ignorenaming
  62602. */
  62603. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62604. this._scene = scene;
  62605. this._audioEngine = BABYLON.Engine.audioEngine;
  62606. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62607. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62608. this._webAudioAnalyser.minDecibels = -140;
  62609. this._webAudioAnalyser.maxDecibels = 0;
  62610. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62611. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62612. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62613. }
  62614. }
  62615. /**
  62616. * Get the number of data values you will have to play with for the visualization
  62617. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62618. * @returns a number
  62619. */
  62620. Analyser.prototype.getFrequencyBinCount = function () {
  62621. if (this._audioEngine.canUseWebAudio) {
  62622. return this._webAudioAnalyser.frequencyBinCount;
  62623. }
  62624. else {
  62625. return 0;
  62626. }
  62627. };
  62628. /**
  62629. * Gets the current frequency data as a byte array
  62630. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62631. * @returns a Uint8Array
  62632. */
  62633. Analyser.prototype.getByteFrequencyData = function () {
  62634. if (this._audioEngine.canUseWebAudio) {
  62635. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62636. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62637. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62638. }
  62639. return this._byteFreqs;
  62640. };
  62641. /**
  62642. * Gets the current waveform as a byte array
  62643. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62644. * @returns a Uint8Array
  62645. */
  62646. Analyser.prototype.getByteTimeDomainData = function () {
  62647. if (this._audioEngine.canUseWebAudio) {
  62648. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62649. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62650. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62651. }
  62652. return this._byteTime;
  62653. };
  62654. /**
  62655. * Gets the current frequency data as a float array
  62656. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62657. * @returns a Float32Array
  62658. */
  62659. Analyser.prototype.getFloatFrequencyData = function () {
  62660. if (this._audioEngine.canUseWebAudio) {
  62661. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62662. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62663. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62664. }
  62665. return this._floatFreqs;
  62666. };
  62667. /**
  62668. * Renders the debug canvas
  62669. */
  62670. Analyser.prototype.drawDebugCanvas = function () {
  62671. var _this = this;
  62672. if (this._audioEngine.canUseWebAudio) {
  62673. if (!this._debugCanvas) {
  62674. this._debugCanvas = document.createElement("canvas");
  62675. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62676. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62677. this._debugCanvas.style.position = "absolute";
  62678. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62679. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62680. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62681. document.body.appendChild(this._debugCanvas);
  62682. this._registerFunc = function () {
  62683. _this.drawDebugCanvas();
  62684. };
  62685. this._scene.registerBeforeRender(this._registerFunc);
  62686. }
  62687. if (this._registerFunc && this._debugCanvasContext) {
  62688. var workingArray = this.getByteFrequencyData();
  62689. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62690. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62691. // Draw the frequency domain chart.
  62692. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62693. var value = workingArray[i];
  62694. var percent = value / this.BARGRAPHAMPLITUDE;
  62695. var height = this.DEBUGCANVASSIZE.height * percent;
  62696. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62697. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62698. var hue = i / this.getFrequencyBinCount() * 360;
  62699. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62700. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62701. }
  62702. }
  62703. }
  62704. };
  62705. /**
  62706. * Stops rendering the debug canvas and removes it
  62707. */
  62708. Analyser.prototype.stopDebugCanvas = function () {
  62709. if (this._debugCanvas) {
  62710. if (this._registerFunc) {
  62711. this._scene.unregisterBeforeRender(this._registerFunc);
  62712. this._registerFunc = null;
  62713. }
  62714. document.body.removeChild(this._debugCanvas);
  62715. this._debugCanvas = null;
  62716. this._debugCanvasContext = null;
  62717. }
  62718. };
  62719. /**
  62720. * Connects two audio nodes
  62721. * @param inputAudioNode defines first node to connect
  62722. * @param outputAudioNode defines second node to connect
  62723. */
  62724. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62725. if (this._audioEngine.canUseWebAudio) {
  62726. inputAudioNode.connect(this._webAudioAnalyser);
  62727. this._webAudioAnalyser.connect(outputAudioNode);
  62728. }
  62729. };
  62730. /**
  62731. * Releases all associated resources
  62732. */
  62733. Analyser.prototype.dispose = function () {
  62734. if (this._audioEngine.canUseWebAudio) {
  62735. this._webAudioAnalyser.disconnect();
  62736. }
  62737. };
  62738. return Analyser;
  62739. }());
  62740. BABYLON.Analyser = Analyser;
  62741. })(BABYLON || (BABYLON = {}));
  62742. //# sourceMappingURL=babylon.analyser.js.map
  62743. var BABYLON;
  62744. (function (BABYLON) {
  62745. var CubeTexture = /** @class */ (function (_super) {
  62746. __extends(CubeTexture, _super);
  62747. /**
  62748. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62749. * as prefiltered data.
  62750. * @param rootUrl defines the url of the texture or the root name of the six images
  62751. * @param scene defines the scene the texture is attached to
  62752. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62753. * @param noMipmap defines if mipmaps should be created or not
  62754. * @param files defines the six files to load for the different faces
  62755. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62756. * @param onError defines a callback triggered in case of error during load
  62757. * @param format defines the internal format to use for the texture once loaded
  62758. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62759. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62760. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62761. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62762. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62763. * @return the cube texture
  62764. */
  62765. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62766. if (extensions === void 0) { extensions = null; }
  62767. if (noMipmap === void 0) { noMipmap = false; }
  62768. if (files === void 0) { files = null; }
  62769. if (onLoad === void 0) { onLoad = null; }
  62770. if (onError === void 0) { onError = null; }
  62771. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62772. if (prefiltered === void 0) { prefiltered = false; }
  62773. if (forcedExtension === void 0) { forcedExtension = null; }
  62774. if (createPolynomials === void 0) { createPolynomials = false; }
  62775. if (lodScale === void 0) { lodScale = 0.8; }
  62776. if (lodOffset === void 0) { lodOffset = 0; }
  62777. var _this = _super.call(this, scene) || this;
  62778. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62779. /**
  62780. * Gets or sets the center of the bounding box associated with the cube texture
  62781. * It must define where the camera used to render the texture was set
  62782. */
  62783. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62784. _this._rotationY = 0;
  62785. /** @hidden */
  62786. _this._prefiltered = false;
  62787. _this.name = rootUrl;
  62788. _this.url = rootUrl;
  62789. _this._noMipmap = noMipmap;
  62790. _this.hasAlpha = false;
  62791. _this._format = format;
  62792. _this.isCube = true;
  62793. _this._textureMatrix = BABYLON.Matrix.Identity();
  62794. _this._createPolynomials = createPolynomials;
  62795. if (!rootUrl && !files) {
  62796. return _this;
  62797. }
  62798. var lastDot = rootUrl.lastIndexOf(".");
  62799. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62800. var isDDS = (extension === ".dds");
  62801. var isEnv = (extension === ".env");
  62802. if (isEnv) {
  62803. _this.gammaSpace = false;
  62804. _this._prefiltered = false;
  62805. }
  62806. else {
  62807. _this._prefiltered = prefiltered;
  62808. if (prefiltered) {
  62809. _this.gammaSpace = false;
  62810. }
  62811. }
  62812. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62813. if (!files) {
  62814. if (!isEnv && !isDDS && !extensions) {
  62815. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62816. }
  62817. files = [];
  62818. if (extensions) {
  62819. for (var index = 0; index < extensions.length; index++) {
  62820. files.push(rootUrl + extensions[index]);
  62821. }
  62822. }
  62823. }
  62824. _this._files = files;
  62825. if (!_this._texture) {
  62826. if (!scene.useDelayedTextureLoading) {
  62827. if (prefiltered) {
  62828. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62829. }
  62830. else {
  62831. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62832. }
  62833. }
  62834. else {
  62835. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62836. }
  62837. }
  62838. else if (onLoad) {
  62839. if (_this._texture.isReady) {
  62840. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62841. }
  62842. else {
  62843. _this._texture.onLoadedObservable.add(onLoad);
  62844. }
  62845. }
  62846. return _this;
  62847. }
  62848. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62849. get: function () {
  62850. return this._boundingBoxSize;
  62851. },
  62852. /**
  62853. * Gets or sets the size of the bounding box associated with the cube texture
  62854. * When defined, the cubemap will switch to local mode
  62855. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62856. * @example https://www.babylonjs-playground.com/#RNASML
  62857. */
  62858. set: function (value) {
  62859. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62860. return;
  62861. }
  62862. this._boundingBoxSize = value;
  62863. var scene = this.getScene();
  62864. if (scene) {
  62865. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62866. }
  62867. },
  62868. enumerable: true,
  62869. configurable: true
  62870. });
  62871. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62872. /**
  62873. * Gets texture matrix rotation angle around Y axis radians.
  62874. */
  62875. get: function () {
  62876. return this._rotationY;
  62877. },
  62878. /**
  62879. * Sets texture matrix rotation angle around Y axis in radians.
  62880. */
  62881. set: function (value) {
  62882. this._rotationY = value;
  62883. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62884. },
  62885. enumerable: true,
  62886. configurable: true
  62887. });
  62888. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62889. var rootUrlKey = "";
  62890. files.forEach(function (url) { return rootUrlKey += url; });
  62891. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62892. };
  62893. /**
  62894. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62895. * @param url defines the url of the prefiltered texture
  62896. * @param scene defines the scene the texture is attached to
  62897. * @param forcedExtension defines the extension of the file if different from the url
  62898. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62899. * @return the prefiltered texture
  62900. */
  62901. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62902. if (forcedExtension === void 0) { forcedExtension = null; }
  62903. if (createPolynomials === void 0) { createPolynomials = true; }
  62904. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62905. };
  62906. // Methods
  62907. CubeTexture.prototype.delayLoad = function () {
  62908. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62909. return;
  62910. }
  62911. var scene = this.getScene();
  62912. if (!scene) {
  62913. return;
  62914. }
  62915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62916. this._texture = this._getFromCache(this.url, this._noMipmap);
  62917. if (!this._texture) {
  62918. if (this._prefiltered) {
  62919. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62920. }
  62921. else {
  62922. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62923. }
  62924. }
  62925. };
  62926. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62927. return this._textureMatrix;
  62928. };
  62929. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62930. this._textureMatrix = value;
  62931. };
  62932. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62933. var texture = BABYLON.SerializationHelper.Parse(function () {
  62934. var prefiltered = false;
  62935. if (parsedTexture.prefiltered) {
  62936. prefiltered = parsedTexture.prefiltered;
  62937. }
  62938. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62939. }, parsedTexture, scene);
  62940. // Local Cubemaps
  62941. if (parsedTexture.boundingBoxPosition) {
  62942. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62943. }
  62944. if (parsedTexture.boundingBoxSize) {
  62945. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62946. }
  62947. // Animations
  62948. if (parsedTexture.animations) {
  62949. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62950. var parsedAnimation = parsedTexture.animations[animationIndex];
  62951. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62952. }
  62953. }
  62954. return texture;
  62955. };
  62956. CubeTexture.prototype.clone = function () {
  62957. var _this = this;
  62958. return BABYLON.SerializationHelper.Clone(function () {
  62959. var scene = _this.getScene();
  62960. if (!scene) {
  62961. return _this;
  62962. }
  62963. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62964. }, this);
  62965. };
  62966. __decorate([
  62967. BABYLON.serialize("rotationY")
  62968. ], CubeTexture.prototype, "_rotationY", void 0);
  62969. return CubeTexture;
  62970. }(BABYLON.BaseTexture));
  62971. BABYLON.CubeTexture = CubeTexture;
  62972. })(BABYLON || (BABYLON = {}));
  62973. //# sourceMappingURL=babylon.cubeTexture.js.map
  62974. var BABYLON;
  62975. (function (BABYLON) {
  62976. var RenderTargetTexture = /** @class */ (function (_super) {
  62977. __extends(RenderTargetTexture, _super);
  62978. /**
  62979. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62980. * or used a shadow, depth texture...
  62981. * @param name The friendly name of the texture
  62982. * @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)
  62983. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62984. * @param generateMipMaps True if mip maps need to be generated after render.
  62985. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62986. * @param type The type of the buffer in the RTT (int, half float, float...)
  62987. * @param isCube True if a cube texture needs to be created
  62988. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62989. * @param generateDepthBuffer True to generate a depth buffer
  62990. * @param generateStencilBuffer True to generate a stencil buffer
  62991. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62992. */
  62993. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62994. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62995. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62996. if (isCube === void 0) { isCube = false; }
  62997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62998. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62999. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63000. if (isMulti === void 0) { isMulti = false; }
  63001. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63002. _this.isCube = isCube;
  63003. /**
  63004. * Use this list to define the list of mesh you want to render.
  63005. */
  63006. _this.renderList = new Array();
  63007. _this.renderParticles = true;
  63008. _this.renderSprites = false;
  63009. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63010. _this.ignoreCameraViewport = false;
  63011. // Events
  63012. /**
  63013. * An event triggered when the texture is unbind.
  63014. */
  63015. _this.onBeforeBindObservable = new BABYLON.Observable();
  63016. /**
  63017. * An event triggered when the texture is unbind.
  63018. */
  63019. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63020. /**
  63021. * An event triggered before rendering the texture
  63022. */
  63023. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63024. /**
  63025. * An event triggered after rendering the texture
  63026. */
  63027. _this.onAfterRenderObservable = new BABYLON.Observable();
  63028. /**
  63029. * An event triggered after the texture clear
  63030. */
  63031. _this.onClearObservable = new BABYLON.Observable();
  63032. _this._currentRefreshId = -1;
  63033. _this._refreshRate = 1;
  63034. _this._samples = 1;
  63035. /**
  63036. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63037. * It must define where the camera used to render the texture is set
  63038. */
  63039. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63040. scene = _this.getScene();
  63041. if (!scene) {
  63042. return _this;
  63043. }
  63044. _this._engine = scene.getEngine();
  63045. _this.name = name;
  63046. _this.isRenderTarget = true;
  63047. _this._initialSizeParameter = size;
  63048. _this._processSizeParameter(size);
  63049. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63050. });
  63051. _this._generateMipMaps = generateMipMaps ? true : false;
  63052. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63053. // Rendering groups
  63054. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63055. if (isMulti) {
  63056. return _this;
  63057. }
  63058. _this._renderTargetOptions = {
  63059. generateMipMaps: generateMipMaps,
  63060. type: type,
  63061. samplingMode: samplingMode,
  63062. generateDepthBuffer: generateDepthBuffer,
  63063. generateStencilBuffer: generateStencilBuffer
  63064. };
  63065. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63066. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63067. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63068. }
  63069. if (isCube) {
  63070. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63071. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63072. _this._textureMatrix = BABYLON.Matrix.Identity();
  63073. }
  63074. else {
  63075. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63076. }
  63077. return _this;
  63078. }
  63079. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63080. get: function () {
  63081. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63082. },
  63083. enumerable: true,
  63084. configurable: true
  63085. });
  63086. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63087. get: function () {
  63088. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63089. },
  63090. enumerable: true,
  63091. configurable: true
  63092. });
  63093. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63094. get: function () {
  63095. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63096. },
  63097. enumerable: true,
  63098. configurable: true
  63099. });
  63100. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63101. set: function (callback) {
  63102. if (this._onAfterUnbindObserver) {
  63103. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63104. }
  63105. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63106. },
  63107. enumerable: true,
  63108. configurable: true
  63109. });
  63110. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63111. set: function (callback) {
  63112. if (this._onBeforeRenderObserver) {
  63113. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63114. }
  63115. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63116. },
  63117. enumerable: true,
  63118. configurable: true
  63119. });
  63120. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63121. set: function (callback) {
  63122. if (this._onAfterRenderObserver) {
  63123. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63124. }
  63125. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63126. },
  63127. enumerable: true,
  63128. configurable: true
  63129. });
  63130. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63131. set: function (callback) {
  63132. if (this._onClearObserver) {
  63133. this.onClearObservable.remove(this._onClearObserver);
  63134. }
  63135. this._onClearObserver = this.onClearObservable.add(callback);
  63136. },
  63137. enumerable: true,
  63138. configurable: true
  63139. });
  63140. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63141. get: function () {
  63142. return this._renderTargetOptions;
  63143. },
  63144. enumerable: true,
  63145. configurable: true
  63146. });
  63147. RenderTargetTexture.prototype._onRatioRescale = function () {
  63148. if (this._sizeRatio) {
  63149. this.resize(this._initialSizeParameter);
  63150. }
  63151. };
  63152. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63153. get: function () {
  63154. return this._boundingBoxSize;
  63155. },
  63156. /**
  63157. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63158. * When defined, the cubemap will switch to local mode
  63159. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63160. * @example https://www.babylonjs-playground.com/#RNASML
  63161. */
  63162. set: function (value) {
  63163. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63164. return;
  63165. }
  63166. this._boundingBoxSize = value;
  63167. var scene = this.getScene();
  63168. if (scene) {
  63169. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63170. }
  63171. },
  63172. enumerable: true,
  63173. configurable: true
  63174. });
  63175. /**
  63176. * Creates a depth stencil texture.
  63177. * This is only available in WebGL 2 or with the depth texture extension available.
  63178. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63179. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63180. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63181. */
  63182. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63183. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63184. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63185. if (generateStencil === void 0) { generateStencil = false; }
  63186. if (!this.getScene()) {
  63187. return;
  63188. }
  63189. var engine = this.getScene().getEngine();
  63190. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63191. bilinearFiltering: bilinearFiltering,
  63192. comparisonFunction: comparisonFunction,
  63193. generateStencil: generateStencil,
  63194. isCube: this.isCube
  63195. });
  63196. engine.setFrameBufferDepthStencilTexture(this);
  63197. };
  63198. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63199. if (size.ratio) {
  63200. this._sizeRatio = size.ratio;
  63201. this._size = {
  63202. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63203. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63204. };
  63205. }
  63206. else {
  63207. this._size = size;
  63208. }
  63209. };
  63210. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63211. get: function () {
  63212. return this._samples;
  63213. },
  63214. set: function (value) {
  63215. if (this._samples === value) {
  63216. return;
  63217. }
  63218. var scene = this.getScene();
  63219. if (!scene) {
  63220. return;
  63221. }
  63222. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63223. },
  63224. enumerable: true,
  63225. configurable: true
  63226. });
  63227. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63228. this._currentRefreshId = -1;
  63229. };
  63230. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63231. get: function () {
  63232. return this._refreshRate;
  63233. },
  63234. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63235. set: function (value) {
  63236. this._refreshRate = value;
  63237. this.resetRefreshCounter();
  63238. },
  63239. enumerable: true,
  63240. configurable: true
  63241. });
  63242. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63243. if (!this._postProcessManager) {
  63244. var scene = this.getScene();
  63245. if (!scene) {
  63246. return;
  63247. }
  63248. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63249. this._postProcesses = new Array();
  63250. }
  63251. this._postProcesses.push(postProcess);
  63252. this._postProcesses[0].autoClear = false;
  63253. };
  63254. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63255. if (!this._postProcesses) {
  63256. return;
  63257. }
  63258. if (dispose) {
  63259. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63260. var postProcess = _a[_i];
  63261. postProcess.dispose();
  63262. }
  63263. }
  63264. this._postProcesses = [];
  63265. };
  63266. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63267. if (!this._postProcesses) {
  63268. return;
  63269. }
  63270. var index = this._postProcesses.indexOf(postProcess);
  63271. if (index === -1) {
  63272. return;
  63273. }
  63274. this._postProcesses.splice(index, 1);
  63275. if (this._postProcesses.length > 0) {
  63276. this._postProcesses[0].autoClear = false;
  63277. }
  63278. };
  63279. RenderTargetTexture.prototype._shouldRender = function () {
  63280. if (this._currentRefreshId === -1) { // At least render once
  63281. this._currentRefreshId = 1;
  63282. return true;
  63283. }
  63284. if (this.refreshRate === this._currentRefreshId) {
  63285. this._currentRefreshId = 1;
  63286. return true;
  63287. }
  63288. this._currentRefreshId++;
  63289. return false;
  63290. };
  63291. RenderTargetTexture.prototype.getRenderSize = function () {
  63292. if (this._size.width) {
  63293. return this._size.width;
  63294. }
  63295. return this._size;
  63296. };
  63297. RenderTargetTexture.prototype.getRenderWidth = function () {
  63298. if (this._size.width) {
  63299. return this._size.width;
  63300. }
  63301. return this._size;
  63302. };
  63303. RenderTargetTexture.prototype.getRenderHeight = function () {
  63304. if (this._size.width) {
  63305. return this._size.height;
  63306. }
  63307. return this._size;
  63308. };
  63309. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63310. get: function () {
  63311. return true;
  63312. },
  63313. enumerable: true,
  63314. configurable: true
  63315. });
  63316. RenderTargetTexture.prototype.scale = function (ratio) {
  63317. var newSize = this.getRenderSize() * ratio;
  63318. this.resize(newSize);
  63319. };
  63320. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63321. if (this.isCube) {
  63322. return this._textureMatrix;
  63323. }
  63324. return _super.prototype.getReflectionTextureMatrix.call(this);
  63325. };
  63326. RenderTargetTexture.prototype.resize = function (size) {
  63327. this.releaseInternalTexture();
  63328. var scene = this.getScene();
  63329. if (!scene) {
  63330. return;
  63331. }
  63332. this._processSizeParameter(size);
  63333. if (this.isCube) {
  63334. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63335. }
  63336. else {
  63337. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63338. }
  63339. };
  63340. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63341. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63342. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63343. var scene = this.getScene();
  63344. if (!scene) {
  63345. return;
  63346. }
  63347. var engine = scene.getEngine();
  63348. if (this.useCameraPostProcesses !== undefined) {
  63349. useCameraPostProcess = this.useCameraPostProcesses;
  63350. }
  63351. if (this._waitingRenderList) {
  63352. this.renderList = [];
  63353. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63354. var id = this._waitingRenderList[index];
  63355. var mesh_1 = scene.getMeshByID(id);
  63356. if (mesh_1) {
  63357. this.renderList.push(mesh_1);
  63358. }
  63359. }
  63360. delete this._waitingRenderList;
  63361. }
  63362. // Is predicate defined?
  63363. if (this.renderListPredicate) {
  63364. if (this.renderList) {
  63365. this.renderList.splice(0); // Clear previous renderList
  63366. }
  63367. else {
  63368. this.renderList = [];
  63369. }
  63370. var scene = this.getScene();
  63371. if (!scene) {
  63372. return;
  63373. }
  63374. var sceneMeshes = scene.meshes;
  63375. for (var index = 0; index < sceneMeshes.length; index++) {
  63376. var mesh = sceneMeshes[index];
  63377. if (this.renderListPredicate(mesh)) {
  63378. this.renderList.push(mesh);
  63379. }
  63380. }
  63381. }
  63382. this.onBeforeBindObservable.notifyObservers(this);
  63383. // Set custom projection.
  63384. // Needs to be before binding to prevent changing the aspect ratio.
  63385. var camera;
  63386. if (this.activeCamera) {
  63387. camera = this.activeCamera;
  63388. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63389. if (this.activeCamera !== scene.activeCamera) {
  63390. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63391. }
  63392. }
  63393. else {
  63394. camera = scene.activeCamera;
  63395. if (camera) {
  63396. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63397. }
  63398. }
  63399. // Prepare renderingManager
  63400. this._renderingManager.reset();
  63401. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63402. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63403. var sceneRenderId = scene.getRenderId();
  63404. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63405. var mesh = currentRenderList[meshIndex];
  63406. if (mesh) {
  63407. if (!mesh.isReady(this.refreshRate === 0)) {
  63408. this.resetRefreshCounter();
  63409. continue;
  63410. }
  63411. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63412. var isMasked = void 0;
  63413. if (!this.renderList && camera) {
  63414. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63415. }
  63416. else {
  63417. isMasked = false;
  63418. }
  63419. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63420. mesh._activate(sceneRenderId);
  63421. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63422. var subMesh = mesh.subMeshes[subIndex];
  63423. scene._activeIndices.addCount(subMesh.indexCount, false);
  63424. this._renderingManager.dispatch(subMesh, mesh);
  63425. }
  63426. }
  63427. }
  63428. }
  63429. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63430. var particleSystem = scene.particleSystems[particleIndex];
  63431. var emitter = particleSystem.emitter;
  63432. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63433. continue;
  63434. }
  63435. if (currentRenderList.indexOf(emitter) >= 0) {
  63436. this._renderingManager.dispatchParticles(particleSystem);
  63437. }
  63438. }
  63439. if (this.isCube) {
  63440. for (var face = 0; face < 6; face++) {
  63441. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63442. scene.incrementRenderId();
  63443. scene.resetCachedMaterial();
  63444. }
  63445. }
  63446. else {
  63447. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63448. }
  63449. this.onAfterUnbindObservable.notifyObservers(this);
  63450. if (scene.activeCamera) {
  63451. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63452. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63453. }
  63454. engine.setViewport(scene.activeCamera.viewport);
  63455. }
  63456. scene.resetCachedMaterial();
  63457. };
  63458. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63459. var minimum = 128;
  63460. var x = renderDimension * scale;
  63461. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63462. // Ensure we don't exceed the render dimension (while staying POT)
  63463. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63464. };
  63465. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63466. var _this = this;
  63467. if (!this._texture) {
  63468. return;
  63469. }
  63470. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63471. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63472. });
  63473. };
  63474. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63475. var scene = this.getScene();
  63476. if (!scene) {
  63477. return;
  63478. }
  63479. var engine = scene.getEngine();
  63480. if (!this._texture) {
  63481. return;
  63482. }
  63483. // Bind
  63484. if (this._postProcessManager) {
  63485. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63486. }
  63487. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63488. if (this._texture) {
  63489. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63490. }
  63491. }
  63492. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63493. // Clear
  63494. if (this.onClearObservable.hasObservers()) {
  63495. this.onClearObservable.notifyObservers(engine);
  63496. }
  63497. else {
  63498. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63499. }
  63500. if (!this._doNotChangeAspectRatio) {
  63501. scene.updateTransformMatrix(true);
  63502. }
  63503. // Render
  63504. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63505. if (this._postProcessManager) {
  63506. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63507. }
  63508. else if (useCameraPostProcess) {
  63509. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63510. }
  63511. if (!this._doNotChangeAspectRatio) {
  63512. scene.updateTransformMatrix(true);
  63513. }
  63514. // Dump ?
  63515. if (dumpForDebug) {
  63516. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63517. }
  63518. // Unbind
  63519. if (!this.isCube || faceIndex === 5) {
  63520. if (this.isCube) {
  63521. if (faceIndex === 5) {
  63522. engine.generateMipMapsForCubemap(this._texture);
  63523. }
  63524. }
  63525. this.unbindFrameBuffer(engine, faceIndex);
  63526. }
  63527. else {
  63528. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63529. }
  63530. };
  63531. /**
  63532. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63533. * This allowed control for front to back rendering or reversly depending of the special needs.
  63534. *
  63535. * @param renderingGroupId The rendering group id corresponding to its index
  63536. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63537. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63538. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63539. */
  63540. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63541. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63542. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63543. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63544. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63545. };
  63546. /**
  63547. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63548. *
  63549. * @param renderingGroupId The rendering group id corresponding to its index
  63550. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63551. */
  63552. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63553. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63554. };
  63555. RenderTargetTexture.prototype.clone = function () {
  63556. var textureSize = this.getSize();
  63557. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63558. // Base texture
  63559. newTexture.hasAlpha = this.hasAlpha;
  63560. newTexture.level = this.level;
  63561. // RenderTarget Texture
  63562. newTexture.coordinatesMode = this.coordinatesMode;
  63563. if (this.renderList) {
  63564. newTexture.renderList = this.renderList.slice(0);
  63565. }
  63566. return newTexture;
  63567. };
  63568. RenderTargetTexture.prototype.serialize = function () {
  63569. if (!this.name) {
  63570. return null;
  63571. }
  63572. var serializationObject = _super.prototype.serialize.call(this);
  63573. serializationObject.renderTargetSize = this.getRenderSize();
  63574. serializationObject.renderList = [];
  63575. if (this.renderList) {
  63576. for (var index = 0; index < this.renderList.length; index++) {
  63577. serializationObject.renderList.push(this.renderList[index].id);
  63578. }
  63579. }
  63580. return serializationObject;
  63581. };
  63582. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63583. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63584. var objBuffer = this.getInternalTexture();
  63585. var scene = this.getScene();
  63586. if (objBuffer && scene) {
  63587. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63588. }
  63589. };
  63590. RenderTargetTexture.prototype.dispose = function () {
  63591. if (this._postProcessManager) {
  63592. this._postProcessManager.dispose();
  63593. this._postProcessManager = null;
  63594. }
  63595. this.clearPostProcesses(true);
  63596. if (this._resizeObserver) {
  63597. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63598. this._resizeObserver = null;
  63599. }
  63600. this.renderList = null;
  63601. // Remove from custom render targets
  63602. var scene = this.getScene();
  63603. if (!scene) {
  63604. return;
  63605. }
  63606. var index = scene.customRenderTargets.indexOf(this);
  63607. if (index >= 0) {
  63608. scene.customRenderTargets.splice(index, 1);
  63609. }
  63610. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63611. var camera = _a[_i];
  63612. index = camera.customRenderTargets.indexOf(this);
  63613. if (index >= 0) {
  63614. camera.customRenderTargets.splice(index, 1);
  63615. }
  63616. }
  63617. _super.prototype.dispose.call(this);
  63618. };
  63619. RenderTargetTexture.prototype._rebuild = function () {
  63620. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63621. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63622. }
  63623. if (this._postProcessManager) {
  63624. this._postProcessManager._rebuild();
  63625. }
  63626. };
  63627. /**
  63628. * Clear the info related to rendering groups preventing retention point in material dispose.
  63629. */
  63630. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63631. if (this._renderingManager) {
  63632. this._renderingManager.freeRenderingGroups();
  63633. }
  63634. };
  63635. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63636. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63637. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63638. return RenderTargetTexture;
  63639. }(BABYLON.Texture));
  63640. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63641. })(BABYLON || (BABYLON = {}));
  63642. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63643. var BABYLON;
  63644. (function (BABYLON) {
  63645. ;
  63646. var MultiRenderTarget = /** @class */ (function (_super) {
  63647. __extends(MultiRenderTarget, _super);
  63648. function MultiRenderTarget(name, size, count, scene, options) {
  63649. var _this = this;
  63650. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63651. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63652. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63653. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63654. _this._engine = scene.getEngine();
  63655. if (!_this.isSupported) {
  63656. _this.dispose();
  63657. return;
  63658. }
  63659. var types = [];
  63660. var samplingModes = [];
  63661. for (var i = 0; i < count; i++) {
  63662. if (options && options.types && options.types[i] !== undefined) {
  63663. types.push(options.types[i]);
  63664. }
  63665. else {
  63666. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63667. }
  63668. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63669. samplingModes.push(options.samplingModes[i]);
  63670. }
  63671. else {
  63672. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63673. }
  63674. }
  63675. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63676. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63677. _this._size = size;
  63678. _this._multiRenderTargetOptions = {
  63679. samplingModes: samplingModes,
  63680. generateMipMaps: generateMipMaps,
  63681. generateDepthBuffer: generateDepthBuffer,
  63682. generateStencilBuffer: generateStencilBuffer,
  63683. generateDepthTexture: generateDepthTexture,
  63684. types: types,
  63685. textureCount: count
  63686. };
  63687. _this._createInternalTextures();
  63688. _this._createTextures();
  63689. return _this;
  63690. }
  63691. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63692. get: function () {
  63693. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63694. },
  63695. enumerable: true,
  63696. configurable: true
  63697. });
  63698. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63699. get: function () {
  63700. return this._textures;
  63701. },
  63702. enumerable: true,
  63703. configurable: true
  63704. });
  63705. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63706. get: function () {
  63707. return this._textures[this._textures.length - 1];
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63713. set: function (wrap) {
  63714. if (this._textures) {
  63715. for (var i = 0; i < this._textures.length; i++) {
  63716. this._textures[i].wrapU = wrap;
  63717. }
  63718. }
  63719. },
  63720. enumerable: true,
  63721. configurable: true
  63722. });
  63723. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63724. set: function (wrap) {
  63725. if (this._textures) {
  63726. for (var i = 0; i < this._textures.length; i++) {
  63727. this._textures[i].wrapV = wrap;
  63728. }
  63729. }
  63730. },
  63731. enumerable: true,
  63732. configurable: true
  63733. });
  63734. MultiRenderTarget.prototype._rebuild = function () {
  63735. this.releaseInternalTextures();
  63736. this._createInternalTextures();
  63737. for (var i = 0; i < this._internalTextures.length; i++) {
  63738. var texture = this._textures[i];
  63739. texture._texture = this._internalTextures[i];
  63740. }
  63741. // Keeps references to frame buffer and stencil/depth buffer
  63742. this._texture = this._internalTextures[0];
  63743. };
  63744. MultiRenderTarget.prototype._createInternalTextures = function () {
  63745. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63746. };
  63747. MultiRenderTarget.prototype._createTextures = function () {
  63748. this._textures = [];
  63749. for (var i = 0; i < this._internalTextures.length; i++) {
  63750. var texture = new BABYLON.Texture(null, this.getScene());
  63751. texture._texture = this._internalTextures[i];
  63752. this._textures.push(texture);
  63753. }
  63754. // Keeps references to frame buffer and stencil/depth buffer
  63755. this._texture = this._internalTextures[0];
  63756. };
  63757. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63758. get: function () {
  63759. return this._samples;
  63760. },
  63761. set: function (value) {
  63762. if (this._samples === value) {
  63763. return;
  63764. }
  63765. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63766. },
  63767. enumerable: true,
  63768. configurable: true
  63769. });
  63770. MultiRenderTarget.prototype.resize = function (size) {
  63771. this.releaseInternalTextures();
  63772. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63773. this._createInternalTextures();
  63774. };
  63775. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63776. var _this = this;
  63777. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63778. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63779. });
  63780. };
  63781. MultiRenderTarget.prototype.dispose = function () {
  63782. this.releaseInternalTextures();
  63783. _super.prototype.dispose.call(this);
  63784. };
  63785. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63786. if (!this._internalTextures) {
  63787. return;
  63788. }
  63789. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63790. if (this._internalTextures[i] !== undefined) {
  63791. this._internalTextures[i].dispose();
  63792. this._internalTextures.splice(i, 1);
  63793. }
  63794. }
  63795. };
  63796. return MultiRenderTarget;
  63797. }(BABYLON.RenderTargetTexture));
  63798. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63799. })(BABYLON || (BABYLON = {}));
  63800. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63801. var BABYLON;
  63802. (function (BABYLON) {
  63803. var MirrorTexture = /** @class */ (function (_super) {
  63804. __extends(MirrorTexture, _super);
  63805. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63806. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63808. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63809. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63810. _this.scene = scene;
  63811. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63812. _this._transformMatrix = BABYLON.Matrix.Zero();
  63813. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63814. _this._adaptiveBlurKernel = 0;
  63815. _this._blurKernelX = 0;
  63816. _this._blurKernelY = 0;
  63817. _this._blurRatio = 1.0;
  63818. _this.ignoreCameraViewport = true;
  63819. _this._updateGammaSpace();
  63820. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63821. _this._updateGammaSpace;
  63822. });
  63823. _this.onBeforeRenderObservable.add(function () {
  63824. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63825. _this._savedViewMatrix = scene.getViewMatrix();
  63826. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63827. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63828. scene.clipPlane = _this.mirrorPlane;
  63829. scene.getEngine().cullBackFaces = false;
  63830. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63831. });
  63832. _this.onAfterRenderObservable.add(function () {
  63833. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63834. scene.getEngine().cullBackFaces = true;
  63835. scene._mirroredCameraPosition = null;
  63836. delete scene.clipPlane;
  63837. });
  63838. return _this;
  63839. }
  63840. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63841. get: function () {
  63842. return this._blurRatio;
  63843. },
  63844. set: function (value) {
  63845. if (this._blurRatio === value) {
  63846. return;
  63847. }
  63848. this._blurRatio = value;
  63849. this._preparePostProcesses();
  63850. },
  63851. enumerable: true,
  63852. configurable: true
  63853. });
  63854. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63855. set: function (value) {
  63856. this._adaptiveBlurKernel = value;
  63857. this._autoComputeBlurKernel();
  63858. },
  63859. enumerable: true,
  63860. configurable: true
  63861. });
  63862. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63863. set: function (value) {
  63864. this.blurKernelX = value;
  63865. this.blurKernelY = value;
  63866. },
  63867. enumerable: true,
  63868. configurable: true
  63869. });
  63870. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63871. get: function () {
  63872. return this._blurKernelX;
  63873. },
  63874. set: function (value) {
  63875. if (this._blurKernelX === value) {
  63876. return;
  63877. }
  63878. this._blurKernelX = value;
  63879. this._preparePostProcesses();
  63880. },
  63881. enumerable: true,
  63882. configurable: true
  63883. });
  63884. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63885. get: function () {
  63886. return this._blurKernelY;
  63887. },
  63888. set: function (value) {
  63889. if (this._blurKernelY === value) {
  63890. return;
  63891. }
  63892. this._blurKernelY = value;
  63893. this._preparePostProcesses();
  63894. },
  63895. enumerable: true,
  63896. configurable: true
  63897. });
  63898. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63899. var engine = this.getScene().getEngine();
  63900. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63901. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63902. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63903. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63904. };
  63905. MirrorTexture.prototype._onRatioRescale = function () {
  63906. if (this._sizeRatio) {
  63907. this.resize(this._initialSizeParameter);
  63908. if (!this._adaptiveBlurKernel) {
  63909. this._preparePostProcesses();
  63910. }
  63911. }
  63912. if (this._adaptiveBlurKernel) {
  63913. this._autoComputeBlurKernel();
  63914. }
  63915. };
  63916. MirrorTexture.prototype._updateGammaSpace = function () {
  63917. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63918. };
  63919. MirrorTexture.prototype._preparePostProcesses = function () {
  63920. this.clearPostProcesses(true);
  63921. if (this._blurKernelX && this._blurKernelY) {
  63922. var engine = this.getScene().getEngine();
  63923. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63924. 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);
  63925. this._blurX.autoClear = false;
  63926. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63927. this._blurX.inputTexture = this._texture;
  63928. }
  63929. else {
  63930. this._blurX.alwaysForcePOT = true;
  63931. }
  63932. 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);
  63933. this._blurY.autoClear = false;
  63934. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63935. this.addPostProcess(this._blurX);
  63936. this.addPostProcess(this._blurY);
  63937. }
  63938. else {
  63939. if (this._blurY) {
  63940. this.removePostProcess(this._blurY);
  63941. this._blurY.dispose();
  63942. this._blurY = null;
  63943. }
  63944. if (this._blurX) {
  63945. this.removePostProcess(this._blurX);
  63946. this._blurX.dispose();
  63947. this._blurX = null;
  63948. }
  63949. }
  63950. };
  63951. MirrorTexture.prototype.clone = function () {
  63952. var scene = this.getScene();
  63953. if (!scene) {
  63954. return this;
  63955. }
  63956. var textureSize = this.getSize();
  63957. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63958. // Base texture
  63959. newTexture.hasAlpha = this.hasAlpha;
  63960. newTexture.level = this.level;
  63961. // Mirror Texture
  63962. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63963. if (this.renderList) {
  63964. newTexture.renderList = this.renderList.slice(0);
  63965. }
  63966. return newTexture;
  63967. };
  63968. MirrorTexture.prototype.serialize = function () {
  63969. if (!this.name) {
  63970. return null;
  63971. }
  63972. var serializationObject = _super.prototype.serialize.call(this);
  63973. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63974. return serializationObject;
  63975. };
  63976. MirrorTexture.prototype.dispose = function () {
  63977. _super.prototype.dispose.call(this);
  63978. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63979. };
  63980. return MirrorTexture;
  63981. }(BABYLON.RenderTargetTexture));
  63982. BABYLON.MirrorTexture = MirrorTexture;
  63983. })(BABYLON || (BABYLON = {}));
  63984. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63985. var BABYLON;
  63986. (function (BABYLON) {
  63987. /**
  63988. * Creates a refraction texture used by refraction channel of the standard material.
  63989. * @param name the texture name
  63990. * @param size size of the underlying texture
  63991. * @param scene root scene
  63992. */
  63993. var RefractionTexture = /** @class */ (function (_super) {
  63994. __extends(RefractionTexture, _super);
  63995. function RefractionTexture(name, size, scene, generateMipMaps) {
  63996. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63997. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63998. _this.depth = 2.0;
  63999. _this.onBeforeRenderObservable.add(function () {
  64000. scene.clipPlane = _this.refractionPlane;
  64001. });
  64002. _this.onAfterRenderObservable.add(function () {
  64003. delete scene.clipPlane;
  64004. });
  64005. return _this;
  64006. }
  64007. RefractionTexture.prototype.clone = function () {
  64008. var scene = this.getScene();
  64009. if (!scene) {
  64010. return this;
  64011. }
  64012. var textureSize = this.getSize();
  64013. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64014. // Base texture
  64015. newTexture.hasAlpha = this.hasAlpha;
  64016. newTexture.level = this.level;
  64017. // Refraction Texture
  64018. newTexture.refractionPlane = this.refractionPlane.clone();
  64019. if (this.renderList) {
  64020. newTexture.renderList = this.renderList.slice(0);
  64021. }
  64022. newTexture.depth = this.depth;
  64023. return newTexture;
  64024. };
  64025. RefractionTexture.prototype.serialize = function () {
  64026. if (!this.name) {
  64027. return null;
  64028. }
  64029. var serializationObject = _super.prototype.serialize.call(this);
  64030. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64031. serializationObject.depth = this.depth;
  64032. return serializationObject;
  64033. };
  64034. return RefractionTexture;
  64035. }(BABYLON.RenderTargetTexture));
  64036. BABYLON.RefractionTexture = RefractionTexture;
  64037. })(BABYLON || (BABYLON = {}));
  64038. //# sourceMappingURL=babylon.refractionTexture.js.map
  64039. var BABYLON;
  64040. (function (BABYLON) {
  64041. /**
  64042. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64043. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64044. */
  64045. var DynamicTexture = /** @class */ (function (_super) {
  64046. __extends(DynamicTexture, _super);
  64047. /**
  64048. * Creates a {BABYLON.DynamicTexture}
  64049. * @param name defines the name of the texture
  64050. * @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
  64051. * @param scene defines the scene where you want the texture
  64052. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64053. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64054. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64055. */
  64056. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64057. if (scene === void 0) { scene = null; }
  64058. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64059. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64060. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64061. _this.name = name;
  64062. _this._engine = _this.getScene().getEngine();
  64063. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64064. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64065. _this._generateMipMaps = generateMipMaps;
  64066. if (options.getContext) {
  64067. _this._canvas = options;
  64068. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64069. }
  64070. else {
  64071. _this._canvas = document.createElement("canvas");
  64072. if (options.width || options.width === 0) {
  64073. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64074. }
  64075. else {
  64076. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64077. }
  64078. }
  64079. var textureSize = _this.getSize();
  64080. _this._canvas.width = textureSize.width;
  64081. _this._canvas.height = textureSize.height;
  64082. _this._context = _this._canvas.getContext("2d");
  64083. return _this;
  64084. }
  64085. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64086. /**
  64087. * Gets the current state of canRescale
  64088. */
  64089. get: function () {
  64090. return true;
  64091. },
  64092. enumerable: true,
  64093. configurable: true
  64094. });
  64095. DynamicTexture.prototype._recreate = function (textureSize) {
  64096. this._canvas.width = textureSize.width;
  64097. this._canvas.height = textureSize.height;
  64098. this.releaseInternalTexture();
  64099. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64100. };
  64101. /**
  64102. * Scales the texture
  64103. * @param ratio the scale factor to apply to both width and height
  64104. */
  64105. DynamicTexture.prototype.scale = function (ratio) {
  64106. var textureSize = this.getSize();
  64107. textureSize.width *= ratio;
  64108. textureSize.height *= ratio;
  64109. this._recreate(textureSize);
  64110. };
  64111. /**
  64112. * Resizes the texture
  64113. * @param width the new width
  64114. * @param height the new height
  64115. */
  64116. DynamicTexture.prototype.scaleTo = function (width, height) {
  64117. var textureSize = this.getSize();
  64118. textureSize.width = width;
  64119. textureSize.height = height;
  64120. this._recreate(textureSize);
  64121. };
  64122. /**
  64123. * Gets the context of the canvas used by the texture
  64124. * @returns the canvas context of the dynamic texture
  64125. */
  64126. DynamicTexture.prototype.getContext = function () {
  64127. return this._context;
  64128. };
  64129. /**
  64130. * Clears the texture
  64131. */
  64132. DynamicTexture.prototype.clear = function () {
  64133. var size = this.getSize();
  64134. this._context.fillRect(0, 0, size.width, size.height);
  64135. };
  64136. /**
  64137. * Updates the texture
  64138. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64139. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64140. */
  64141. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64142. if (premulAlpha === void 0) { premulAlpha = false; }
  64143. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64144. };
  64145. /**
  64146. * Draws text onto the texture
  64147. * @param text defines the text to be drawn
  64148. * @param x defines the placement of the text from the left
  64149. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64150. * @param font defines the font to be used with font-style, font-size, font-name
  64151. * @param color defines the color used for the text
  64152. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64153. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64154. * @param update defines whether texture is immediately update (default is true)
  64155. */
  64156. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64157. if (update === void 0) { update = true; }
  64158. var size = this.getSize();
  64159. if (clearColor) {
  64160. this._context.fillStyle = clearColor;
  64161. this._context.fillRect(0, 0, size.width, size.height);
  64162. }
  64163. this._context.font = font;
  64164. if (x === null || x === undefined) {
  64165. var textSize = this._context.measureText(text);
  64166. x = (size.width - textSize.width) / 2;
  64167. }
  64168. if (y === null || y === undefined) {
  64169. var fontSize = parseInt((font.replace(/\D/g, '')));
  64170. y = (size.height / 2) + (fontSize / 3.65);
  64171. }
  64172. this._context.fillStyle = color;
  64173. this._context.fillText(text, x, y);
  64174. if (update) {
  64175. this.update(invertY);
  64176. }
  64177. };
  64178. /**
  64179. * Clones the texture
  64180. * @returns the clone of the texture.
  64181. */
  64182. DynamicTexture.prototype.clone = function () {
  64183. var scene = this.getScene();
  64184. if (!scene) {
  64185. return this;
  64186. }
  64187. var textureSize = this.getSize();
  64188. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64189. // Base texture
  64190. newTexture.hasAlpha = this.hasAlpha;
  64191. newTexture.level = this.level;
  64192. // Dynamic Texture
  64193. newTexture.wrapU = this.wrapU;
  64194. newTexture.wrapV = this.wrapV;
  64195. return newTexture;
  64196. };
  64197. /** @hidden */
  64198. DynamicTexture.prototype._rebuild = function () {
  64199. this.update();
  64200. };
  64201. return DynamicTexture;
  64202. }(BABYLON.Texture));
  64203. BABYLON.DynamicTexture = DynamicTexture;
  64204. })(BABYLON || (BABYLON = {}));
  64205. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64206. var BABYLON;
  64207. (function (BABYLON) {
  64208. var VideoTexture = /** @class */ (function (_super) {
  64209. __extends(VideoTexture, _super);
  64210. /**
  64211. * Creates a video texture.
  64212. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64213. * @param {string | null} name optional name, will detect from video source, if not defined
  64214. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64215. * @param {BABYLON.Scene} scene is obviously the current scene.
  64216. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64217. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64218. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64219. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64220. */
  64221. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64222. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64223. if (invertY === void 0) { invertY = false; }
  64224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64225. if (settings === void 0) { settings = {
  64226. autoPlay: true,
  64227. loop: true,
  64228. autoUpdateTexture: true,
  64229. }; }
  64230. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64231. _this._onUserActionRequestedObservable = null;
  64232. _this._stillImageCaptured = false;
  64233. _this._createInternalTexture = function () {
  64234. if (_this._texture != null) {
  64235. return;
  64236. }
  64237. if (!_this._engine.needPOTTextures ||
  64238. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64239. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64240. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64241. }
  64242. else {
  64243. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64244. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64245. _this._generateMipMaps = false;
  64246. }
  64247. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64248. if (!_this.video.autoplay) {
  64249. var oldHandler_1 = _this.video.onplaying;
  64250. var error_1 = false;
  64251. _this.video.onplaying = function () {
  64252. _this.video.onplaying = oldHandler_1;
  64253. _this._texture.isReady = true;
  64254. _this._updateInternalTexture();
  64255. if (!error_1) {
  64256. _this.video.pause();
  64257. }
  64258. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64259. _this.onLoadObservable.notifyObservers(_this);
  64260. }
  64261. };
  64262. var playing = _this.video.play();
  64263. if (playing) {
  64264. playing.then(function () {
  64265. // Everything is good.
  64266. })
  64267. .catch(function () {
  64268. error_1 = true;
  64269. // On Chrome for instance, new policies might prevent playing without user interaction.
  64270. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64271. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64272. }
  64273. });
  64274. }
  64275. else {
  64276. _this.video.onplaying = oldHandler_1;
  64277. _this._texture.isReady = true;
  64278. _this._updateInternalTexture();
  64279. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64280. _this.onLoadObservable.notifyObservers(_this);
  64281. }
  64282. }
  64283. }
  64284. else {
  64285. _this._texture.isReady = true;
  64286. _this._updateInternalTexture();
  64287. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64288. _this.onLoadObservable.notifyObservers(_this);
  64289. }
  64290. }
  64291. };
  64292. _this.reset = function () {
  64293. if (_this._texture == null) {
  64294. return;
  64295. }
  64296. _this._texture.dispose();
  64297. _this._texture = null;
  64298. };
  64299. _this._updateInternalTexture = function (e) {
  64300. if (_this._texture == null || !_this._texture.isReady) {
  64301. return;
  64302. }
  64303. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64304. return;
  64305. }
  64306. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64307. };
  64308. _this._engine = _this.getScene().getEngine();
  64309. _this._generateMipMaps = generateMipMaps;
  64310. _this._samplingMode = samplingMode;
  64311. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64312. _this.name = name || _this._getName(src);
  64313. _this.video = _this._getVideo(src);
  64314. if (settings.poster) {
  64315. _this.video.poster = settings.poster;
  64316. }
  64317. if (settings.autoPlay !== undefined) {
  64318. _this.video.autoplay = settings.autoPlay;
  64319. }
  64320. if (settings.loop !== undefined) {
  64321. _this.video.loop = settings.loop;
  64322. }
  64323. _this.video.setAttribute("playsinline", "");
  64324. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64325. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64326. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64327. _this.video.addEventListener("emptied", _this.reset);
  64328. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64329. _this._createInternalTexture();
  64330. }
  64331. return _this;
  64332. }
  64333. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64334. get: function () {
  64335. if (!this._onUserActionRequestedObservable) {
  64336. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64337. }
  64338. return this._onUserActionRequestedObservable;
  64339. },
  64340. enumerable: true,
  64341. configurable: true
  64342. });
  64343. VideoTexture.prototype._getName = function (src) {
  64344. if (src instanceof HTMLVideoElement) {
  64345. return src.currentSrc;
  64346. }
  64347. if (typeof src === "object") {
  64348. return src.toString();
  64349. }
  64350. return src;
  64351. };
  64352. ;
  64353. VideoTexture.prototype._getVideo = function (src) {
  64354. if (src instanceof HTMLVideoElement) {
  64355. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64356. return src;
  64357. }
  64358. var video = document.createElement("video");
  64359. if (typeof src === "string") {
  64360. BABYLON.Tools.SetCorsBehavior(src, video);
  64361. video.src = src;
  64362. }
  64363. else {
  64364. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64365. src.forEach(function (url) {
  64366. var source = document.createElement("source");
  64367. source.src = url;
  64368. video.appendChild(source);
  64369. });
  64370. }
  64371. return video;
  64372. };
  64373. ;
  64374. /**
  64375. * Internal method to initiate `update`.
  64376. */
  64377. VideoTexture.prototype._rebuild = function () {
  64378. this.update();
  64379. };
  64380. /**
  64381. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64382. */
  64383. VideoTexture.prototype.update = function () {
  64384. if (!this.autoUpdateTexture) {
  64385. // Expecting user to call `updateTexture` manually
  64386. return;
  64387. }
  64388. this.updateTexture(true);
  64389. };
  64390. /**
  64391. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64392. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64393. */
  64394. VideoTexture.prototype.updateTexture = function (isVisible) {
  64395. if (!isVisible) {
  64396. return;
  64397. }
  64398. if (this.video.paused && this._stillImageCaptured) {
  64399. return;
  64400. }
  64401. this._stillImageCaptured = true;
  64402. this._updateInternalTexture();
  64403. };
  64404. /**
  64405. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64406. * @param url New url.
  64407. */
  64408. VideoTexture.prototype.updateURL = function (url) {
  64409. this.video.src = url;
  64410. };
  64411. VideoTexture.prototype.dispose = function () {
  64412. _super.prototype.dispose.call(this);
  64413. if (this._onUserActionRequestedObservable) {
  64414. this._onUserActionRequestedObservable.clear();
  64415. this._onUserActionRequestedObservable = null;
  64416. }
  64417. this.video.removeEventListener("canplay", this._createInternalTexture);
  64418. this.video.removeEventListener("paused", this._updateInternalTexture);
  64419. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64420. this.video.removeEventListener("emptied", this.reset);
  64421. this.video.pause();
  64422. };
  64423. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64424. var video = document.createElement("video");
  64425. var constraintsDeviceId;
  64426. if (constraints && constraints.deviceId) {
  64427. constraintsDeviceId = {
  64428. exact: constraints.deviceId,
  64429. };
  64430. }
  64431. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64432. if (navigator.mediaDevices) {
  64433. navigator.mediaDevices.getUserMedia({ video: constraints })
  64434. .then(function (stream) {
  64435. if (video.mozSrcObject !== undefined) {
  64436. // hack for Firefox < 19
  64437. video.mozSrcObject = stream;
  64438. }
  64439. else {
  64440. video.srcObject = stream;
  64441. }
  64442. var onPlaying = function () {
  64443. if (onReady) {
  64444. onReady(new VideoTexture("video", video, scene, true, true));
  64445. }
  64446. video.removeEventListener("playing", onPlaying);
  64447. };
  64448. video.addEventListener("playing", onPlaying);
  64449. video.play();
  64450. })
  64451. .catch(function (err) {
  64452. BABYLON.Tools.Error(err.name);
  64453. });
  64454. }
  64455. else {
  64456. navigator.getUserMedia =
  64457. navigator.getUserMedia ||
  64458. navigator.webkitGetUserMedia ||
  64459. navigator.mozGetUserMedia ||
  64460. navigator.msGetUserMedia;
  64461. if (navigator.getUserMedia) {
  64462. navigator.getUserMedia({
  64463. video: {
  64464. deviceId: constraintsDeviceId,
  64465. width: {
  64466. min: (constraints && constraints.minWidth) || 256,
  64467. max: (constraints && constraints.maxWidth) || 640,
  64468. },
  64469. height: {
  64470. min: (constraints && constraints.minHeight) || 256,
  64471. max: (constraints && constraints.maxHeight) || 480,
  64472. },
  64473. },
  64474. }, function (stream) {
  64475. if (video.mozSrcObject !== undefined) {
  64476. // hack for Firefox < 19
  64477. video.mozSrcObject = stream;
  64478. }
  64479. else {
  64480. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64481. }
  64482. video.play();
  64483. if (onReady) {
  64484. onReady(new VideoTexture("video", video, scene, true, true));
  64485. }
  64486. }, function (e) {
  64487. BABYLON.Tools.Error(e.name);
  64488. });
  64489. }
  64490. }
  64491. };
  64492. return VideoTexture;
  64493. }(BABYLON.Texture));
  64494. BABYLON.VideoTexture = VideoTexture;
  64495. })(BABYLON || (BABYLON = {}));
  64496. //# sourceMappingURL=babylon.videoTexture.js.map
  64497. var BABYLON;
  64498. (function (BABYLON) {
  64499. var RawTexture = /** @class */ (function (_super) {
  64500. __extends(RawTexture, _super);
  64501. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64503. if (invertY === void 0) { invertY = false; }
  64504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64505. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64506. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64507. _this.format = format;
  64508. _this._engine = scene.getEngine();
  64509. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64510. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64511. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64512. return _this;
  64513. }
  64514. RawTexture.prototype.update = function (data) {
  64515. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64516. };
  64517. // Statics
  64518. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64519. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64520. if (invertY === void 0) { invertY = false; }
  64521. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64522. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64523. };
  64524. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64525. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64526. if (invertY === void 0) { invertY = false; }
  64527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64528. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64529. };
  64530. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64531. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64532. if (invertY === void 0) { invertY = false; }
  64533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64534. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64535. };
  64536. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64538. if (invertY === void 0) { invertY = false; }
  64539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64540. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64541. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64542. };
  64543. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64544. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64545. if (invertY === void 0) { invertY = false; }
  64546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64547. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64548. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64549. };
  64550. return RawTexture;
  64551. }(BABYLON.Texture));
  64552. BABYLON.RawTexture = RawTexture;
  64553. })(BABYLON || (BABYLON = {}));
  64554. //# sourceMappingURL=babylon.rawTexture.js.map
  64555. var BABYLON;
  64556. (function (BABYLON) {
  64557. /**
  64558. * Class used to store 3D textures containing user data
  64559. */
  64560. var RawTexture3D = /** @class */ (function (_super) {
  64561. __extends(RawTexture3D, _super);
  64562. /**
  64563. * Create a new RawTexture3D
  64564. * @param data defines the data of the texture
  64565. * @param width defines the width of the texture
  64566. * @param height defines the height of the texture
  64567. * @param depth defines the depth of the texture
  64568. * @param format defines the texture format to use
  64569. * @param scene defines the hosting scene
  64570. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64571. * @param invertY defines if texture must be stored with Y axis inverted
  64572. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64573. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64574. */
  64575. function RawTexture3D(data, width, height, depth,
  64576. /** Gets or sets the texture format to use */
  64577. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64579. if (invertY === void 0) { invertY = false; }
  64580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64582. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64583. _this.format = format;
  64584. _this._engine = scene.getEngine();
  64585. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64586. _this.is3D = true;
  64587. return _this;
  64588. }
  64589. /**
  64590. * Update the texture with new data
  64591. * @param data defines the data to store in the texture
  64592. */
  64593. RawTexture3D.prototype.update = function (data) {
  64594. if (!this._texture) {
  64595. return;
  64596. }
  64597. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64598. };
  64599. return RawTexture3D;
  64600. }(BABYLON.Texture));
  64601. BABYLON.RawTexture3D = RawTexture3D;
  64602. })(BABYLON || (BABYLON = {}));
  64603. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64604. var BABYLON;
  64605. (function (BABYLON) {
  64606. /**
  64607. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64608. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64609. */
  64610. var PostProcessManager = /** @class */ (function () {
  64611. /**
  64612. * Creates a new instance PostProcess
  64613. * @param scene The scene that the post process is associated with.
  64614. */
  64615. function PostProcessManager(scene) {
  64616. this._vertexBuffers = {};
  64617. this._scene = scene;
  64618. }
  64619. PostProcessManager.prototype._prepareBuffers = function () {
  64620. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64621. return;
  64622. }
  64623. // VBO
  64624. var vertices = [];
  64625. vertices.push(1, 1);
  64626. vertices.push(-1, 1);
  64627. vertices.push(-1, -1);
  64628. vertices.push(1, -1);
  64629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64630. this._buildIndexBuffer();
  64631. };
  64632. PostProcessManager.prototype._buildIndexBuffer = function () {
  64633. // Indices
  64634. var indices = [];
  64635. indices.push(0);
  64636. indices.push(1);
  64637. indices.push(2);
  64638. indices.push(0);
  64639. indices.push(2);
  64640. indices.push(3);
  64641. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64642. };
  64643. /**
  64644. * Rebuilds the vertex buffers of the manager.
  64645. */
  64646. PostProcessManager.prototype._rebuild = function () {
  64647. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64648. if (!vb) {
  64649. return;
  64650. }
  64651. vb._rebuild();
  64652. this._buildIndexBuffer();
  64653. };
  64654. // Methods
  64655. /**
  64656. * Prepares a frame to be run through a post process.
  64657. * @param sourceTexture The input texture to the post procesess. (default: null)
  64658. * @param postProcesses An array of post processes to be run. (default: null)
  64659. * @returns True if the post processes were able to be run.
  64660. */
  64661. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64662. if (sourceTexture === void 0) { sourceTexture = null; }
  64663. if (postProcesses === void 0) { postProcesses = null; }
  64664. var camera = this._scene.activeCamera;
  64665. if (!camera) {
  64666. return false;
  64667. }
  64668. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64669. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64670. return false;
  64671. }
  64672. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64673. return true;
  64674. };
  64675. /**
  64676. * Manually render a set of post processes to a texture.
  64677. * @param postProcesses An array of post processes to be run.
  64678. * @param targetTexture The target texture to render to.
  64679. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64680. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64681. * @param lodLevel defines which lod of the texture to render to
  64682. */
  64683. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64684. if (targetTexture === void 0) { targetTexture = null; }
  64685. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64686. if (faceIndex === void 0) { faceIndex = 0; }
  64687. if (lodLevel === void 0) { lodLevel = 0; }
  64688. var engine = this._scene.getEngine();
  64689. for (var index = 0; index < postProcesses.length; index++) {
  64690. if (index < postProcesses.length - 1) {
  64691. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64692. }
  64693. else {
  64694. if (targetTexture) {
  64695. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64696. }
  64697. else {
  64698. engine.restoreDefaultFramebuffer();
  64699. }
  64700. }
  64701. var pp = postProcesses[index];
  64702. var effect = pp.apply();
  64703. if (effect) {
  64704. pp.onBeforeRenderObservable.notifyObservers(effect);
  64705. // VBOs
  64706. this._prepareBuffers();
  64707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64708. // Draw order
  64709. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64710. pp.onAfterRenderObservable.notifyObservers(effect);
  64711. }
  64712. }
  64713. // Restore depth buffer
  64714. engine.setDepthBuffer(true);
  64715. engine.setDepthWrite(true);
  64716. };
  64717. /**
  64718. * Finalize the result of the output of the postprocesses.
  64719. * @param doNotPresent If true the result will not be displayed to the screen.
  64720. * @param targetTexture The target texture to render to.
  64721. * @param faceIndex The index of the face to bind the target texture to.
  64722. * @param postProcesses The array of post processes to render.
  64723. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64724. */
  64725. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64726. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64727. var camera = this._scene.activeCamera;
  64728. if (!camera) {
  64729. return;
  64730. }
  64731. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64732. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64733. return;
  64734. }
  64735. var engine = this._scene.getEngine();
  64736. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64737. var pp = postProcesses[index];
  64738. if (index < len - 1) {
  64739. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64740. }
  64741. else {
  64742. if (targetTexture) {
  64743. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64744. pp._outputTexture = targetTexture;
  64745. }
  64746. else {
  64747. engine.restoreDefaultFramebuffer();
  64748. pp._outputTexture = null;
  64749. }
  64750. }
  64751. if (doNotPresent) {
  64752. break;
  64753. }
  64754. var effect = pp.apply();
  64755. if (effect) {
  64756. pp.onBeforeRenderObservable.notifyObservers(effect);
  64757. // VBOs
  64758. this._prepareBuffers();
  64759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64760. // Draw order
  64761. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64762. pp.onAfterRenderObservable.notifyObservers(effect);
  64763. }
  64764. }
  64765. // Restore states
  64766. engine.setDepthBuffer(true);
  64767. engine.setDepthWrite(true);
  64768. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64769. };
  64770. /**
  64771. * Disposes of the post process manager.
  64772. */
  64773. PostProcessManager.prototype.dispose = function () {
  64774. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64775. if (buffer) {
  64776. buffer.dispose();
  64777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64778. }
  64779. if (this._indexBuffer) {
  64780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64781. this._indexBuffer = null;
  64782. }
  64783. };
  64784. return PostProcessManager;
  64785. }());
  64786. BABYLON.PostProcessManager = PostProcessManager;
  64787. })(BABYLON || (BABYLON = {}));
  64788. //# sourceMappingURL=babylon.postProcessManager.js.map
  64789. var BABYLON;
  64790. (function (BABYLON) {
  64791. /**
  64792. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64793. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64794. */
  64795. var PostProcess = /** @class */ (function () {
  64796. /**
  64797. * Creates a new instance PostProcess
  64798. * @param name The name of the PostProcess.
  64799. * @param fragmentUrl The url of the fragment shader to be used.
  64800. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64801. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64802. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64803. * @param camera The camera to apply the render pass to.
  64804. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64805. * @param engine The engine which the post process will be applied. (default: current engine)
  64806. * @param reusable If the post process can be reused on the same frame. (default: false)
  64807. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64808. * @param textureType Type of textures used when performing the post process. (default: 0)
  64809. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64810. * @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
  64811. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64812. */
  64813. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64814. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64815. if (defines === void 0) { defines = null; }
  64816. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64817. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64818. if (blockCompilation === void 0) { blockCompilation = false; }
  64819. this.name = name;
  64820. /**
  64821. * Width of the texture to apply the post process on
  64822. */
  64823. this.width = -1;
  64824. /**
  64825. * Height of the texture to apply the post process on
  64826. */
  64827. this.height = -1;
  64828. /**
  64829. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64830. */
  64831. this._outputTexture = null;
  64832. /**
  64833. * If the buffer needs to be cleared before applying the post process. (default: true)
  64834. * Should be set to false if shader will overwrite all previous pixels.
  64835. */
  64836. this.autoClear = true;
  64837. /**
  64838. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64839. */
  64840. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64841. /**
  64842. * Animations to be used for the post processing
  64843. */
  64844. this.animations = new Array();
  64845. /**
  64846. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64847. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64848. */
  64849. this.enablePixelPerfectMode = false;
  64850. /**
  64851. * Force the postprocess to be applied without taking in account viewport
  64852. */
  64853. this.forceFullscreenViewport = true;
  64854. /**
  64855. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64856. *
  64857. * | Value | Type | Description |
  64858. * | ----- | ----------------------------------- | ----------- |
  64859. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64860. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64861. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64862. *
  64863. */
  64864. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64865. /**
  64866. * Force textures to be a power of two (default: false)
  64867. */
  64868. this.alwaysForcePOT = false;
  64869. /**
  64870. * Number of sample textures (default: 1)
  64871. */
  64872. this.samples = 1;
  64873. /**
  64874. * Modify the scale of the post process to be the same as the viewport (default: false)
  64875. */
  64876. this.adaptScaleToCurrentViewport = false;
  64877. this._reusable = false;
  64878. /**
  64879. * Smart array of input and output textures for the post process.
  64880. */
  64881. this._textures = new BABYLON.SmartArray(2);
  64882. /**
  64883. * The index in _textures that corresponds to the output texture.
  64884. */
  64885. this._currentRenderTextureInd = 0;
  64886. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64887. this._texelSize = BABYLON.Vector2.Zero();
  64888. // Events
  64889. /**
  64890. * An event triggered when the postprocess is activated.
  64891. */
  64892. this.onActivateObservable = new BABYLON.Observable();
  64893. /**
  64894. * An event triggered when the postprocess changes its size.
  64895. */
  64896. this.onSizeChangedObservable = new BABYLON.Observable();
  64897. /**
  64898. * An event triggered when the postprocess applies its effect.
  64899. */
  64900. this.onApplyObservable = new BABYLON.Observable();
  64901. /**
  64902. * An event triggered before rendering the postprocess
  64903. */
  64904. this.onBeforeRenderObservable = new BABYLON.Observable();
  64905. /**
  64906. * An event triggered after rendering the postprocess
  64907. */
  64908. this.onAfterRenderObservable = new BABYLON.Observable();
  64909. if (camera != null) {
  64910. this._camera = camera;
  64911. this._scene = camera.getScene();
  64912. camera.attachPostProcess(this);
  64913. this._engine = this._scene.getEngine();
  64914. this._scene.postProcesses.push(this);
  64915. }
  64916. else if (engine) {
  64917. this._engine = engine;
  64918. this._engine.postProcesses.push(this);
  64919. }
  64920. this._options = options;
  64921. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64922. this._reusable = reusable || false;
  64923. this._textureType = textureType;
  64924. this._samplers = samplers || [];
  64925. this._samplers.push("textureSampler");
  64926. this._fragmentUrl = fragmentUrl;
  64927. this._vertexUrl = vertexUrl;
  64928. this._parameters = parameters || [];
  64929. this._parameters.push("scale");
  64930. this._indexParameters = indexParameters;
  64931. if (!blockCompilation) {
  64932. this.updateEffect(defines);
  64933. }
  64934. }
  64935. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64936. /**
  64937. * A function that is added to the onActivateObservable
  64938. */
  64939. set: function (callback) {
  64940. if (this._onActivateObserver) {
  64941. this.onActivateObservable.remove(this._onActivateObserver);
  64942. }
  64943. if (callback) {
  64944. this._onActivateObserver = this.onActivateObservable.add(callback);
  64945. }
  64946. },
  64947. enumerable: true,
  64948. configurable: true
  64949. });
  64950. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64951. /**
  64952. * A function that is added to the onSizeChangedObservable
  64953. */
  64954. set: function (callback) {
  64955. if (this._onSizeChangedObserver) {
  64956. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64957. }
  64958. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64959. },
  64960. enumerable: true,
  64961. configurable: true
  64962. });
  64963. Object.defineProperty(PostProcess.prototype, "onApply", {
  64964. /**
  64965. * A function that is added to the onApplyObservable
  64966. */
  64967. set: function (callback) {
  64968. if (this._onApplyObserver) {
  64969. this.onApplyObservable.remove(this._onApplyObserver);
  64970. }
  64971. this._onApplyObserver = this.onApplyObservable.add(callback);
  64972. },
  64973. enumerable: true,
  64974. configurable: true
  64975. });
  64976. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64977. /**
  64978. * A function that is added to the onBeforeRenderObservable
  64979. */
  64980. set: function (callback) {
  64981. if (this._onBeforeRenderObserver) {
  64982. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64983. }
  64984. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64985. },
  64986. enumerable: true,
  64987. configurable: true
  64988. });
  64989. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64990. /**
  64991. * A function that is added to the onAfterRenderObservable
  64992. */
  64993. set: function (callback) {
  64994. if (this._onAfterRenderObserver) {
  64995. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64996. }
  64997. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64998. },
  64999. enumerable: true,
  65000. configurable: true
  65001. });
  65002. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65003. /**
  65004. * 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
  65005. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65006. */
  65007. get: function () {
  65008. return this._textures.data[this._currentRenderTextureInd];
  65009. },
  65010. set: function (value) {
  65011. this._forcedOutputTexture = value;
  65012. },
  65013. enumerable: true,
  65014. configurable: true
  65015. });
  65016. /**
  65017. * Gets the camera which post process is applied to.
  65018. * @returns The camera the post process is applied to.
  65019. */
  65020. PostProcess.prototype.getCamera = function () {
  65021. return this._camera;
  65022. };
  65023. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65024. /**
  65025. * Gets the texel size of the postprocess.
  65026. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65027. */
  65028. get: function () {
  65029. if (this._shareOutputWithPostProcess) {
  65030. return this._shareOutputWithPostProcess.texelSize;
  65031. }
  65032. if (this._forcedOutputTexture) {
  65033. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65034. }
  65035. return this._texelSize;
  65036. },
  65037. enumerable: true,
  65038. configurable: true
  65039. });
  65040. /**
  65041. * Gets the engine which this post process belongs to.
  65042. * @returns The engine the post process was enabled with.
  65043. */
  65044. PostProcess.prototype.getEngine = function () {
  65045. return this._engine;
  65046. };
  65047. /**
  65048. * The effect that is created when initializing the post process.
  65049. * @returns The created effect corrisponding the the postprocess.
  65050. */
  65051. PostProcess.prototype.getEffect = function () {
  65052. return this._effect;
  65053. };
  65054. /**
  65055. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65056. * @param postProcess The post process to share the output with.
  65057. * @returns This post process.
  65058. */
  65059. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65060. this._disposeTextures();
  65061. this._shareOutputWithPostProcess = postProcess;
  65062. return this;
  65063. };
  65064. /**
  65065. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65066. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65067. */
  65068. PostProcess.prototype.useOwnOutput = function () {
  65069. if (this._textures.length == 0) {
  65070. this._textures = new BABYLON.SmartArray(2);
  65071. }
  65072. this._shareOutputWithPostProcess = null;
  65073. };
  65074. /**
  65075. * Updates the effect with the current post process compile time values and recompiles the shader.
  65076. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65077. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65078. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65079. * @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
  65080. * @param onCompiled Called when the shader has been compiled.
  65081. * @param onError Called if there is an error when compiling a shader.
  65082. */
  65083. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65084. if (defines === void 0) { defines = null; }
  65085. if (uniforms === void 0) { uniforms = null; }
  65086. if (samplers === void 0) { samplers = null; }
  65087. 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);
  65088. };
  65089. /**
  65090. * The post process is reusable if it can be used multiple times within one frame.
  65091. * @returns If the post process is reusable
  65092. */
  65093. PostProcess.prototype.isReusable = function () {
  65094. return this._reusable;
  65095. };
  65096. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65097. PostProcess.prototype.markTextureDirty = function () {
  65098. this.width = -1;
  65099. };
  65100. /**
  65101. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65102. * 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.
  65103. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65104. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65105. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65106. * @returns The target texture that was bound to be written to.
  65107. */
  65108. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65109. var _this = this;
  65110. if (sourceTexture === void 0) { sourceTexture = null; }
  65111. camera = camera || this._camera;
  65112. var scene = camera.getScene();
  65113. var engine = scene.getEngine();
  65114. var maxSize = engine.getCaps().maxTextureSize;
  65115. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65116. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65117. // 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
  65118. var webVRCamera = camera.parent;
  65119. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65120. requiredWidth /= 2;
  65121. }
  65122. var desiredWidth = (this._options.width || requiredWidth);
  65123. var desiredHeight = this._options.height || requiredHeight;
  65124. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65125. if (this.adaptScaleToCurrentViewport) {
  65126. var currentViewport = engine.currentViewport;
  65127. if (currentViewport) {
  65128. desiredWidth *= currentViewport.width;
  65129. desiredHeight *= currentViewport.height;
  65130. }
  65131. }
  65132. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65133. if (!this._options.width) {
  65134. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65135. }
  65136. if (!this._options.height) {
  65137. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65138. }
  65139. }
  65140. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65141. if (this._textures.length > 0) {
  65142. for (var i = 0; i < this._textures.length; i++) {
  65143. this._engine._releaseTexture(this._textures.data[i]);
  65144. }
  65145. this._textures.reset();
  65146. }
  65147. this.width = desiredWidth;
  65148. this.height = desiredHeight;
  65149. var textureSize = { width: this.width, height: this.height };
  65150. var textureOptions = {
  65151. generateMipMaps: false,
  65152. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65153. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65154. samplingMode: this.renderTargetSamplingMode,
  65155. type: this._textureType
  65156. };
  65157. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65158. if (this._reusable) {
  65159. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65160. }
  65161. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65162. this.onSizeChangedObservable.notifyObservers(this);
  65163. }
  65164. this._textures.forEach(function (texture) {
  65165. if (texture.samples !== _this.samples) {
  65166. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65167. }
  65168. });
  65169. }
  65170. var target;
  65171. if (this._shareOutputWithPostProcess) {
  65172. target = this._shareOutputWithPostProcess.inputTexture;
  65173. }
  65174. else if (this._forcedOutputTexture) {
  65175. target = this._forcedOutputTexture;
  65176. this.width = this._forcedOutputTexture.width;
  65177. this.height = this._forcedOutputTexture.height;
  65178. }
  65179. else {
  65180. target = this.inputTexture;
  65181. }
  65182. // Bind the input of this post process to be used as the output of the previous post process.
  65183. if (this.enablePixelPerfectMode) {
  65184. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65185. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65186. }
  65187. else {
  65188. this._scaleRatio.copyFromFloats(1, 1);
  65189. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65190. }
  65191. this.onActivateObservable.notifyObservers(camera);
  65192. // Clear
  65193. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65194. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65195. }
  65196. if (this._reusable) {
  65197. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65198. }
  65199. return target;
  65200. };
  65201. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65202. /**
  65203. * If the post process is supported.
  65204. */
  65205. get: function () {
  65206. return this._effect.isSupported;
  65207. },
  65208. enumerable: true,
  65209. configurable: true
  65210. });
  65211. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65212. /**
  65213. * The aspect ratio of the output texture.
  65214. */
  65215. get: function () {
  65216. if (this._shareOutputWithPostProcess) {
  65217. return this._shareOutputWithPostProcess.aspectRatio;
  65218. }
  65219. if (this._forcedOutputTexture) {
  65220. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65221. }
  65222. return this.width / this.height;
  65223. },
  65224. enumerable: true,
  65225. configurable: true
  65226. });
  65227. /**
  65228. * Get a value indicating if the post-process is ready to be used
  65229. * @returns true if the post-process is ready (shader is compiled)
  65230. */
  65231. PostProcess.prototype.isReady = function () {
  65232. return this._effect && this._effect.isReady();
  65233. };
  65234. /**
  65235. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65236. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65237. */
  65238. PostProcess.prototype.apply = function () {
  65239. // Check
  65240. if (!this._effect || !this._effect.isReady())
  65241. return null;
  65242. // States
  65243. this._engine.enableEffect(this._effect);
  65244. this._engine.setState(false);
  65245. this._engine.setDepthBuffer(false);
  65246. this._engine.setDepthWrite(false);
  65247. // Alpha
  65248. this._engine.setAlphaMode(this.alphaMode);
  65249. if (this.alphaConstants) {
  65250. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65251. }
  65252. // Bind the output texture of the preivous post process as the input to this post process.
  65253. var source;
  65254. if (this._shareOutputWithPostProcess) {
  65255. source = this._shareOutputWithPostProcess.inputTexture;
  65256. }
  65257. else if (this._forcedOutputTexture) {
  65258. source = this._forcedOutputTexture;
  65259. }
  65260. else {
  65261. source = this.inputTexture;
  65262. }
  65263. this._effect._bindTexture("textureSampler", source);
  65264. // Parameters
  65265. this._effect.setVector2("scale", this._scaleRatio);
  65266. this.onApplyObservable.notifyObservers(this._effect);
  65267. return this._effect;
  65268. };
  65269. PostProcess.prototype._disposeTextures = function () {
  65270. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65271. return;
  65272. }
  65273. if (this._textures.length > 0) {
  65274. for (var i = 0; i < this._textures.length; i++) {
  65275. this._engine._releaseTexture(this._textures.data[i]);
  65276. }
  65277. }
  65278. this._textures.dispose();
  65279. };
  65280. /**
  65281. * Disposes the post process.
  65282. * @param camera The camera to dispose the post process on.
  65283. */
  65284. PostProcess.prototype.dispose = function (camera) {
  65285. camera = camera || this._camera;
  65286. this._disposeTextures();
  65287. if (this._scene) {
  65288. var index_1 = this._scene.postProcesses.indexOf(this);
  65289. if (index_1 !== -1) {
  65290. this._scene.postProcesses.splice(index_1, 1);
  65291. }
  65292. }
  65293. else {
  65294. var index_2 = this._engine.postProcesses.indexOf(this);
  65295. if (index_2 !== -1) {
  65296. this._engine.postProcesses.splice(index_2, 1);
  65297. }
  65298. }
  65299. if (!camera) {
  65300. return;
  65301. }
  65302. camera.detachPostProcess(this);
  65303. var index = camera._postProcesses.indexOf(this);
  65304. if (index === 0 && camera._postProcesses.length > 0) {
  65305. var firstPostProcess = this._camera._getFirstPostProcess();
  65306. if (firstPostProcess) {
  65307. firstPostProcess.markTextureDirty();
  65308. }
  65309. }
  65310. this.onActivateObservable.clear();
  65311. this.onAfterRenderObservable.clear();
  65312. this.onApplyObservable.clear();
  65313. this.onBeforeRenderObservable.clear();
  65314. this.onSizeChangedObservable.clear();
  65315. };
  65316. return PostProcess;
  65317. }());
  65318. BABYLON.PostProcess = PostProcess;
  65319. })(BABYLON || (BABYLON = {}));
  65320. //# sourceMappingURL=babylon.postProcess.js.map
  65321. var BABYLON;
  65322. (function (BABYLON) {
  65323. var PassPostProcess = /** @class */ (function (_super) {
  65324. __extends(PassPostProcess, _super);
  65325. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65326. if (camera === void 0) { camera = null; }
  65327. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65328. if (blockCompilation === void 0) { blockCompilation = false; }
  65329. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65330. }
  65331. return PassPostProcess;
  65332. }(BABYLON.PostProcess));
  65333. BABYLON.PassPostProcess = PassPostProcess;
  65334. })(BABYLON || (BABYLON = {}));
  65335. //# sourceMappingURL=babylon.passPostProcess.js.map
  65336. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65337. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65338. s = arguments[i];
  65339. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65340. t[p] = s[p];
  65341. }
  65342. return t;
  65343. };
  65344. var BABYLON;
  65345. (function (BABYLON) {
  65346. /**
  65347. * Default implementation IShadowGenerator.
  65348. * This is the main object responsible of generating shadows in the framework.
  65349. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65350. */
  65351. var ShadowGenerator = /** @class */ (function () {
  65352. /**
  65353. * Creates a ShadowGenerator object.
  65354. * A ShadowGenerator is the required tool to use the shadows.
  65355. * Each light casting shadows needs to use its own ShadowGenerator.
  65356. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65357. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65358. * @param light The light object generating the shadows.
  65359. * @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.
  65360. */
  65361. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65362. this._bias = 0.00005;
  65363. this._normalBias = 0;
  65364. this._blurBoxOffset = 1;
  65365. this._blurScale = 2;
  65366. this._blurKernel = 1;
  65367. this._useKernelBlur = false;
  65368. this._filter = ShadowGenerator.FILTER_NONE;
  65369. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65370. this._contactHardeningLightSizeUVRatio = 0.1;
  65371. this._darkness = 0;
  65372. this._transparencyShadow = false;
  65373. /**
  65374. * Controls the extent to which the shadows fade out at the edge of the frustum
  65375. * Used only by directionals and spots
  65376. */
  65377. this.frustumEdgeFalloff = 0;
  65378. /**
  65379. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65380. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65381. * It might on the other hand introduce peter panning.
  65382. */
  65383. this.forceBackFacesOnly = false;
  65384. this._lightDirection = BABYLON.Vector3.Zero();
  65385. this._viewMatrix = BABYLON.Matrix.Zero();
  65386. this._projectionMatrix = BABYLON.Matrix.Zero();
  65387. this._transformMatrix = BABYLON.Matrix.Zero();
  65388. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65389. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65390. this._currentFaceIndex = 0;
  65391. this._currentFaceIndexCache = 0;
  65392. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65393. this._mapSize = mapSize;
  65394. this._light = light;
  65395. this._scene = light.getScene();
  65396. light._shadowGenerator = this;
  65397. // Texture type fallback from float to int if not supported.
  65398. var caps = this._scene.getEngine().getCaps();
  65399. if (!useFullFloatFirst) {
  65400. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65401. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65402. }
  65403. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65404. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65405. }
  65406. else {
  65407. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65408. }
  65409. }
  65410. else {
  65411. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65412. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65413. }
  65414. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65415. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65416. }
  65417. else {
  65418. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65419. }
  65420. }
  65421. this._initializeGenerator();
  65422. this._applyFilterValues();
  65423. }
  65424. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65425. /**
  65426. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65427. */
  65428. get: function () {
  65429. return this._bias;
  65430. },
  65431. /**
  65432. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65433. */
  65434. set: function (bias) {
  65435. this._bias = bias;
  65436. },
  65437. enumerable: true,
  65438. configurable: true
  65439. });
  65440. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65441. /**
  65442. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65443. */
  65444. get: function () {
  65445. return this._normalBias;
  65446. },
  65447. /**
  65448. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65449. */
  65450. set: function (normalBias) {
  65451. this._normalBias = normalBias;
  65452. },
  65453. enumerable: true,
  65454. configurable: true
  65455. });
  65456. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65457. /**
  65458. * Gets the blur box offset: offset applied during the blur pass.
  65459. * Only usefull if useKernelBlur = false
  65460. */
  65461. get: function () {
  65462. return this._blurBoxOffset;
  65463. },
  65464. /**
  65465. * Sets the blur box offset: offset applied during the blur pass.
  65466. * Only usefull if useKernelBlur = false
  65467. */
  65468. set: function (value) {
  65469. if (this._blurBoxOffset === value) {
  65470. return;
  65471. }
  65472. this._blurBoxOffset = value;
  65473. this._disposeBlurPostProcesses();
  65474. },
  65475. enumerable: true,
  65476. configurable: true
  65477. });
  65478. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65479. /**
  65480. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65481. * 2 means half of the size.
  65482. */
  65483. get: function () {
  65484. return this._blurScale;
  65485. },
  65486. /**
  65487. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65488. * 2 means half of the size.
  65489. */
  65490. set: function (value) {
  65491. if (this._blurScale === value) {
  65492. return;
  65493. }
  65494. this._blurScale = value;
  65495. this._disposeBlurPostProcesses();
  65496. },
  65497. enumerable: true,
  65498. configurable: true
  65499. });
  65500. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65501. /**
  65502. * Gets the blur kernel: kernel size of the blur pass.
  65503. * Only usefull if useKernelBlur = true
  65504. */
  65505. get: function () {
  65506. return this._blurKernel;
  65507. },
  65508. /**
  65509. * Sets the blur kernel: kernel size of the blur pass.
  65510. * Only usefull if useKernelBlur = true
  65511. */
  65512. set: function (value) {
  65513. if (this._blurKernel === value) {
  65514. return;
  65515. }
  65516. this._blurKernel = value;
  65517. this._disposeBlurPostProcesses();
  65518. },
  65519. enumerable: true,
  65520. configurable: true
  65521. });
  65522. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65523. /**
  65524. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65525. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65526. */
  65527. get: function () {
  65528. return this._useKernelBlur;
  65529. },
  65530. /**
  65531. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65532. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65533. */
  65534. set: function (value) {
  65535. if (this._useKernelBlur === value) {
  65536. return;
  65537. }
  65538. this._useKernelBlur = value;
  65539. this._disposeBlurPostProcesses();
  65540. },
  65541. enumerable: true,
  65542. configurable: true
  65543. });
  65544. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65545. /**
  65546. * Gets the depth scale used in ESM mode.
  65547. */
  65548. get: function () {
  65549. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65550. },
  65551. /**
  65552. * Sets the depth scale used in ESM mode.
  65553. * This can override the scale stored on the light.
  65554. */
  65555. set: function (value) {
  65556. this._depthScale = value;
  65557. },
  65558. enumerable: true,
  65559. configurable: true
  65560. });
  65561. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65562. /**
  65563. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65564. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65565. */
  65566. get: function () {
  65567. return this._filter;
  65568. },
  65569. /**
  65570. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65571. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65572. */
  65573. set: function (value) {
  65574. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65575. if (this._light.needCube()) {
  65576. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65577. this.useExponentialShadowMap = true;
  65578. return;
  65579. }
  65580. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65581. this.useCloseExponentialShadowMap = true;
  65582. return;
  65583. }
  65584. // PCF on cubemap would also be expensive
  65585. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65586. this.usePoissonSampling = true;
  65587. return;
  65588. }
  65589. }
  65590. // Weblg1 fallback for PCF.
  65591. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65592. if (this._scene.getEngine().webGLVersion === 1) {
  65593. this.usePoissonSampling = true;
  65594. return;
  65595. }
  65596. }
  65597. if (this._filter === value) {
  65598. return;
  65599. }
  65600. this._filter = value;
  65601. this._disposeBlurPostProcesses();
  65602. this._applyFilterValues();
  65603. this._light._markMeshesAsLightDirty();
  65604. },
  65605. enumerable: true,
  65606. configurable: true
  65607. });
  65608. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65609. /**
  65610. * Gets if the current filter is set to Poisson Sampling.
  65611. */
  65612. get: function () {
  65613. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65614. },
  65615. /**
  65616. * Sets the current filter to Poisson Sampling.
  65617. */
  65618. set: function (value) {
  65619. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65620. return;
  65621. }
  65622. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65623. },
  65624. enumerable: true,
  65625. configurable: true
  65626. });
  65627. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65628. /**
  65629. * Gets if the current filter is set to VSM.
  65630. * DEPRECATED. Should use useExponentialShadowMap instead.
  65631. */
  65632. get: function () {
  65633. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65634. return this.useExponentialShadowMap;
  65635. },
  65636. /**
  65637. * Sets the current filter is to VSM.
  65638. * DEPRECATED. Should use useExponentialShadowMap instead.
  65639. */
  65640. set: function (value) {
  65641. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65642. this.useExponentialShadowMap = value;
  65643. },
  65644. enumerable: true,
  65645. configurable: true
  65646. });
  65647. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65648. /**
  65649. * Gets if the current filter is set to blurred VSM.
  65650. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65651. */
  65652. get: function () {
  65653. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65654. return this.useBlurExponentialShadowMap;
  65655. },
  65656. /**
  65657. * Sets the current filter is to blurred VSM.
  65658. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65659. */
  65660. set: function (value) {
  65661. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65662. this.useBlurExponentialShadowMap = value;
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65668. /**
  65669. * Gets if the current filter is set to ESM.
  65670. */
  65671. get: function () {
  65672. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65673. },
  65674. /**
  65675. * Sets the current filter is to ESM.
  65676. */
  65677. set: function (value) {
  65678. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65679. return;
  65680. }
  65681. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65682. },
  65683. enumerable: true,
  65684. configurable: true
  65685. });
  65686. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65687. /**
  65688. * Gets if the current filter is set to filtered ESM.
  65689. */
  65690. get: function () {
  65691. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65692. },
  65693. /**
  65694. * Gets if the current filter is set to filtered ESM.
  65695. */
  65696. set: function (value) {
  65697. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65698. return;
  65699. }
  65700. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65701. },
  65702. enumerable: true,
  65703. configurable: true
  65704. });
  65705. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65706. /**
  65707. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65708. * exponential to prevent steep falloff artifacts).
  65709. */
  65710. get: function () {
  65711. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65712. },
  65713. /**
  65714. * Sets the current filter to "close ESM" (using the inverse of the
  65715. * exponential to prevent steep falloff artifacts).
  65716. */
  65717. set: function (value) {
  65718. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65719. return;
  65720. }
  65721. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65722. },
  65723. enumerable: true,
  65724. configurable: true
  65725. });
  65726. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65727. /**
  65728. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65729. * exponential to prevent steep falloff artifacts).
  65730. */
  65731. get: function () {
  65732. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65733. },
  65734. /**
  65735. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65736. * exponential to prevent steep falloff artifacts).
  65737. */
  65738. set: function (value) {
  65739. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65740. return;
  65741. }
  65742. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65743. },
  65744. enumerable: true,
  65745. configurable: true
  65746. });
  65747. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65748. /**
  65749. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65750. */
  65751. get: function () {
  65752. return this.filter === ShadowGenerator.FILTER_PCF;
  65753. },
  65754. /**
  65755. * Sets the current filter to "PCF" (percentage closer filtering).
  65756. */
  65757. set: function (value) {
  65758. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65759. return;
  65760. }
  65761. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65762. },
  65763. enumerable: true,
  65764. configurable: true
  65765. });
  65766. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65767. /**
  65768. * Gets the PCF or PCSS Quality.
  65769. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65770. */
  65771. get: function () {
  65772. return this._filteringQuality;
  65773. },
  65774. /**
  65775. * Sets the PCF or PCSS Quality.
  65776. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65777. */
  65778. set: function (filteringQuality) {
  65779. this._filteringQuality = filteringQuality;
  65780. },
  65781. enumerable: true,
  65782. configurable: true
  65783. });
  65784. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65785. /**
  65786. * Gets if the current filter is set to "PCSS" (contact hardening).
  65787. */
  65788. get: function () {
  65789. return this.filter === ShadowGenerator.FILTER_PCSS;
  65790. },
  65791. /**
  65792. * Sets the current filter to "PCSS" (contact hardening).
  65793. */
  65794. set: function (value) {
  65795. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65796. return;
  65797. }
  65798. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65799. },
  65800. enumerable: true,
  65801. configurable: true
  65802. });
  65803. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65804. /**
  65805. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65806. * Using a ratio helps keeping shape stability independently of the map size.
  65807. *
  65808. * It does not account for the light projection as it was having too much
  65809. * instability during the light setup or during light position changes.
  65810. *
  65811. * Only valid if useContactHardeningShadow is true.
  65812. */
  65813. get: function () {
  65814. return this._contactHardeningLightSizeUVRatio;
  65815. },
  65816. /**
  65817. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65818. * Using a ratio helps keeping shape stability independently of the map size.
  65819. *
  65820. * It does not account for the light projection as it was having too much
  65821. * instability during the light setup or during light position changes.
  65822. *
  65823. * Only valid if useContactHardeningShadow is true.
  65824. */
  65825. set: function (contactHardeningLightSizeUVRatio) {
  65826. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65827. },
  65828. enumerable: true,
  65829. configurable: true
  65830. });
  65831. /**
  65832. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65833. * 0 means strongest and 1 would means no shadow.
  65834. * @returns the darkness.
  65835. */
  65836. ShadowGenerator.prototype.getDarkness = function () {
  65837. return this._darkness;
  65838. };
  65839. /**
  65840. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65841. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65842. * @returns the shadow generator allowing fluent coding.
  65843. */
  65844. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65845. if (darkness >= 1.0)
  65846. this._darkness = 1.0;
  65847. else if (darkness <= 0.0)
  65848. this._darkness = 0.0;
  65849. else
  65850. this._darkness = darkness;
  65851. return this;
  65852. };
  65853. /**
  65854. * Sets the ability to have transparent shadow (boolean).
  65855. * @param transparent True if transparent else False
  65856. * @returns the shadow generator allowing fluent coding
  65857. */
  65858. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65859. this._transparencyShadow = transparent;
  65860. return this;
  65861. };
  65862. /**
  65863. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65864. * @returns The render target texture if present otherwise, null
  65865. */
  65866. ShadowGenerator.prototype.getShadowMap = function () {
  65867. return this._shadowMap;
  65868. };
  65869. /**
  65870. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65871. * @returns The render target texture if the shadow map is present otherwise, null
  65872. */
  65873. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65874. if (this._shadowMap2) {
  65875. return this._shadowMap2;
  65876. }
  65877. return this._shadowMap;
  65878. };
  65879. /**
  65880. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65881. * @param mesh Mesh to add
  65882. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65883. * @returns the Shadow Generator itself
  65884. */
  65885. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65886. if (includeDescendants === void 0) { includeDescendants = true; }
  65887. if (!this._shadowMap) {
  65888. return this;
  65889. }
  65890. if (!this._shadowMap.renderList) {
  65891. this._shadowMap.renderList = [];
  65892. }
  65893. this._shadowMap.renderList.push(mesh);
  65894. if (includeDescendants) {
  65895. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65896. }
  65897. return this;
  65898. var _a;
  65899. };
  65900. /**
  65901. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65902. * @param mesh Mesh to remove
  65903. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65904. * @returns the Shadow Generator itself
  65905. */
  65906. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65907. if (includeDescendants === void 0) { includeDescendants = true; }
  65908. if (!this._shadowMap || !this._shadowMap.renderList) {
  65909. return this;
  65910. }
  65911. var index = this._shadowMap.renderList.indexOf(mesh);
  65912. if (index !== -1) {
  65913. this._shadowMap.renderList.splice(index, 1);
  65914. }
  65915. if (includeDescendants) {
  65916. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65917. var child = _a[_i];
  65918. this.removeShadowCaster(child);
  65919. }
  65920. }
  65921. return this;
  65922. };
  65923. /**
  65924. * Returns the associated light object.
  65925. * @returns the light generating the shadow
  65926. */
  65927. ShadowGenerator.prototype.getLight = function () {
  65928. return this._light;
  65929. };
  65930. ShadowGenerator.prototype._initializeGenerator = function () {
  65931. this._light._markMeshesAsLightDirty();
  65932. this._initializeShadowMap();
  65933. };
  65934. ShadowGenerator.prototype._initializeShadowMap = function () {
  65935. var _this = this;
  65936. // Render target
  65937. var engine = this._scene.getEngine();
  65938. if (engine.webGLVersion > 1) {
  65939. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65940. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65941. }
  65942. else {
  65943. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65944. }
  65945. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65946. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65947. this._shadowMap.anisotropicFilteringLevel = 1;
  65948. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65949. this._shadowMap.renderParticles = false;
  65950. this._shadowMap.ignoreCameraViewport = true;
  65951. // Record Face Index before render.
  65952. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65953. _this._currentFaceIndex = faceIndex;
  65954. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65955. engine.setColorWrite(false);
  65956. }
  65957. });
  65958. // Custom render function.
  65959. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65960. // Blur if required afer render.
  65961. this._shadowMap.onAfterUnbindObservable.add(function () {
  65962. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65963. engine.setColorWrite(true);
  65964. }
  65965. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65966. return;
  65967. }
  65968. var shadowMap = _this.getShadowMapForRendering();
  65969. if (shadowMap) {
  65970. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65971. }
  65972. });
  65973. // Clear according to the chosen filter.
  65974. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65975. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65976. this._shadowMap.onClearObservable.add(function (engine) {
  65977. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65978. engine.clear(clearOne, false, true, false);
  65979. }
  65980. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65981. engine.clear(clearZero, true, true, false);
  65982. }
  65983. else {
  65984. engine.clear(clearOne, true, true, false);
  65985. }
  65986. });
  65987. };
  65988. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65989. var _this = this;
  65990. var engine = this._scene.getEngine();
  65991. var targetSize = this._mapSize / this.blurScale;
  65992. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65993. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65994. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65995. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65996. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65997. }
  65998. if (this.useKernelBlur) {
  65999. 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);
  66000. this._kernelBlurXPostprocess.width = targetSize;
  66001. this._kernelBlurXPostprocess.height = targetSize;
  66002. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66003. effect.setTexture("textureSampler", _this._shadowMap);
  66004. });
  66005. 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);
  66006. this._kernelBlurXPostprocess.autoClear = false;
  66007. this._kernelBlurYPostprocess.autoClear = false;
  66008. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66009. this._kernelBlurXPostprocess.packedFloat = true;
  66010. this._kernelBlurYPostprocess.packedFloat = true;
  66011. }
  66012. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66013. }
  66014. else {
  66015. 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);
  66016. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66017. effect.setFloat2("screenSize", targetSize, targetSize);
  66018. effect.setTexture("textureSampler", _this._shadowMap);
  66019. });
  66020. this._boxBlurPostprocess.autoClear = false;
  66021. this._blurPostProcesses = [this._boxBlurPostprocess];
  66022. }
  66023. };
  66024. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66025. var index;
  66026. var engine = this._scene.getEngine();
  66027. if (depthOnlySubMeshes.length) {
  66028. engine.setColorWrite(false);
  66029. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66030. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66031. }
  66032. engine.setColorWrite(true);
  66033. }
  66034. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66035. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66036. }
  66037. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66038. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66039. }
  66040. if (this._transparencyShadow) {
  66041. for (index = 0; index < transparentSubMeshes.length; index++) {
  66042. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66043. }
  66044. }
  66045. };
  66046. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66047. var _this = this;
  66048. var mesh = subMesh.getRenderingMesh();
  66049. var scene = this._scene;
  66050. var engine = scene.getEngine();
  66051. var material = subMesh.getMaterial();
  66052. if (!material) {
  66053. return;
  66054. }
  66055. // Culling
  66056. engine.setState(material.backFaceCulling);
  66057. // Managing instances
  66058. var batch = mesh._getInstancesRenderList(subMesh._id);
  66059. if (batch.mustReturn) {
  66060. return;
  66061. }
  66062. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66063. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66064. engine.enableEffect(this._effect);
  66065. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66066. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66067. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66068. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66069. this._effect.setVector3("lightData", this._cachedDirection);
  66070. }
  66071. else {
  66072. this._effect.setVector3("lightData", this._cachedPosition);
  66073. }
  66074. if (scene.activeCamera) {
  66075. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66076. }
  66077. // Alpha test
  66078. if (material && material.needAlphaTesting()) {
  66079. var alphaTexture = material.getAlphaTestTexture();
  66080. if (alphaTexture) {
  66081. this._effect.setTexture("diffuseSampler", alphaTexture);
  66082. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66083. }
  66084. }
  66085. // Bones
  66086. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66087. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66088. }
  66089. // Morph targets
  66090. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66091. if (this.forceBackFacesOnly) {
  66092. engine.setState(true, 0, false, true);
  66093. }
  66094. // Draw
  66095. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66096. if (this.forceBackFacesOnly) {
  66097. engine.setState(true, 0, false, false);
  66098. }
  66099. }
  66100. else {
  66101. // Need to reset refresh rate of the shadowMap
  66102. if (this._shadowMap) {
  66103. this._shadowMap.resetRefreshCounter();
  66104. }
  66105. }
  66106. };
  66107. ShadowGenerator.prototype._applyFilterValues = function () {
  66108. if (!this._shadowMap) {
  66109. return;
  66110. }
  66111. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66112. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66113. }
  66114. else {
  66115. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66116. }
  66117. };
  66118. /**
  66119. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66120. * @param onCompiled Callback triggered at the and of the effects compilation
  66121. * @param options Sets of optional options forcing the compilation with different modes
  66122. */
  66123. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66124. var _this = this;
  66125. var localOptions = __assign({ useInstances: false }, options);
  66126. var shadowMap = this.getShadowMap();
  66127. if (!shadowMap) {
  66128. if (onCompiled) {
  66129. onCompiled(this);
  66130. }
  66131. return;
  66132. }
  66133. var renderList = shadowMap.renderList;
  66134. if (!renderList) {
  66135. if (onCompiled) {
  66136. onCompiled(this);
  66137. }
  66138. return;
  66139. }
  66140. var subMeshes = new Array();
  66141. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66142. var mesh = renderList_1[_i];
  66143. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66144. }
  66145. if (subMeshes.length === 0) {
  66146. if (onCompiled) {
  66147. onCompiled(this);
  66148. }
  66149. return;
  66150. }
  66151. var currentIndex = 0;
  66152. var checkReady = function () {
  66153. if (!_this._scene || !_this._scene.getEngine()) {
  66154. return;
  66155. }
  66156. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66157. currentIndex++;
  66158. if (currentIndex >= subMeshes.length) {
  66159. if (onCompiled) {
  66160. onCompiled(_this);
  66161. }
  66162. return;
  66163. }
  66164. }
  66165. setTimeout(checkReady, 16);
  66166. };
  66167. checkReady();
  66168. };
  66169. /**
  66170. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66171. * @param options Sets of optional options forcing the compilation with different modes
  66172. * @returns A promise that resolves when the compilation completes
  66173. */
  66174. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66175. var _this = this;
  66176. return new Promise(function (resolve) {
  66177. _this.forceCompilation(function () {
  66178. resolve();
  66179. }, options);
  66180. });
  66181. };
  66182. /**
  66183. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66184. * @param subMesh The submesh we want to render in the shadow map
  66185. * @param useInstances Defines wether will draw in the map using instances
  66186. * @returns true if ready otherwise, false
  66187. */
  66188. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66189. var defines = [];
  66190. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66191. defines.push("#define FLOAT");
  66192. }
  66193. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66194. defines.push("#define ESM");
  66195. }
  66196. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66197. defines.push("#define DEPTHTEXTURE");
  66198. }
  66199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66200. var mesh = subMesh.getMesh();
  66201. var material = subMesh.getMaterial();
  66202. // Normal bias.
  66203. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66204. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66205. defines.push("#define NORMAL");
  66206. if (mesh.nonUniformScaling) {
  66207. defines.push("#define NONUNIFORMSCALING");
  66208. }
  66209. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66210. defines.push("#define DIRECTIONINLIGHTDATA");
  66211. }
  66212. }
  66213. // Alpha test
  66214. if (material && material.needAlphaTesting()) {
  66215. var alphaTexture = material.getAlphaTestTexture();
  66216. if (alphaTexture) {
  66217. defines.push("#define ALPHATEST");
  66218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66219. attribs.push(BABYLON.VertexBuffer.UVKind);
  66220. defines.push("#define UV1");
  66221. }
  66222. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66223. if (alphaTexture.coordinatesIndex === 1) {
  66224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66225. defines.push("#define UV2");
  66226. }
  66227. }
  66228. }
  66229. }
  66230. // Bones
  66231. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66232. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66233. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66234. if (mesh.numBoneInfluencers > 4) {
  66235. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66236. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66237. }
  66238. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66239. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66240. }
  66241. else {
  66242. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66243. }
  66244. // Morph targets
  66245. var manager = mesh.morphTargetManager;
  66246. var morphInfluencers = 0;
  66247. if (manager) {
  66248. if (manager.numInfluencers > 0) {
  66249. defines.push("#define MORPHTARGETS");
  66250. morphInfluencers = manager.numInfluencers;
  66251. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66252. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66253. }
  66254. }
  66255. // Instances
  66256. if (useInstances) {
  66257. defines.push("#define INSTANCES");
  66258. attribs.push("world0");
  66259. attribs.push("world1");
  66260. attribs.push("world2");
  66261. attribs.push("world3");
  66262. }
  66263. // Get correct effect
  66264. var join = defines.join("\n");
  66265. if (this._cachedDefines !== join) {
  66266. this._cachedDefines = join;
  66267. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66268. }
  66269. if (!this._effect.isReady()) {
  66270. return false;
  66271. }
  66272. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66273. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66274. this._initializeBlurRTTAndPostProcesses();
  66275. }
  66276. }
  66277. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66278. return false;
  66279. }
  66280. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66281. return false;
  66282. }
  66283. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66284. return false;
  66285. }
  66286. return true;
  66287. };
  66288. /**
  66289. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66290. * @param defines Defines of the material we want to update
  66291. * @param lightIndex Index of the light in the enabled light list of the material
  66292. */
  66293. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66294. var scene = this._scene;
  66295. var light = this._light;
  66296. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66297. return;
  66298. }
  66299. defines["SHADOW" + lightIndex] = true;
  66300. if (this.useContactHardeningShadow) {
  66301. defines["SHADOWPCSS" + lightIndex] = true;
  66302. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66303. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66304. }
  66305. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66306. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66307. }
  66308. // else default to high.
  66309. }
  66310. if (this.usePercentageCloserFiltering) {
  66311. defines["SHADOWPCF" + lightIndex] = true;
  66312. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66313. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66314. }
  66315. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66316. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66317. }
  66318. // else default to high.
  66319. }
  66320. else if (this.usePoissonSampling) {
  66321. defines["SHADOWPOISSON" + lightIndex] = true;
  66322. }
  66323. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66324. defines["SHADOWESM" + lightIndex] = true;
  66325. }
  66326. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66327. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66328. }
  66329. if (light.needCube()) {
  66330. defines["SHADOWCUBE" + lightIndex] = true;
  66331. }
  66332. };
  66333. /**
  66334. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66335. * defined in the generator but impacting the effect).
  66336. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66337. * @param effect The effect we are binfing the information for
  66338. */
  66339. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66340. var light = this._light;
  66341. var scene = this._scene;
  66342. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66343. return;
  66344. }
  66345. var camera = scene.activeCamera;
  66346. if (!camera) {
  66347. return;
  66348. }
  66349. var shadowMap = this.getShadowMap();
  66350. if (!shadowMap) {
  66351. return;
  66352. }
  66353. if (!light.needCube()) {
  66354. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66355. }
  66356. // Only PCF uses depth stencil texture.
  66357. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66358. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66359. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66360. }
  66361. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66362. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66363. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66364. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66365. }
  66366. else {
  66367. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66368. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66369. }
  66370. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66371. };
  66372. /**
  66373. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66374. * (eq to shadow prjection matrix * light transform matrix)
  66375. * @returns The transform matrix used to create the shadow map
  66376. */
  66377. ShadowGenerator.prototype.getTransformMatrix = function () {
  66378. var scene = this._scene;
  66379. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66380. return this._transformMatrix;
  66381. }
  66382. this._currentRenderID = scene.getRenderId();
  66383. this._currentFaceIndexCache = this._currentFaceIndex;
  66384. var lightPosition = this._light.position;
  66385. if (this._light.computeTransformedInformation()) {
  66386. lightPosition = this._light.transformedPosition;
  66387. }
  66388. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66389. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66390. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66391. }
  66392. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66393. this._cachedPosition.copyFrom(lightPosition);
  66394. this._cachedDirection.copyFrom(this._lightDirection);
  66395. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66396. var shadowMap = this.getShadowMap();
  66397. if (shadowMap) {
  66398. var renderList = shadowMap.renderList;
  66399. if (renderList) {
  66400. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66401. }
  66402. }
  66403. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66404. }
  66405. return this._transformMatrix;
  66406. };
  66407. /**
  66408. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66409. * Cube and 2D textures for instance.
  66410. */
  66411. ShadowGenerator.prototype.recreateShadowMap = function () {
  66412. var shadowMap = this._shadowMap;
  66413. if (!shadowMap) {
  66414. return;
  66415. }
  66416. // Track render list.
  66417. var renderList = shadowMap.renderList;
  66418. // Clean up existing data.
  66419. this._disposeRTTandPostProcesses();
  66420. // Reinitializes.
  66421. this._initializeGenerator();
  66422. // Reaffect the filter to ensure a correct fallback if necessary.
  66423. this.filter = this.filter;
  66424. // Reaffect the filter.
  66425. this._applyFilterValues();
  66426. // Reaffect Render List.
  66427. this._shadowMap.renderList = renderList;
  66428. };
  66429. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66430. if (this._shadowMap2) {
  66431. this._shadowMap2.dispose();
  66432. this._shadowMap2 = null;
  66433. }
  66434. if (this._boxBlurPostprocess) {
  66435. this._boxBlurPostprocess.dispose();
  66436. this._boxBlurPostprocess = null;
  66437. }
  66438. if (this._kernelBlurXPostprocess) {
  66439. this._kernelBlurXPostprocess.dispose();
  66440. this._kernelBlurXPostprocess = null;
  66441. }
  66442. if (this._kernelBlurYPostprocess) {
  66443. this._kernelBlurYPostprocess.dispose();
  66444. this._kernelBlurYPostprocess = null;
  66445. }
  66446. this._blurPostProcesses = [];
  66447. };
  66448. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66449. if (this._shadowMap) {
  66450. this._shadowMap.dispose();
  66451. this._shadowMap = null;
  66452. }
  66453. this._disposeBlurPostProcesses();
  66454. };
  66455. /**
  66456. * Disposes the ShadowGenerator.
  66457. * Returns nothing.
  66458. */
  66459. ShadowGenerator.prototype.dispose = function () {
  66460. this._disposeRTTandPostProcesses();
  66461. if (this._light) {
  66462. this._light._shadowGenerator = null;
  66463. this._light._markMeshesAsLightDirty();
  66464. }
  66465. };
  66466. /**
  66467. * Serializes the shadow generator setup to a json object.
  66468. * @returns The serialized JSON object
  66469. */
  66470. ShadowGenerator.prototype.serialize = function () {
  66471. var serializationObject = {};
  66472. var shadowMap = this.getShadowMap();
  66473. if (!shadowMap) {
  66474. return serializationObject;
  66475. }
  66476. serializationObject.lightId = this._light.id;
  66477. serializationObject.mapSize = shadowMap.getRenderSize();
  66478. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66479. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66480. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66481. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66482. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66483. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66484. serializationObject.depthScale = this.depthScale;
  66485. serializationObject.darkness = this.getDarkness();
  66486. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66487. serializationObject.blurKernel = this.blurKernel;
  66488. serializationObject.blurScale = this.blurScale;
  66489. serializationObject.useKernelBlur = this.useKernelBlur;
  66490. serializationObject.transparencyShadow = this._transparencyShadow;
  66491. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66492. serializationObject.bias = this.bias;
  66493. serializationObject.normalBias = this.normalBias;
  66494. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66495. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66496. serializationObject.filteringQuality = this.filteringQuality;
  66497. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66498. serializationObject.renderList = [];
  66499. if (shadowMap.renderList) {
  66500. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66501. var mesh = shadowMap.renderList[meshIndex];
  66502. serializationObject.renderList.push(mesh.id);
  66503. }
  66504. }
  66505. return serializationObject;
  66506. };
  66507. /**
  66508. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66509. * @param parsedShadowGenerator The JSON object to parse
  66510. * @param scene The scene to create the shadow map for
  66511. * @returns The parsed shadow generator
  66512. */
  66513. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66514. //casting to point light, as light is missing the position attr and typescript complains.
  66515. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66516. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66517. var shadowMap = shadowGenerator.getShadowMap();
  66518. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66519. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66520. meshes.forEach(function (mesh) {
  66521. if (!shadowMap) {
  66522. return;
  66523. }
  66524. if (!shadowMap.renderList) {
  66525. shadowMap.renderList = [];
  66526. }
  66527. shadowMap.renderList.push(mesh);
  66528. });
  66529. }
  66530. if (parsedShadowGenerator.usePoissonSampling) {
  66531. shadowGenerator.usePoissonSampling = true;
  66532. }
  66533. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66534. shadowGenerator.useExponentialShadowMap = true;
  66535. }
  66536. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66537. shadowGenerator.useBlurExponentialShadowMap = true;
  66538. }
  66539. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66540. shadowGenerator.useCloseExponentialShadowMap = true;
  66541. }
  66542. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66543. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66544. }
  66545. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66546. shadowGenerator.usePercentageCloserFiltering = true;
  66547. }
  66548. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66549. shadowGenerator.useContactHardeningShadow = true;
  66550. }
  66551. if (parsedShadowGenerator.filteringQuality) {
  66552. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66553. }
  66554. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66555. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66556. }
  66557. // Backward compat
  66558. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66559. shadowGenerator.useExponentialShadowMap = true;
  66560. }
  66561. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66562. shadowGenerator.useBlurExponentialShadowMap = true;
  66563. }
  66564. if (parsedShadowGenerator.depthScale) {
  66565. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66566. }
  66567. if (parsedShadowGenerator.blurScale) {
  66568. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66569. }
  66570. if (parsedShadowGenerator.blurBoxOffset) {
  66571. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66572. }
  66573. if (parsedShadowGenerator.useKernelBlur) {
  66574. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66575. }
  66576. if (parsedShadowGenerator.blurKernel) {
  66577. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66578. }
  66579. if (parsedShadowGenerator.bias !== undefined) {
  66580. shadowGenerator.bias = parsedShadowGenerator.bias;
  66581. }
  66582. if (parsedShadowGenerator.normalBias !== undefined) {
  66583. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66584. }
  66585. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66586. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66587. }
  66588. if (parsedShadowGenerator.darkness) {
  66589. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66590. }
  66591. if (parsedShadowGenerator.transparencyShadow) {
  66592. shadowGenerator.setTransparencyShadow(true);
  66593. }
  66594. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66595. return shadowGenerator;
  66596. };
  66597. /**
  66598. * Shadow generator mode None: no filtering applied.
  66599. */
  66600. ShadowGenerator.FILTER_NONE = 0;
  66601. /**
  66602. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66603. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66604. */
  66605. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66606. /**
  66607. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66608. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66609. */
  66610. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66611. /**
  66612. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66613. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66614. */
  66615. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66616. /**
  66617. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66618. * edge artifacts on steep falloff.
  66619. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66620. */
  66621. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66622. /**
  66623. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66624. * edge artifacts on steep falloff.
  66625. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66626. */
  66627. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66628. /**
  66629. * Shadow generator mode PCF: Percentage Closer Filtering
  66630. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66631. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66632. */
  66633. ShadowGenerator.FILTER_PCF = 6;
  66634. /**
  66635. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66636. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66637. * Contact Hardening
  66638. */
  66639. ShadowGenerator.FILTER_PCSS = 7;
  66640. /**
  66641. * Reserved for PCF and PCSS
  66642. * Highest Quality.
  66643. *
  66644. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66645. *
  66646. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66647. */
  66648. ShadowGenerator.QUALITY_HIGH = 0;
  66649. /**
  66650. * Reserved for PCF and PCSS
  66651. * Good tradeoff for quality/perf cross devices
  66652. *
  66653. * Execute PCF on a 3*3 kernel.
  66654. *
  66655. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66656. */
  66657. ShadowGenerator.QUALITY_MEDIUM = 1;
  66658. /**
  66659. * Reserved for PCF and PCSS
  66660. * The lowest quality but the fastest.
  66661. *
  66662. * Execute PCF on a 1*1 kernel.
  66663. *
  66664. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66665. */
  66666. ShadowGenerator.QUALITY_LOW = 2;
  66667. return ShadowGenerator;
  66668. }());
  66669. BABYLON.ShadowGenerator = ShadowGenerator;
  66670. })(BABYLON || (BABYLON = {}));
  66671. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66672. var BABYLON;
  66673. (function (BABYLON) {
  66674. var DefaultLoadingScreen = /** @class */ (function () {
  66675. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66676. if (_loadingText === void 0) { _loadingText = ""; }
  66677. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66678. var _this = this;
  66679. this._renderingCanvas = _renderingCanvas;
  66680. this._loadingText = _loadingText;
  66681. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66682. // Resize
  66683. this._resizeLoadingUI = function () {
  66684. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66685. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66686. if (!_this._loadingDiv) {
  66687. return;
  66688. }
  66689. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66690. _this._loadingDiv.style.left = canvasRect.left + "px";
  66691. _this._loadingDiv.style.top = canvasRect.top + "px";
  66692. _this._loadingDiv.style.width = canvasRect.width + "px";
  66693. _this._loadingDiv.style.height = canvasRect.height + "px";
  66694. };
  66695. }
  66696. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66697. if (this._loadingDiv) {
  66698. // Do not add a loading screen if there is already one
  66699. return;
  66700. }
  66701. this._loadingDiv = document.createElement("div");
  66702. this._loadingDiv.id = "babylonjsLoadingDiv";
  66703. this._loadingDiv.style.opacity = "0";
  66704. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66705. this._loadingDiv.style.pointerEvents = "none";
  66706. // Loading text
  66707. this._loadingTextDiv = document.createElement("div");
  66708. this._loadingTextDiv.style.position = "absolute";
  66709. this._loadingTextDiv.style.left = "0";
  66710. this._loadingTextDiv.style.top = "50%";
  66711. this._loadingTextDiv.style.marginTop = "80px";
  66712. this._loadingTextDiv.style.width = "100%";
  66713. this._loadingTextDiv.style.height = "20px";
  66714. this._loadingTextDiv.style.fontFamily = "Arial";
  66715. this._loadingTextDiv.style.fontSize = "14px";
  66716. this._loadingTextDiv.style.color = "white";
  66717. this._loadingTextDiv.style.textAlign = "center";
  66718. this._loadingTextDiv.innerHTML = "Loading";
  66719. this._loadingDiv.appendChild(this._loadingTextDiv);
  66720. //set the predefined text
  66721. this._loadingTextDiv.innerHTML = this._loadingText;
  66722. // Generating keyframes
  66723. var style = document.createElement('style');
  66724. style.type = 'text/css';
  66725. 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 }";
  66726. style.innerHTML = keyFrames;
  66727. document.getElementsByTagName('head')[0].appendChild(style);
  66728. // Loading img
  66729. var imgBack = new Image();
  66730. 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++foHnXkW4mLC1JUl947333tsMY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GBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  66731. imgBack.style.position = "absolute";
  66732. imgBack.style.left = "50%";
  66733. imgBack.style.top = "50%";
  66734. imgBack.style.marginLeft = "-60px";
  66735. imgBack.style.marginTop = "-60px";
  66736. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66737. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66738. imgBack.style.transformOrigin = "50% 50%";
  66739. imgBack.style.webkitTransformOrigin = "50% 50%";
  66740. this._loadingDiv.appendChild(imgBack);
  66741. this._resizeLoadingUI();
  66742. window.addEventListener("resize", this._resizeLoadingUI);
  66743. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66744. document.body.appendChild(this._loadingDiv);
  66745. this._loadingDiv.style.opacity = "1";
  66746. };
  66747. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66748. var _this = this;
  66749. if (!this._loadingDiv) {
  66750. return;
  66751. }
  66752. var onTransitionEnd = function () {
  66753. if (!_this._loadingDiv) {
  66754. return;
  66755. }
  66756. document.body.removeChild(_this._loadingDiv);
  66757. window.removeEventListener("resize", _this._resizeLoadingUI);
  66758. _this._loadingDiv = null;
  66759. };
  66760. this._loadingDiv.style.opacity = "0";
  66761. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66762. };
  66763. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66764. set: function (text) {
  66765. this._loadingText = text;
  66766. if (this._loadingTextDiv) {
  66767. this._loadingTextDiv.innerHTML = this._loadingText;
  66768. }
  66769. },
  66770. enumerable: true,
  66771. configurable: true
  66772. });
  66773. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66774. get: function () {
  66775. return this._loadingDivBackgroundColor;
  66776. },
  66777. set: function (color) {
  66778. this._loadingDivBackgroundColor = color;
  66779. if (!this._loadingDiv) {
  66780. return;
  66781. }
  66782. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66783. },
  66784. enumerable: true,
  66785. configurable: true
  66786. });
  66787. return DefaultLoadingScreen;
  66788. }());
  66789. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66790. })(BABYLON || (BABYLON = {}));
  66791. //# sourceMappingURL=babylon.loadingScreen.js.map
  66792. var BABYLON;
  66793. (function (BABYLON) {
  66794. var SceneLoaderProgressEvent = /** @class */ (function () {
  66795. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66796. this.lengthComputable = lengthComputable;
  66797. this.loaded = loaded;
  66798. this.total = total;
  66799. }
  66800. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66801. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66802. };
  66803. return SceneLoaderProgressEvent;
  66804. }());
  66805. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66806. var SceneLoader = /** @class */ (function () {
  66807. function SceneLoader() {
  66808. }
  66809. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66810. get: function () {
  66811. return 0;
  66812. },
  66813. enumerable: true,
  66814. configurable: true
  66815. });
  66816. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66817. get: function () {
  66818. return 1;
  66819. },
  66820. enumerable: true,
  66821. configurable: true
  66822. });
  66823. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66824. get: function () {
  66825. return 2;
  66826. },
  66827. enumerable: true,
  66828. configurable: true
  66829. });
  66830. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66831. get: function () {
  66832. return 3;
  66833. },
  66834. enumerable: true,
  66835. configurable: true
  66836. });
  66837. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66838. get: function () {
  66839. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66840. },
  66841. set: function (value) {
  66842. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66843. },
  66844. enumerable: true,
  66845. configurable: true
  66846. });
  66847. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66848. get: function () {
  66849. return SceneLoader._ShowLoadingScreen;
  66850. },
  66851. set: function (value) {
  66852. SceneLoader._ShowLoadingScreen = value;
  66853. },
  66854. enumerable: true,
  66855. configurable: true
  66856. });
  66857. Object.defineProperty(SceneLoader, "loggingLevel", {
  66858. get: function () {
  66859. return SceneLoader._loggingLevel;
  66860. },
  66861. set: function (value) {
  66862. SceneLoader._loggingLevel = value;
  66863. },
  66864. enumerable: true,
  66865. configurable: true
  66866. });
  66867. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66868. get: function () {
  66869. return SceneLoader._CleanBoneMatrixWeights;
  66870. },
  66871. set: function (value) {
  66872. SceneLoader._CleanBoneMatrixWeights = value;
  66873. },
  66874. enumerable: true,
  66875. configurable: true
  66876. });
  66877. SceneLoader._getDefaultPlugin = function () {
  66878. return SceneLoader._registeredPlugins[".babylon"];
  66879. };
  66880. SceneLoader._getPluginForExtension = function (extension) {
  66881. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66882. if (registeredPlugin) {
  66883. return registeredPlugin;
  66884. }
  66885. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  66886. return SceneLoader._getDefaultPlugin();
  66887. };
  66888. SceneLoader._getPluginForDirectLoad = function (data) {
  66889. for (var extension in SceneLoader._registeredPlugins) {
  66890. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66891. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66892. return SceneLoader._registeredPlugins[extension];
  66893. }
  66894. }
  66895. return SceneLoader._getDefaultPlugin();
  66896. };
  66897. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66898. if (sceneFilename.name) {
  66899. sceneFilename = sceneFilename.name;
  66900. }
  66901. var queryStringPosition = sceneFilename.indexOf("?");
  66902. if (queryStringPosition !== -1) {
  66903. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66904. }
  66905. var dotPosition = sceneFilename.lastIndexOf(".");
  66906. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66907. return SceneLoader._getPluginForExtension(extension);
  66908. };
  66909. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66910. SceneLoader._getDirectLoad = function (sceneFilename) {
  66911. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66912. return sceneFilename.substr(5);
  66913. }
  66914. return null;
  66915. };
  66916. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66917. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66918. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66919. var plugin;
  66920. if (registeredPlugin.plugin.createPlugin) {
  66921. plugin = registeredPlugin.plugin.createPlugin();
  66922. }
  66923. else {
  66924. plugin = registeredPlugin.plugin;
  66925. }
  66926. var useArrayBuffer = registeredPlugin.isBinary;
  66927. var database;
  66928. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66929. var dataCallback = function (data, responseURL) {
  66930. if (scene.isDisposed) {
  66931. onError("Scene has been disposed");
  66932. return;
  66933. }
  66934. scene.database = database;
  66935. onSuccess(plugin, data, responseURL);
  66936. };
  66937. var request = null;
  66938. var pluginDisposed = false;
  66939. var onDisposeObservable = plugin.onDisposeObservable;
  66940. if (onDisposeObservable) {
  66941. onDisposeObservable.add(function () {
  66942. pluginDisposed = true;
  66943. if (request) {
  66944. request.abort();
  66945. request = null;
  66946. }
  66947. onDispose();
  66948. });
  66949. }
  66950. var manifestChecked = function () {
  66951. if (pluginDisposed) {
  66952. return;
  66953. }
  66954. var url = rootUrl + sceneFilename;
  66955. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66956. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66957. } : undefined, database, useArrayBuffer, function (request, exception) {
  66958. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66959. });
  66960. };
  66961. if (directLoad) {
  66962. dataCallback(directLoad);
  66963. return plugin;
  66964. }
  66965. if (rootUrl.indexOf("file:") === -1) {
  66966. var engine = scene.getEngine();
  66967. var canUseOfflineSupport = engine.enableOfflineSupport;
  66968. if (canUseOfflineSupport) {
  66969. // Also check for exceptions
  66970. var exceptionFound = false;
  66971. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66972. var regex = _a[_i];
  66973. if (regex.test(rootUrl + sceneFilename)) {
  66974. exceptionFound = true;
  66975. break;
  66976. }
  66977. }
  66978. canUseOfflineSupport = !exceptionFound;
  66979. }
  66980. if (canUseOfflineSupport) {
  66981. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66982. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66983. }
  66984. else {
  66985. manifestChecked();
  66986. }
  66987. }
  66988. // Loading file from disk via input file or drag'n'drop
  66989. else {
  66990. var fileOrString = sceneFilename;
  66991. if (fileOrString.name) { // File
  66992. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66993. }
  66994. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66995. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66996. }
  66997. else {
  66998. onError("Unable to find file named " + sceneFilename);
  66999. }
  67000. }
  67001. return plugin;
  67002. };
  67003. // Public functions
  67004. SceneLoader.GetPluginForExtension = function (extension) {
  67005. return SceneLoader._getPluginForExtension(extension).plugin;
  67006. };
  67007. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67008. return !!SceneLoader._registeredPlugins[extension];
  67009. };
  67010. SceneLoader.RegisterPlugin = function (plugin) {
  67011. if (typeof plugin.extensions === "string") {
  67012. var extension = plugin.extensions;
  67013. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67014. plugin: plugin,
  67015. isBinary: false
  67016. };
  67017. }
  67018. else {
  67019. var extensions = plugin.extensions;
  67020. Object.keys(extensions).forEach(function (extension) {
  67021. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67022. plugin: plugin,
  67023. isBinary: extensions[extension].isBinary
  67024. };
  67025. });
  67026. }
  67027. };
  67028. /**
  67029. * Import meshes into a scene
  67030. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67031. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67032. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67033. * @param scene the instance of BABYLON.Scene to append to
  67034. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67035. * @param onProgress a callback with a progress event for each file being loaded
  67036. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67037. * @param pluginExtension the extension used to determine the plugin
  67038. * @returns The loaded plugin
  67039. */
  67040. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67041. if (sceneFilename === void 0) { sceneFilename = ""; }
  67042. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67043. if (onSuccess === void 0) { onSuccess = null; }
  67044. if (onProgress === void 0) { onProgress = null; }
  67045. if (onError === void 0) { onError = null; }
  67046. if (pluginExtension === void 0) { pluginExtension = null; }
  67047. if (!scene) {
  67048. BABYLON.Tools.Error("No scene available to import mesh to");
  67049. return null;
  67050. }
  67051. if (!sceneFilename) {
  67052. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67053. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67054. }
  67055. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67056. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67057. return null;
  67058. }
  67059. var loadingToken = {};
  67060. scene._addPendingData(loadingToken);
  67061. var disposeHandler = function () {
  67062. scene._removePendingData(loadingToken);
  67063. };
  67064. var errorHandler = function (message, exception) {
  67065. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67066. if (onError) {
  67067. onError(scene, errorMessage, exception);
  67068. }
  67069. else {
  67070. BABYLON.Tools.Error(errorMessage);
  67071. // should the exception be thrown?
  67072. }
  67073. disposeHandler();
  67074. };
  67075. var progressHandler = onProgress ? function (event) {
  67076. try {
  67077. onProgress(event);
  67078. }
  67079. catch (e) {
  67080. errorHandler("Error in onProgress callback", e);
  67081. }
  67082. } : undefined;
  67083. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67084. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67085. if (onSuccess) {
  67086. try {
  67087. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67088. }
  67089. catch (e) {
  67090. errorHandler("Error in onSuccess callback", e);
  67091. }
  67092. }
  67093. scene._removePendingData(loadingToken);
  67094. };
  67095. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67096. if (plugin.rewriteRootURL) {
  67097. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67098. }
  67099. if (sceneFilename === "") {
  67100. if (sceneFilename === "") {
  67101. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67102. }
  67103. }
  67104. if (plugin.importMesh) {
  67105. var syncedPlugin = plugin;
  67106. var meshes = new Array();
  67107. var particleSystems = new Array();
  67108. var skeletons = new Array();
  67109. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67110. return;
  67111. }
  67112. scene.loadingPluginName = plugin.name;
  67113. successHandler(meshes, particleSystems, skeletons, []);
  67114. }
  67115. else {
  67116. var asyncedPlugin = plugin;
  67117. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67118. scene.loadingPluginName = plugin.name;
  67119. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67120. }).catch(function (error) {
  67121. errorHandler(error.message, error);
  67122. });
  67123. }
  67124. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67125. };
  67126. /**
  67127. * Import meshes into a scene
  67128. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67129. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67130. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67131. * @param scene the instance of BABYLON.Scene to append to
  67132. * @param onProgress a callback with a progress event for each file being loaded
  67133. * @param pluginExtension the extension used to determine the plugin
  67134. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67135. */
  67136. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67137. if (sceneFilename === void 0) { sceneFilename = ""; }
  67138. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67139. if (onProgress === void 0) { onProgress = null; }
  67140. if (pluginExtension === void 0) { pluginExtension = null; }
  67141. return new Promise(function (resolve, reject) {
  67142. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67143. resolve({
  67144. meshes: meshes,
  67145. particleSystems: particleSystems,
  67146. skeletons: skeletons,
  67147. animationGroups: animationGroups
  67148. });
  67149. }, onProgress, function (scene, message, exception) {
  67150. reject(exception || new Error(message));
  67151. }, pluginExtension);
  67152. });
  67153. };
  67154. /**
  67155. * Load a scene
  67156. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67157. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67158. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67159. * @param onSuccess a callback with the scene when import succeeds
  67160. * @param onProgress a callback with a progress event for each file being loaded
  67161. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67162. * @param pluginExtension the extension used to determine the plugin
  67163. * @returns The loaded plugin
  67164. */
  67165. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67166. if (onSuccess === void 0) { onSuccess = null; }
  67167. if (onProgress === void 0) { onProgress = null; }
  67168. if (onError === void 0) { onError = null; }
  67169. if (pluginExtension === void 0) { pluginExtension = null; }
  67170. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67171. };
  67172. /**
  67173. * Load a scene
  67174. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67175. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67176. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67177. * @param onProgress a callback with a progress event for each file being loaded
  67178. * @param pluginExtension the extension used to determine the plugin
  67179. * @returns The loaded scene
  67180. */
  67181. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67182. if (onProgress === void 0) { onProgress = null; }
  67183. if (pluginExtension === void 0) { pluginExtension = null; }
  67184. return new Promise(function (resolve, reject) {
  67185. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67186. resolve(scene);
  67187. }, onProgress, function (scene, message, exception) {
  67188. reject(exception || new Error(message));
  67189. }, pluginExtension);
  67190. });
  67191. };
  67192. /**
  67193. * Append a scene
  67194. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67195. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67196. * @param scene is the instance of BABYLON.Scene to append to
  67197. * @param onSuccess a callback with the scene when import succeeds
  67198. * @param onProgress a callback with a progress event for each file being loaded
  67199. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67200. * @param pluginExtension the extension used to determine the plugin
  67201. * @returns The loaded plugin
  67202. */
  67203. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67204. if (sceneFilename === void 0) { sceneFilename = ""; }
  67205. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67206. if (onSuccess === void 0) { onSuccess = null; }
  67207. if (onProgress === void 0) { onProgress = null; }
  67208. if (onError === void 0) { onError = null; }
  67209. if (pluginExtension === void 0) { pluginExtension = null; }
  67210. if (!scene) {
  67211. BABYLON.Tools.Error("No scene available to append to");
  67212. return null;
  67213. }
  67214. if (!sceneFilename) {
  67215. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67216. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67217. }
  67218. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67219. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67220. return null;
  67221. }
  67222. if (SceneLoader.ShowLoadingScreen) {
  67223. scene.getEngine().displayLoadingUI();
  67224. }
  67225. var loadingToken = {};
  67226. scene._addPendingData(loadingToken);
  67227. var disposeHandler = function () {
  67228. scene._removePendingData(loadingToken);
  67229. scene.getEngine().hideLoadingUI();
  67230. };
  67231. var errorHandler = function (message, exception) {
  67232. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67233. if (onError) {
  67234. onError(scene, errorMessage, exception);
  67235. }
  67236. else {
  67237. BABYLON.Tools.Error(errorMessage);
  67238. // should the exception be thrown?
  67239. }
  67240. disposeHandler();
  67241. };
  67242. var progressHandler = onProgress ? function (event) {
  67243. try {
  67244. onProgress(event);
  67245. }
  67246. catch (e) {
  67247. errorHandler("Error in onProgress callback", e);
  67248. }
  67249. } : undefined;
  67250. var successHandler = function () {
  67251. if (onSuccess) {
  67252. try {
  67253. onSuccess(scene);
  67254. }
  67255. catch (e) {
  67256. errorHandler("Error in onSuccess callback", e);
  67257. }
  67258. }
  67259. scene._removePendingData(loadingToken);
  67260. };
  67261. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67262. if (sceneFilename === "") {
  67263. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67264. }
  67265. if (plugin.load) {
  67266. var syncedPlugin = plugin;
  67267. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67268. return;
  67269. }
  67270. scene.loadingPluginName = plugin.name;
  67271. successHandler();
  67272. }
  67273. else {
  67274. var asyncedPlugin = plugin;
  67275. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67276. scene.loadingPluginName = plugin.name;
  67277. successHandler();
  67278. }).catch(function (error) {
  67279. errorHandler(error.message, error);
  67280. });
  67281. }
  67282. if (SceneLoader.ShowLoadingScreen) {
  67283. scene.executeWhenReady(function () {
  67284. scene.getEngine().hideLoadingUI();
  67285. });
  67286. }
  67287. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67288. };
  67289. /**
  67290. * Append a scene
  67291. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67292. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67293. * @param scene is the instance of BABYLON.Scene to append to
  67294. * @param onProgress a callback with a progress event for each file being loaded
  67295. * @param pluginExtension the extension used to determine the plugin
  67296. * @returns The given scene
  67297. */
  67298. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67299. if (sceneFilename === void 0) { sceneFilename = ""; }
  67300. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67301. if (onProgress === void 0) { onProgress = null; }
  67302. if (pluginExtension === void 0) { pluginExtension = null; }
  67303. return new Promise(function (resolve, reject) {
  67304. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67305. resolve(scene);
  67306. }, onProgress, function (scene, message, exception) {
  67307. reject(exception || new Error(message));
  67308. }, pluginExtension);
  67309. });
  67310. };
  67311. /**
  67312. * Load a scene into an asset container
  67313. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67314. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67315. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67316. * @param onSuccess a callback with the scene when import succeeds
  67317. * @param onProgress a callback with a progress event for each file being loaded
  67318. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67319. * @param pluginExtension the extension used to determine the plugin
  67320. * @returns The loaded plugin
  67321. */
  67322. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67323. if (sceneFilename === void 0) { sceneFilename = ""; }
  67324. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67325. if (onSuccess === void 0) { onSuccess = null; }
  67326. if (onProgress === void 0) { onProgress = null; }
  67327. if (onError === void 0) { onError = null; }
  67328. if (pluginExtension === void 0) { pluginExtension = null; }
  67329. if (!scene) {
  67330. BABYLON.Tools.Error("No scene available to load asset container to");
  67331. return null;
  67332. }
  67333. if (!sceneFilename) {
  67334. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67335. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67336. }
  67337. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67338. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67339. return null;
  67340. }
  67341. var loadingToken = {};
  67342. scene._addPendingData(loadingToken);
  67343. var disposeHandler = function () {
  67344. scene._removePendingData(loadingToken);
  67345. };
  67346. var errorHandler = function (message, exception) {
  67347. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67348. if (onError) {
  67349. onError(scene, errorMessage, exception);
  67350. }
  67351. else {
  67352. BABYLON.Tools.Error(errorMessage);
  67353. // should the exception be thrown?
  67354. }
  67355. disposeHandler();
  67356. };
  67357. var progressHandler = onProgress ? function (event) {
  67358. try {
  67359. onProgress(event);
  67360. }
  67361. catch (e) {
  67362. errorHandler("Error in onProgress callback", e);
  67363. }
  67364. } : undefined;
  67365. var successHandler = function (assets) {
  67366. if (onSuccess) {
  67367. try {
  67368. onSuccess(assets);
  67369. }
  67370. catch (e) {
  67371. errorHandler("Error in onSuccess callback", e);
  67372. }
  67373. }
  67374. scene._removePendingData(loadingToken);
  67375. };
  67376. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67377. if (plugin.loadAssetContainer) {
  67378. var syncedPlugin = plugin;
  67379. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67380. if (!assetContainer) {
  67381. return;
  67382. }
  67383. scene.loadingPluginName = plugin.name;
  67384. successHandler(assetContainer);
  67385. }
  67386. else if (plugin.loadAssetContainerAsync) {
  67387. var asyncedPlugin = plugin;
  67388. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67389. scene.loadingPluginName = plugin.name;
  67390. successHandler(assetContainer);
  67391. }).catch(function (error) {
  67392. errorHandler(error.message, error);
  67393. });
  67394. }
  67395. else {
  67396. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67397. }
  67398. if (SceneLoader.ShowLoadingScreen) {
  67399. scene.executeWhenReady(function () {
  67400. scene.getEngine().hideLoadingUI();
  67401. });
  67402. }
  67403. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67404. };
  67405. /**
  67406. * Load a scene into an asset container
  67407. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67408. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67409. * @param scene is the instance of BABYLON.Scene to append to
  67410. * @param onProgress a callback with a progress event for each file being loaded
  67411. * @param pluginExtension the extension used to determine the plugin
  67412. * @returns The loaded asset container
  67413. */
  67414. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67415. if (sceneFilename === void 0) { sceneFilename = ""; }
  67416. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67417. if (onProgress === void 0) { onProgress = null; }
  67418. if (pluginExtension === void 0) { pluginExtension = null; }
  67419. return new Promise(function (resolve, reject) {
  67420. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67421. resolve(assetContainer);
  67422. }, onProgress, function (scene, message, exception) {
  67423. reject(exception || new Error(message));
  67424. }, pluginExtension);
  67425. });
  67426. };
  67427. // Flags
  67428. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67429. SceneLoader._ShowLoadingScreen = true;
  67430. SceneLoader._CleanBoneMatrixWeights = false;
  67431. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67432. // Members
  67433. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67434. SceneLoader._registeredPlugins = {};
  67435. return SceneLoader;
  67436. }());
  67437. BABYLON.SceneLoader = SceneLoader;
  67438. ;
  67439. })(BABYLON || (BABYLON = {}));
  67440. //# sourceMappingURL=babylon.sceneLoader.js.map
  67441. var BABYLON;
  67442. (function (BABYLON) {
  67443. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67444. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67445. var parsedMaterial = parsedData.materials[index];
  67446. if (parsedMaterial.id === id) {
  67447. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67448. }
  67449. }
  67450. return null;
  67451. };
  67452. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67453. for (var i in names) {
  67454. if (mesh.name === names[i]) {
  67455. hierarchyIds.push(mesh.id);
  67456. return true;
  67457. }
  67458. }
  67459. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67460. hierarchyIds.push(mesh.id);
  67461. return true;
  67462. }
  67463. return false;
  67464. };
  67465. var logOperation = function (operation, producer) {
  67466. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67467. };
  67468. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67469. if (addToScene === void 0) { addToScene = false; }
  67470. var container = new BABYLON.AssetContainer(scene);
  67471. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67472. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67473. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67474. // and avoid problems with multiple concurrent .babylon loads.
  67475. var log = "importScene has failed JSON parse";
  67476. try {
  67477. var parsedData = JSON.parse(data);
  67478. log = "";
  67479. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67480. var index;
  67481. var cache;
  67482. // Lights
  67483. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67484. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67485. var parsedLight = parsedData.lights[index];
  67486. var light = BABYLON.Light.Parse(parsedLight, scene);
  67487. if (light) {
  67488. container.lights.push(light);
  67489. log += (index === 0 ? "\n\tLights:" : "");
  67490. log += "\n\t\t" + light.toString(fullDetails);
  67491. }
  67492. }
  67493. }
  67494. // Animations
  67495. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67496. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67497. var parsedAnimation = parsedData.animations[index];
  67498. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67499. scene.animations.push(animation);
  67500. container.animations.push(animation);
  67501. log += (index === 0 ? "\n\tAnimations:" : "");
  67502. log += "\n\t\t" + animation.toString(fullDetails);
  67503. }
  67504. }
  67505. // Materials
  67506. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67507. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67508. var parsedMaterial = parsedData.materials[index];
  67509. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67510. container.materials.push(mat);
  67511. log += (index === 0 ? "\n\tMaterials:" : "");
  67512. log += "\n\t\t" + mat.toString(fullDetails);
  67513. }
  67514. }
  67515. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67516. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67517. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67518. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67519. container.multiMaterials.push(mmat);
  67520. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67521. log += "\n\t\t" + mmat.toString(fullDetails);
  67522. }
  67523. }
  67524. // Morph targets
  67525. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67526. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67527. var managerData = _a[_i];
  67528. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67529. }
  67530. }
  67531. // Skeletons
  67532. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67533. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67534. var parsedSkeleton = parsedData.skeletons[index];
  67535. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67536. container.skeletons.push(skeleton);
  67537. log += (index === 0 ? "\n\tSkeletons:" : "");
  67538. log += "\n\t\t" + skeleton.toString(fullDetails);
  67539. }
  67540. }
  67541. // Geometries
  67542. var geometries = parsedData.geometries;
  67543. if (geometries !== undefined && geometries !== null) {
  67544. var addedGeometry = new Array();
  67545. // Boxes
  67546. var boxes = geometries.boxes;
  67547. if (boxes !== undefined && boxes !== null) {
  67548. for (index = 0, cache = boxes.length; index < cache; index++) {
  67549. var parsedBox = boxes[index];
  67550. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67551. }
  67552. }
  67553. // Spheres
  67554. var spheres = geometries.spheres;
  67555. if (spheres !== undefined && spheres !== null) {
  67556. for (index = 0, cache = spheres.length; index < cache; index++) {
  67557. var parsedSphere = spheres[index];
  67558. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67559. }
  67560. }
  67561. // Cylinders
  67562. var cylinders = geometries.cylinders;
  67563. if (cylinders !== undefined && cylinders !== null) {
  67564. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67565. var parsedCylinder = cylinders[index];
  67566. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67567. }
  67568. }
  67569. // Toruses
  67570. var toruses = geometries.toruses;
  67571. if (toruses !== undefined && toruses !== null) {
  67572. for (index = 0, cache = toruses.length; index < cache; index++) {
  67573. var parsedTorus = toruses[index];
  67574. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67575. }
  67576. }
  67577. // Grounds
  67578. var grounds = geometries.grounds;
  67579. if (grounds !== undefined && grounds !== null) {
  67580. for (index = 0, cache = grounds.length; index < cache; index++) {
  67581. var parsedGround = grounds[index];
  67582. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67583. }
  67584. }
  67585. // Planes
  67586. var planes = geometries.planes;
  67587. if (planes !== undefined && planes !== null) {
  67588. for (index = 0, cache = planes.length; index < cache; index++) {
  67589. var parsedPlane = planes[index];
  67590. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67591. }
  67592. }
  67593. // TorusKnots
  67594. var torusKnots = geometries.torusKnots;
  67595. if (torusKnots !== undefined && torusKnots !== null) {
  67596. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67597. var parsedTorusKnot = torusKnots[index];
  67598. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67599. }
  67600. }
  67601. // VertexData
  67602. var vertexData = geometries.vertexData;
  67603. if (vertexData !== undefined && vertexData !== null) {
  67604. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67605. var parsedVertexData = vertexData[index];
  67606. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67607. }
  67608. }
  67609. addedGeometry.forEach(function (g) {
  67610. if (g) {
  67611. container.geometries.push(g);
  67612. }
  67613. });
  67614. }
  67615. // Transform nodes
  67616. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67617. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67618. var parsedTransformNode = parsedData.transformNodes[index];
  67619. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67620. container.transformNodes.push(node);
  67621. }
  67622. }
  67623. // Meshes
  67624. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67625. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67626. var parsedMesh = parsedData.meshes[index];
  67627. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67628. container.meshes.push(mesh);
  67629. log += (index === 0 ? "\n\tMeshes:" : "");
  67630. log += "\n\t\t" + mesh.toString(fullDetails);
  67631. }
  67632. }
  67633. // Cameras
  67634. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67635. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67636. var parsedCamera = parsedData.cameras[index];
  67637. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67638. container.cameras.push(camera);
  67639. log += (index === 0 ? "\n\tCameras:" : "");
  67640. log += "\n\t\t" + camera.toString(fullDetails);
  67641. }
  67642. }
  67643. // Browsing all the graph to connect the dots
  67644. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67645. var camera = scene.cameras[index];
  67646. if (camera._waitingParentId) {
  67647. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67648. camera._waitingParentId = null;
  67649. }
  67650. }
  67651. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67652. var light_1 = scene.lights[index];
  67653. if (light_1 && light_1._waitingParentId) {
  67654. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67655. light_1._waitingParentId = null;
  67656. }
  67657. }
  67658. // Sounds
  67659. // TODO: add sound
  67660. var loadedSounds = [];
  67661. var loadedSound;
  67662. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67663. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67664. var parsedSound = parsedData.sounds[index];
  67665. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67666. if (!parsedSound.url)
  67667. parsedSound.url = parsedSound.name;
  67668. if (!loadedSounds[parsedSound.url]) {
  67669. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67670. loadedSounds[parsedSound.url] = loadedSound;
  67671. container.sounds.push(loadedSound);
  67672. }
  67673. else {
  67674. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67675. }
  67676. }
  67677. else {
  67678. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67679. }
  67680. }
  67681. }
  67682. loadedSounds = [];
  67683. // Connect parents & children and parse actions
  67684. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67685. var transformNode = scene.transformNodes[index];
  67686. if (transformNode._waitingParentId) {
  67687. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67688. transformNode._waitingParentId = null;
  67689. }
  67690. }
  67691. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67692. var mesh = scene.meshes[index];
  67693. if (mesh._waitingParentId) {
  67694. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67695. mesh._waitingParentId = null;
  67696. }
  67697. if (mesh._waitingActions) {
  67698. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67699. mesh._waitingActions = null;
  67700. }
  67701. }
  67702. // freeze world matrix application
  67703. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67704. var currentMesh = scene.meshes[index];
  67705. if (currentMesh._waitingFreezeWorldMatrix) {
  67706. currentMesh.freezeWorldMatrix();
  67707. currentMesh._waitingFreezeWorldMatrix = null;
  67708. }
  67709. else {
  67710. currentMesh.computeWorldMatrix(true);
  67711. }
  67712. }
  67713. // Particles Systems
  67714. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67715. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67716. var parsedParticleSystem = parsedData.particleSystems[index];
  67717. if (parsedParticleSystem.activeParticleCount) {
  67718. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67719. container.particleSystems.push(ps);
  67720. }
  67721. else {
  67722. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67723. container.particleSystems.push(ps);
  67724. }
  67725. }
  67726. }
  67727. // Lens flares
  67728. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67729. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67730. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67731. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67732. container.lensFlareSystems.push(lf);
  67733. }
  67734. }
  67735. // Shadows
  67736. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67737. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67738. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67739. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67740. container.shadowGenerators.push(sg);
  67741. }
  67742. }
  67743. // Lights exclusions / inclusions
  67744. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67745. var light_2 = scene.lights[index];
  67746. // Excluded check
  67747. if (light_2._excludedMeshesIds.length > 0) {
  67748. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67749. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67750. if (excludedMesh) {
  67751. light_2.excludedMeshes.push(excludedMesh);
  67752. }
  67753. }
  67754. light_2._excludedMeshesIds = [];
  67755. }
  67756. // Included check
  67757. if (light_2._includedOnlyMeshesIds.length > 0) {
  67758. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67759. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67760. if (includedOnlyMesh) {
  67761. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67762. }
  67763. }
  67764. light_2._includedOnlyMeshesIds = [];
  67765. }
  67766. }
  67767. // Effect layers
  67768. if (parsedData.effectLayers) {
  67769. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67770. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67771. container.effectLayers.push(effectLayer);
  67772. }
  67773. }
  67774. // Actions (scene)
  67775. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67776. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67777. }
  67778. if (!addToScene) {
  67779. container.removeAllFromScene();
  67780. }
  67781. }
  67782. catch (err) {
  67783. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67784. if (onError) {
  67785. onError(msg, err);
  67786. }
  67787. else {
  67788. BABYLON.Tools.Log(msg);
  67789. throw err;
  67790. }
  67791. }
  67792. finally {
  67793. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67794. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67795. }
  67796. }
  67797. return container;
  67798. };
  67799. BABYLON.SceneLoader.RegisterPlugin({
  67800. name: "babylon.js",
  67801. extensions: ".babylon",
  67802. canDirectLoad: function (data) {
  67803. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67804. return true;
  67805. }
  67806. return false;
  67807. },
  67808. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67809. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67810. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67811. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67812. // and avoid problems with multiple concurrent .babylon loads.
  67813. var log = "importMesh has failed JSON parse";
  67814. try {
  67815. var parsedData = JSON.parse(data);
  67816. log = "";
  67817. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67818. if (!meshesNames) {
  67819. meshesNames = null;
  67820. }
  67821. else if (!Array.isArray(meshesNames)) {
  67822. meshesNames = [meshesNames];
  67823. }
  67824. var hierarchyIds = new Array();
  67825. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67826. var loadedSkeletonsIds = [];
  67827. var loadedMaterialsIds = [];
  67828. var index;
  67829. var cache;
  67830. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67831. var parsedMesh = parsedData.meshes[index];
  67832. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67833. if (meshesNames !== null) {
  67834. // Remove found mesh name from list.
  67835. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67836. }
  67837. //Geometry?
  67838. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67839. //does the file contain geometries?
  67840. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67841. //find the correct geometry and add it to the scene
  67842. var found = false;
  67843. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67844. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67845. return;
  67846. }
  67847. else {
  67848. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67849. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67850. switch (geometryType) {
  67851. case "boxes":
  67852. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67853. break;
  67854. case "spheres":
  67855. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67856. break;
  67857. case "cylinders":
  67858. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67859. break;
  67860. case "toruses":
  67861. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67862. break;
  67863. case "grounds":
  67864. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67865. break;
  67866. case "planes":
  67867. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67868. break;
  67869. case "torusKnots":
  67870. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67871. break;
  67872. case "vertexData":
  67873. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67874. break;
  67875. }
  67876. found = true;
  67877. }
  67878. });
  67879. }
  67880. });
  67881. if (found === false) {
  67882. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67883. }
  67884. }
  67885. }
  67886. // Material ?
  67887. if (parsedMesh.materialId) {
  67888. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67889. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67890. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67891. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67892. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67893. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67894. var subMatId = parsedMultiMaterial.materials[matIndex];
  67895. loadedMaterialsIds.push(subMatId);
  67896. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67897. if (mat) {
  67898. log += "\n\tMaterial " + mat.toString(fullDetails);
  67899. }
  67900. }
  67901. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67902. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67903. if (mmat) {
  67904. materialFound = true;
  67905. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67906. }
  67907. break;
  67908. }
  67909. }
  67910. }
  67911. if (materialFound === false) {
  67912. loadedMaterialsIds.push(parsedMesh.materialId);
  67913. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67914. if (!mat) {
  67915. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67916. }
  67917. else {
  67918. log += "\n\tMaterial " + mat.toString(fullDetails);
  67919. }
  67920. }
  67921. }
  67922. // Skeleton ?
  67923. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67924. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67925. if (skeletonAlreadyLoaded === false) {
  67926. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67927. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67928. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67929. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67930. skeletons.push(skeleton);
  67931. loadedSkeletonsIds.push(parsedSkeleton.id);
  67932. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67933. }
  67934. }
  67935. }
  67936. }
  67937. // Morph targets ?
  67938. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67939. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67940. var managerData = _a[_i];
  67941. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67942. }
  67943. }
  67944. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67945. meshes.push(mesh);
  67946. log += "\n\tMesh " + mesh.toString(fullDetails);
  67947. }
  67948. }
  67949. // Connecting parents
  67950. var currentMesh;
  67951. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67952. currentMesh = scene.meshes[index];
  67953. if (currentMesh._waitingParentId) {
  67954. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67955. currentMesh._waitingParentId = null;
  67956. }
  67957. }
  67958. // freeze and compute world matrix application
  67959. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67960. currentMesh = scene.meshes[index];
  67961. if (currentMesh._waitingFreezeWorldMatrix) {
  67962. currentMesh.freezeWorldMatrix();
  67963. currentMesh._waitingFreezeWorldMatrix = null;
  67964. }
  67965. else {
  67966. currentMesh.computeWorldMatrix(true);
  67967. }
  67968. }
  67969. }
  67970. // Particles
  67971. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67972. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67973. var parsedParticleSystem = parsedData.particleSystems[index];
  67974. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67975. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67976. }
  67977. }
  67978. }
  67979. return true;
  67980. }
  67981. catch (err) {
  67982. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67983. if (onError) {
  67984. onError(msg, err);
  67985. }
  67986. else {
  67987. BABYLON.Tools.Log(msg);
  67988. throw err;
  67989. }
  67990. }
  67991. finally {
  67992. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67993. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67994. }
  67995. }
  67996. return false;
  67997. },
  67998. load: function (scene, data, rootUrl, onError) {
  67999. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68000. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68001. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68002. // and avoid problems with multiple concurrent .babylon loads.
  68003. var log = "importScene has failed JSON parse";
  68004. try {
  68005. var parsedData = JSON.parse(data);
  68006. log = "";
  68007. // Scene
  68008. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68009. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68010. }
  68011. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68012. scene.autoClear = parsedData.autoClear;
  68013. }
  68014. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68015. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68016. }
  68017. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68018. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68019. }
  68020. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68021. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68022. }
  68023. // Fog
  68024. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68025. scene.fogMode = parsedData.fogMode;
  68026. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68027. scene.fogStart = parsedData.fogStart;
  68028. scene.fogEnd = parsedData.fogEnd;
  68029. scene.fogDensity = parsedData.fogDensity;
  68030. log += "\tFog mode for scene: ";
  68031. switch (scene.fogMode) {
  68032. // getters not compiling, so using hardcoded
  68033. case 1:
  68034. log += "exp\n";
  68035. break;
  68036. case 2:
  68037. log += "exp2\n";
  68038. break;
  68039. case 3:
  68040. log += "linear\n";
  68041. break;
  68042. }
  68043. }
  68044. //Physics
  68045. if (parsedData.physicsEnabled) {
  68046. var physicsPlugin;
  68047. if (parsedData.physicsEngine === "cannon") {
  68048. physicsPlugin = new BABYLON.CannonJSPlugin();
  68049. }
  68050. else if (parsedData.physicsEngine === "oimo") {
  68051. physicsPlugin = new BABYLON.OimoJSPlugin();
  68052. }
  68053. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68054. //else - default engine, which is currently oimo
  68055. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68056. scene.enablePhysics(physicsGravity, physicsPlugin);
  68057. }
  68058. // Metadata
  68059. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68060. scene.metadata = parsedData.metadata;
  68061. }
  68062. //collisions, if defined. otherwise, default is true
  68063. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68064. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68065. }
  68066. scene.workerCollisions = !!parsedData.workerCollisions;
  68067. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68068. if (!container) {
  68069. return false;
  68070. }
  68071. if (parsedData.autoAnimate) {
  68072. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68073. }
  68074. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68075. scene.setActiveCameraByID(parsedData.activeCameraID);
  68076. }
  68077. // Environment texture
  68078. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68079. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68080. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68081. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68082. if (parsedData.environmentTextureRotationY) {
  68083. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68084. }
  68085. scene.environmentTexture = hdrTexture;
  68086. }
  68087. else {
  68088. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68089. if (parsedData.environmentTextureRotationY) {
  68090. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68091. }
  68092. scene.environmentTexture = cubeTexture;
  68093. }
  68094. if (parsedData.createDefaultSkybox === true) {
  68095. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68096. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68097. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68098. }
  68099. }
  68100. // Finish
  68101. return true;
  68102. }
  68103. catch (err) {
  68104. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68105. if (onError) {
  68106. onError(msg, err);
  68107. }
  68108. else {
  68109. BABYLON.Tools.Log(msg);
  68110. throw err;
  68111. }
  68112. }
  68113. finally {
  68114. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68115. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68116. }
  68117. }
  68118. return false;
  68119. },
  68120. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68121. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68122. return container;
  68123. }
  68124. });
  68125. })(BABYLON || (BABYLON = {}));
  68126. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68127. var BABYLON;
  68128. (function (BABYLON) {
  68129. var FilesInput = /** @class */ (function () {
  68130. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68131. this.onProcessFileCallback = function () { return true; };
  68132. this._engine = engine;
  68133. this._currentScene = scene;
  68134. this._sceneLoadedCallback = sceneLoadedCallback;
  68135. this._progressCallback = progressCallback;
  68136. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68137. this._textureLoadingCallback = textureLoadingCallback;
  68138. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68139. this._onReloadCallback = onReloadCallback;
  68140. this._errorCallback = errorCallback;
  68141. }
  68142. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68143. var _this = this;
  68144. if (elementToMonitor) {
  68145. this._elementToMonitor = elementToMonitor;
  68146. this._dragEnterHandler = function (e) { _this.drag(e); };
  68147. this._dragOverHandler = function (e) { _this.drag(e); };
  68148. this._dropHandler = function (e) { _this.drop(e); };
  68149. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68150. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68151. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68152. }
  68153. };
  68154. FilesInput.prototype.dispose = function () {
  68155. if (!this._elementToMonitor) {
  68156. return;
  68157. }
  68158. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68159. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68160. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68161. };
  68162. FilesInput.prototype.renderFunction = function () {
  68163. if (this._additionalRenderLoopLogicCallback) {
  68164. this._additionalRenderLoopLogicCallback();
  68165. }
  68166. if (this._currentScene) {
  68167. if (this._textureLoadingCallback) {
  68168. var remaining = this._currentScene.getWaitingItemsCount();
  68169. if (remaining > 0) {
  68170. this._textureLoadingCallback(remaining);
  68171. }
  68172. }
  68173. this._currentScene.render();
  68174. }
  68175. };
  68176. FilesInput.prototype.drag = function (e) {
  68177. e.stopPropagation();
  68178. e.preventDefault();
  68179. };
  68180. FilesInput.prototype.drop = function (eventDrop) {
  68181. eventDrop.stopPropagation();
  68182. eventDrop.preventDefault();
  68183. this.loadFiles(eventDrop);
  68184. };
  68185. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68186. var _this = this;
  68187. var reader = folder.createReader();
  68188. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68189. reader.readEntries(function (entries) {
  68190. remaining.count += entries.length;
  68191. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68192. var entry = entries_1[_i];
  68193. if (entry.isFile) {
  68194. entry.file(function (file) {
  68195. file.correctName = relativePath + file.name;
  68196. files.push(file);
  68197. if (--remaining.count === 0) {
  68198. callback();
  68199. }
  68200. });
  68201. }
  68202. else if (entry.isDirectory) {
  68203. _this._traverseFolder(entry, files, remaining, callback);
  68204. }
  68205. }
  68206. if (--remaining.count) {
  68207. callback();
  68208. }
  68209. });
  68210. };
  68211. FilesInput.prototype._processFiles = function (files) {
  68212. for (var i = 0; i < files.length; i++) {
  68213. var name = files[i].correctName.toLowerCase();
  68214. var extension = name.split('.').pop();
  68215. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68216. continue;
  68217. }
  68218. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68219. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68220. this._sceneFileToLoad = files[i];
  68221. }
  68222. else {
  68223. FilesInput.FilesToLoad[name] = files[i];
  68224. }
  68225. }
  68226. };
  68227. FilesInput.prototype.loadFiles = function (event) {
  68228. var _this = this;
  68229. if (this._startingProcessingFilesCallback)
  68230. this._startingProcessingFilesCallback();
  68231. // Handling data transfer via drag'n'drop
  68232. if (event && event.dataTransfer && event.dataTransfer.files) {
  68233. this._filesToLoad = event.dataTransfer.files;
  68234. }
  68235. // Handling files from input files
  68236. if (event && event.target && event.target.files) {
  68237. this._filesToLoad = event.target.files;
  68238. }
  68239. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68240. var files_1 = new Array();
  68241. var folders = [];
  68242. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68243. for (var i = 0; i < this._filesToLoad.length; i++) {
  68244. var fileToLoad = this._filesToLoad[i];
  68245. var name_1 = fileToLoad.name.toLowerCase();
  68246. var entry = void 0;
  68247. fileToLoad.correctName = name_1;
  68248. if (items) {
  68249. var item = items[i];
  68250. if (item.getAsEntry) {
  68251. entry = item.getAsEntry();
  68252. }
  68253. else if (item.webkitGetAsEntry) {
  68254. entry = item.webkitGetAsEntry();
  68255. }
  68256. }
  68257. if (!entry) {
  68258. files_1.push(fileToLoad);
  68259. }
  68260. else {
  68261. if (entry.isDirectory) {
  68262. folders.push(entry);
  68263. }
  68264. else {
  68265. files_1.push(fileToLoad);
  68266. }
  68267. }
  68268. }
  68269. if (folders.length === 0) {
  68270. this._processFiles(files_1);
  68271. this._processReload();
  68272. }
  68273. else {
  68274. var remaining = { count: folders.length };
  68275. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68276. var folder = folders_1[_i];
  68277. this._traverseFolder(folder, files_1, remaining, function () {
  68278. _this._processFiles(files_1);
  68279. if (remaining.count === 0) {
  68280. _this._processReload();
  68281. }
  68282. });
  68283. }
  68284. }
  68285. }
  68286. };
  68287. FilesInput.prototype._processReload = function () {
  68288. if (this._onReloadCallback) {
  68289. this._onReloadCallback(this._sceneFileToLoad);
  68290. }
  68291. else {
  68292. this.reload();
  68293. }
  68294. };
  68295. FilesInput.prototype.reload = function () {
  68296. var _this = this;
  68297. // If a scene file has been provided
  68298. if (this._sceneFileToLoad) {
  68299. if (this._currentScene) {
  68300. if (BABYLON.Tools.errorsCount > 0) {
  68301. BABYLON.Tools.ClearLogCache();
  68302. }
  68303. this._engine.stopRenderLoop();
  68304. }
  68305. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68306. if (_this._progressCallback) {
  68307. _this._progressCallback(progress);
  68308. }
  68309. }).then(function (scene) {
  68310. if (_this._currentScene) {
  68311. _this._currentScene.dispose();
  68312. }
  68313. _this._currentScene = scene;
  68314. if (_this._sceneLoadedCallback) {
  68315. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68316. }
  68317. // Wait for textures and shaders to be ready
  68318. _this._currentScene.executeWhenReady(function () {
  68319. _this._engine.runRenderLoop(function () {
  68320. _this.renderFunction();
  68321. });
  68322. });
  68323. }).catch(function (error) {
  68324. if (_this._errorCallback) {
  68325. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68326. }
  68327. });
  68328. }
  68329. else {
  68330. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68331. }
  68332. };
  68333. FilesInput.FilesToLoad = {};
  68334. return FilesInput;
  68335. }());
  68336. BABYLON.FilesInput = FilesInput;
  68337. })(BABYLON || (BABYLON = {}));
  68338. //# sourceMappingURL=babylon.filesInput.js.map
  68339. var BABYLON;
  68340. (function (BABYLON) {
  68341. /**
  68342. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68343. * The underlying implementation relies on an associative array to ensure the best performances.
  68344. * The value can be anything including 'null' but except 'undefined'
  68345. */
  68346. var StringDictionary = /** @class */ (function () {
  68347. function StringDictionary() {
  68348. this._count = 0;
  68349. this._data = {};
  68350. }
  68351. /**
  68352. * This will clear this dictionary and copy the content from the 'source' one.
  68353. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68354. * @param source the dictionary to take the content from and copy to this dictionary
  68355. */
  68356. StringDictionary.prototype.copyFrom = function (source) {
  68357. var _this = this;
  68358. this.clear();
  68359. source.forEach(function (t, v) { return _this.add(t, v); });
  68360. };
  68361. /**
  68362. * Get a value based from its key
  68363. * @param key the given key to get the matching value from
  68364. * @return the value if found, otherwise undefined is returned
  68365. */
  68366. StringDictionary.prototype.get = function (key) {
  68367. var val = this._data[key];
  68368. if (val !== undefined) {
  68369. return val;
  68370. }
  68371. return undefined;
  68372. };
  68373. /**
  68374. * Get a value from its key or add it if it doesn't exist.
  68375. * This method will ensure you that a given key/data will be present in the dictionary.
  68376. * @param key the given key to get the matching value from
  68377. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68378. * The factory will only be invoked if there's no data for the given key.
  68379. * @return the value corresponding to the key.
  68380. */
  68381. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68382. var val = this.get(key);
  68383. if (val !== undefined) {
  68384. return val;
  68385. }
  68386. val = factory(key);
  68387. if (val) {
  68388. this.add(key, val);
  68389. }
  68390. return val;
  68391. };
  68392. /**
  68393. * Get a value from its key if present in the dictionary otherwise add it
  68394. * @param key the key to get the value from
  68395. * @param val if there's no such key/value pair in the dictionary add it with this value
  68396. * @return the value corresponding to the key
  68397. */
  68398. StringDictionary.prototype.getOrAdd = function (key, val) {
  68399. var curVal = this.get(key);
  68400. if (curVal !== undefined) {
  68401. return curVal;
  68402. }
  68403. this.add(key, val);
  68404. return val;
  68405. };
  68406. /**
  68407. * Check if there's a given key in the dictionary
  68408. * @param key the key to check for
  68409. * @return true if the key is present, false otherwise
  68410. */
  68411. StringDictionary.prototype.contains = function (key) {
  68412. return this._data[key] !== undefined;
  68413. };
  68414. /**
  68415. * Add a new key and its corresponding value
  68416. * @param key the key to add
  68417. * @param value the value corresponding to the key
  68418. * @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
  68419. */
  68420. StringDictionary.prototype.add = function (key, value) {
  68421. if (this._data[key] !== undefined) {
  68422. return false;
  68423. }
  68424. this._data[key] = value;
  68425. ++this._count;
  68426. return true;
  68427. };
  68428. StringDictionary.prototype.set = function (key, value) {
  68429. if (this._data[key] === undefined) {
  68430. return false;
  68431. }
  68432. this._data[key] = value;
  68433. return true;
  68434. };
  68435. /**
  68436. * Get the element of the given key and remove it from the dictionary
  68437. * @param key
  68438. */
  68439. StringDictionary.prototype.getAndRemove = function (key) {
  68440. var val = this.get(key);
  68441. if (val !== undefined) {
  68442. delete this._data[key];
  68443. --this._count;
  68444. return val;
  68445. }
  68446. return null;
  68447. };
  68448. /**
  68449. * Remove a key/value from the dictionary.
  68450. * @param key the key to remove
  68451. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68452. */
  68453. StringDictionary.prototype.remove = function (key) {
  68454. if (this.contains(key)) {
  68455. delete this._data[key];
  68456. --this._count;
  68457. return true;
  68458. }
  68459. return false;
  68460. };
  68461. /**
  68462. * Clear the whole content of the dictionary
  68463. */
  68464. StringDictionary.prototype.clear = function () {
  68465. this._data = {};
  68466. this._count = 0;
  68467. };
  68468. Object.defineProperty(StringDictionary.prototype, "count", {
  68469. get: function () {
  68470. return this._count;
  68471. },
  68472. enumerable: true,
  68473. configurable: true
  68474. });
  68475. /**
  68476. * Execute a callback on each key/val of the dictionary.
  68477. * Note that you can remove any element in this dictionary in the callback implementation
  68478. * @param callback the callback to execute on a given key/value pair
  68479. */
  68480. StringDictionary.prototype.forEach = function (callback) {
  68481. for (var cur in this._data) {
  68482. var val = this._data[cur];
  68483. callback(cur, val);
  68484. }
  68485. };
  68486. /**
  68487. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68488. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68489. * Note that you can remove any element in this dictionary in the callback implementation
  68490. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68491. */
  68492. StringDictionary.prototype.first = function (callback) {
  68493. for (var cur in this._data) {
  68494. var val = this._data[cur];
  68495. var res = callback(cur, val);
  68496. if (res) {
  68497. return res;
  68498. }
  68499. }
  68500. return null;
  68501. };
  68502. return StringDictionary;
  68503. }());
  68504. BABYLON.StringDictionary = StringDictionary;
  68505. })(BABYLON || (BABYLON = {}));
  68506. //# sourceMappingURL=babylon.stringDictionary.js.map
  68507. var BABYLON;
  68508. (function (BABYLON) {
  68509. var Tags = /** @class */ (function () {
  68510. function Tags() {
  68511. }
  68512. Tags.EnableFor = function (obj) {
  68513. obj._tags = obj._tags || {};
  68514. obj.hasTags = function () {
  68515. return Tags.HasTags(obj);
  68516. };
  68517. obj.addTags = function (tagsString) {
  68518. return Tags.AddTagsTo(obj, tagsString);
  68519. };
  68520. obj.removeTags = function (tagsString) {
  68521. return Tags.RemoveTagsFrom(obj, tagsString);
  68522. };
  68523. obj.matchesTagsQuery = function (tagsQuery) {
  68524. return Tags.MatchesQuery(obj, tagsQuery);
  68525. };
  68526. };
  68527. Tags.DisableFor = function (obj) {
  68528. delete obj._tags;
  68529. delete obj.hasTags;
  68530. delete obj.addTags;
  68531. delete obj.removeTags;
  68532. delete obj.matchesTagsQuery;
  68533. };
  68534. Tags.HasTags = function (obj) {
  68535. if (!obj._tags) {
  68536. return false;
  68537. }
  68538. return !BABYLON.Tools.IsEmpty(obj._tags);
  68539. };
  68540. Tags.GetTags = function (obj, asString) {
  68541. if (asString === void 0) { asString = true; }
  68542. if (!obj._tags) {
  68543. return null;
  68544. }
  68545. if (asString) {
  68546. var tagsArray = [];
  68547. for (var tag in obj._tags) {
  68548. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68549. tagsArray.push(tag);
  68550. }
  68551. }
  68552. return tagsArray.join(" ");
  68553. }
  68554. else {
  68555. return obj._tags;
  68556. }
  68557. };
  68558. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68559. // a tag cannot start with '||', '&&', and '!'
  68560. // it cannot contain whitespaces
  68561. Tags.AddTagsTo = function (obj, tagsString) {
  68562. if (!tagsString) {
  68563. return;
  68564. }
  68565. if (typeof tagsString !== "string") {
  68566. return;
  68567. }
  68568. var tags = tagsString.split(" ");
  68569. tags.forEach(function (tag, index, array) {
  68570. Tags._AddTagTo(obj, tag);
  68571. });
  68572. };
  68573. Tags._AddTagTo = function (obj, tag) {
  68574. tag = tag.trim();
  68575. if (tag === "" || tag === "true" || tag === "false") {
  68576. return;
  68577. }
  68578. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68579. return;
  68580. }
  68581. Tags.EnableFor(obj);
  68582. obj._tags[tag] = true;
  68583. };
  68584. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68585. if (!Tags.HasTags(obj)) {
  68586. return;
  68587. }
  68588. var tags = tagsString.split(" ");
  68589. for (var t in tags) {
  68590. Tags._RemoveTagFrom(obj, tags[t]);
  68591. }
  68592. };
  68593. Tags._RemoveTagFrom = function (obj, tag) {
  68594. delete obj._tags[tag];
  68595. };
  68596. Tags.MatchesQuery = function (obj, tagsQuery) {
  68597. if (tagsQuery === undefined) {
  68598. return true;
  68599. }
  68600. if (tagsQuery === "") {
  68601. return Tags.HasTags(obj);
  68602. }
  68603. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68604. };
  68605. return Tags;
  68606. }());
  68607. BABYLON.Tags = Tags;
  68608. })(BABYLON || (BABYLON = {}));
  68609. //# sourceMappingURL=babylon.tags.js.map
  68610. var BABYLON;
  68611. (function (BABYLON) {
  68612. /**
  68613. * Class used to evalaute queries containing `and` and `or` operators
  68614. */
  68615. var AndOrNotEvaluator = /** @class */ (function () {
  68616. function AndOrNotEvaluator() {
  68617. }
  68618. /**
  68619. * Evaluate a query
  68620. * @param query defines the query to evaluate
  68621. * @param evaluateCallback defines the callback used to filter result
  68622. * @returns true if the query matches
  68623. */
  68624. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68625. if (!query.match(/\([^\(\)]*\)/g)) {
  68626. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68627. }
  68628. else {
  68629. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68630. // remove parenthesis
  68631. r = r.slice(1, r.length - 1);
  68632. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68633. });
  68634. }
  68635. if (query === "true") {
  68636. return true;
  68637. }
  68638. if (query === "false") {
  68639. return false;
  68640. }
  68641. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68642. };
  68643. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68644. evaluateCallback = evaluateCallback || (function (r) {
  68645. return r === "true" ? true : false;
  68646. });
  68647. var result;
  68648. var or = parenthesisContent.split("||");
  68649. for (var i in or) {
  68650. if (or.hasOwnProperty(i)) {
  68651. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68652. var and = ori.split("&&");
  68653. if (and.length > 1) {
  68654. for (var j = 0; j < and.length; ++j) {
  68655. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68656. if (andj !== "true" && andj !== "false") {
  68657. if (andj[0] === "!") {
  68658. result = !evaluateCallback(andj.substring(1));
  68659. }
  68660. else {
  68661. result = evaluateCallback(andj);
  68662. }
  68663. }
  68664. else {
  68665. result = andj === "true" ? true : false;
  68666. }
  68667. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68668. ori = "false";
  68669. break;
  68670. }
  68671. }
  68672. }
  68673. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68674. result = true;
  68675. break;
  68676. }
  68677. // result equals false (or undefined)
  68678. if (ori !== "true" && ori !== "false") {
  68679. if (ori[0] === "!") {
  68680. result = !evaluateCallback(ori.substring(1));
  68681. }
  68682. else {
  68683. result = evaluateCallback(ori);
  68684. }
  68685. }
  68686. else {
  68687. result = ori === "true" ? true : false;
  68688. }
  68689. }
  68690. }
  68691. // the whole parenthesis scope is replaced by 'true' or 'false'
  68692. return result ? "true" : "false";
  68693. };
  68694. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68695. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68696. // remove whitespaces
  68697. r = r.replace(/[\s]/g, function () { return ""; });
  68698. return r.length % 2 ? "!" : "";
  68699. });
  68700. booleanString = booleanString.trim();
  68701. if (booleanString === "!true") {
  68702. booleanString = "false";
  68703. }
  68704. else if (booleanString === "!false") {
  68705. booleanString = "true";
  68706. }
  68707. return booleanString;
  68708. };
  68709. return AndOrNotEvaluator;
  68710. }());
  68711. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68712. })(BABYLON || (BABYLON = {}));
  68713. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68714. var BABYLON;
  68715. (function (BABYLON) {
  68716. /**
  68717. * Class used to enable access to IndexedDB
  68718. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68719. */
  68720. var Database = /** @class */ (function () {
  68721. /**
  68722. * Creates a new Database
  68723. * @param urlToScene defines the url to load the scene
  68724. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68725. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68726. */
  68727. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68728. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68729. var _this = this;
  68730. // Handling various flavors of prefixed version of IndexedDB
  68731. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68732. this.callbackManifestChecked = callbackManifestChecked;
  68733. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68734. this.db = null;
  68735. this._enableSceneOffline = false;
  68736. this._enableTexturesOffline = false;
  68737. this.manifestVersionFound = 0;
  68738. this.mustUpdateRessources = false;
  68739. this.hasReachedQuota = false;
  68740. if (!Database.IDBStorageEnabled) {
  68741. this.callbackManifestChecked(true);
  68742. }
  68743. else {
  68744. if (disableManifestCheck) {
  68745. this._enableSceneOffline = true;
  68746. this._enableTexturesOffline = true;
  68747. this.manifestVersionFound = 1;
  68748. BABYLON.Tools.SetImmediate(function () {
  68749. _this.callbackManifestChecked(true);
  68750. });
  68751. }
  68752. else {
  68753. this._checkManifestFile();
  68754. }
  68755. }
  68756. }
  68757. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68758. /**
  68759. * Gets a boolean indicating if scene must be saved in the database
  68760. */
  68761. get: function () {
  68762. return this._enableSceneOffline;
  68763. },
  68764. enumerable: true,
  68765. configurable: true
  68766. });
  68767. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68768. /**
  68769. * Gets a boolean indicating if textures must be saved in the database
  68770. */
  68771. get: function () {
  68772. return this._enableTexturesOffline;
  68773. },
  68774. enumerable: true,
  68775. configurable: true
  68776. });
  68777. Database.prototype._checkManifestFile = function () {
  68778. var _this = this;
  68779. var noManifestFile = function () {
  68780. _this._enableSceneOffline = false;
  68781. _this._enableTexturesOffline = false;
  68782. _this.callbackManifestChecked(false);
  68783. };
  68784. var timeStampUsed = false;
  68785. var manifestURL = this.currentSceneUrl + ".manifest";
  68786. var xhr = new XMLHttpRequest();
  68787. if (navigator.onLine) {
  68788. // Adding a timestamp to by-pass browsers' cache
  68789. timeStampUsed = true;
  68790. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68791. }
  68792. xhr.open("GET", manifestURL, true);
  68793. xhr.addEventListener("load", function () {
  68794. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68795. try {
  68796. var manifestFile = JSON.parse(xhr.response);
  68797. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68798. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68799. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68800. _this.manifestVersionFound = manifestFile.version;
  68801. }
  68802. if (_this.callbackManifestChecked) {
  68803. _this.callbackManifestChecked(true);
  68804. }
  68805. }
  68806. catch (ex) {
  68807. noManifestFile();
  68808. }
  68809. }
  68810. else {
  68811. noManifestFile();
  68812. }
  68813. }, false);
  68814. xhr.addEventListener("error", function (event) {
  68815. if (timeStampUsed) {
  68816. timeStampUsed = false;
  68817. // Let's retry without the timeStamp
  68818. // It could fail when coupled with HTML5 Offline API
  68819. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68820. xhr.open("GET", retryManifestURL, true);
  68821. xhr.send();
  68822. }
  68823. else {
  68824. noManifestFile();
  68825. }
  68826. }, false);
  68827. try {
  68828. xhr.send();
  68829. }
  68830. catch (ex) {
  68831. BABYLON.Tools.Error("Error on XHR send request.");
  68832. this.callbackManifestChecked(false);
  68833. }
  68834. };
  68835. /**
  68836. * Open the database and make it available
  68837. * @param successCallback defines the callback to call on success
  68838. * @param errorCallback defines the callback to call on error
  68839. */
  68840. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68841. var _this = this;
  68842. var handleError = function () {
  68843. _this.isSupported = false;
  68844. if (errorCallback)
  68845. errorCallback();
  68846. };
  68847. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68848. // Your browser doesn't support IndexedDB
  68849. this.isSupported = false;
  68850. if (errorCallback)
  68851. errorCallback();
  68852. }
  68853. else {
  68854. // If the DB hasn't been opened or created yet
  68855. if (!this.db) {
  68856. this.hasReachedQuota = false;
  68857. this.isSupported = true;
  68858. var request = this.idbFactory.open("babylonjs", 1);
  68859. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68860. request.onerror = function (event) {
  68861. handleError();
  68862. };
  68863. // executes when a version change transaction cannot complete due to other active transactions
  68864. request.onblocked = function (event) {
  68865. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68866. handleError();
  68867. };
  68868. // DB has been opened successfully
  68869. request.onsuccess = function (event) {
  68870. _this.db = request.result;
  68871. successCallback();
  68872. };
  68873. // Initialization of the DB. Creating Scenes & Textures stores
  68874. request.onupgradeneeded = function (event) {
  68875. _this.db = (event.target).result;
  68876. if (_this.db) {
  68877. try {
  68878. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68879. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68880. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68881. }
  68882. catch (ex) {
  68883. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68884. handleError();
  68885. }
  68886. }
  68887. };
  68888. }
  68889. // DB has already been created and opened
  68890. else {
  68891. if (successCallback)
  68892. successCallback();
  68893. }
  68894. }
  68895. };
  68896. /**
  68897. * Loads an image from the database
  68898. * @param url defines the url to load from
  68899. * @param image defines the target DOM image
  68900. */
  68901. Database.prototype.loadImageFromDB = function (url, image) {
  68902. var _this = this;
  68903. var completeURL = Database._ReturnFullUrlLocation(url);
  68904. var saveAndLoadImage = function () {
  68905. if (!_this.hasReachedQuota && _this.db !== null) {
  68906. // the texture is not yet in the DB, let's try to save it
  68907. _this._saveImageIntoDBAsync(completeURL, image);
  68908. }
  68909. // If the texture is not in the DB and we've reached the DB quota limit
  68910. // let's load it directly from the web
  68911. else {
  68912. image.src = url;
  68913. }
  68914. };
  68915. if (!this.mustUpdateRessources) {
  68916. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68917. }
  68918. // First time we're download the images or update requested in the manifest file by a version change
  68919. else {
  68920. saveAndLoadImage();
  68921. }
  68922. };
  68923. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68924. if (this.isSupported && this.db !== null) {
  68925. var texture;
  68926. var transaction = this.db.transaction(["textures"]);
  68927. transaction.onabort = function (event) {
  68928. image.src = url;
  68929. };
  68930. transaction.oncomplete = function (event) {
  68931. var blobTextureURL;
  68932. if (texture) {
  68933. var URL = window.URL || window.webkitURL;
  68934. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68935. image.onerror = function () {
  68936. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68937. image.src = url;
  68938. };
  68939. image.src = blobTextureURL;
  68940. }
  68941. else {
  68942. notInDBCallback();
  68943. }
  68944. };
  68945. var getRequest = transaction.objectStore("textures").get(url);
  68946. getRequest.onsuccess = function (event) {
  68947. texture = (event.target).result;
  68948. };
  68949. getRequest.onerror = function (event) {
  68950. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68951. image.src = url;
  68952. };
  68953. }
  68954. else {
  68955. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68956. image.src = url;
  68957. }
  68958. };
  68959. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68960. var _this = this;
  68961. if (this.isSupported) {
  68962. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68963. var generateBlobUrl = function () {
  68964. var blobTextureURL;
  68965. if (blob) {
  68966. var URL = window.URL || window.webkitURL;
  68967. try {
  68968. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68969. }
  68970. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68971. catch (ex) {
  68972. blobTextureURL = URL.createObjectURL(blob);
  68973. }
  68974. }
  68975. if (blobTextureURL) {
  68976. image.src = blobTextureURL;
  68977. }
  68978. };
  68979. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68980. var xhr = new XMLHttpRequest(), blob;
  68981. xhr.open("GET", url, true);
  68982. xhr.responseType = "blob";
  68983. xhr.addEventListener("load", function () {
  68984. if (xhr.status === 200 && _this.db) {
  68985. // Blob as response (XHR2)
  68986. blob = xhr.response;
  68987. var transaction = _this.db.transaction(["textures"], "readwrite");
  68988. // the transaction could abort because of a QuotaExceededError error
  68989. transaction.onabort = function (event) {
  68990. try {
  68991. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68992. var srcElement = (event.srcElement || event.target);
  68993. var error = srcElement.error;
  68994. if (error && error.name === "QuotaExceededError") {
  68995. _this.hasReachedQuota = true;
  68996. }
  68997. }
  68998. catch (ex) { }
  68999. generateBlobUrl();
  69000. };
  69001. transaction.oncomplete = function (event) {
  69002. generateBlobUrl();
  69003. };
  69004. var newTexture = { textureUrl: url, data: blob };
  69005. try {
  69006. // Put the blob into the dabase
  69007. var addRequest = transaction.objectStore("textures").put(newTexture);
  69008. addRequest.onsuccess = function (event) {
  69009. };
  69010. addRequest.onerror = function (event) {
  69011. generateBlobUrl();
  69012. };
  69013. }
  69014. catch (ex) {
  69015. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69016. if (ex.code === 25) {
  69017. Database.IsUASupportingBlobStorage = false;
  69018. }
  69019. image.src = url;
  69020. }
  69021. }
  69022. else {
  69023. image.src = url;
  69024. }
  69025. }, false);
  69026. xhr.addEventListener("error", function (event) {
  69027. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69028. image.src = url;
  69029. }, false);
  69030. xhr.send();
  69031. }
  69032. else {
  69033. image.src = url;
  69034. }
  69035. }
  69036. else {
  69037. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69038. image.src = url;
  69039. }
  69040. };
  69041. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69042. var _this = this;
  69043. var updateVersion = function () {
  69044. // the version is not yet in the DB or we need to update it
  69045. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69046. };
  69047. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69048. };
  69049. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69050. var _this = this;
  69051. if (this.isSupported && this.db) {
  69052. var version;
  69053. try {
  69054. var transaction = this.db.transaction(["versions"]);
  69055. transaction.oncomplete = function (event) {
  69056. if (version) {
  69057. // If the version in the JSON file is different from the version in DB
  69058. if (_this.manifestVersionFound !== version.data) {
  69059. _this.mustUpdateRessources = true;
  69060. updateInDBCallback();
  69061. }
  69062. else {
  69063. callback(version.data);
  69064. }
  69065. }
  69066. // version was not found in DB
  69067. else {
  69068. _this.mustUpdateRessources = true;
  69069. updateInDBCallback();
  69070. }
  69071. };
  69072. transaction.onabort = function (event) {
  69073. callback(-1);
  69074. };
  69075. var getRequest = transaction.objectStore("versions").get(url);
  69076. getRequest.onsuccess = function (event) {
  69077. version = (event.target).result;
  69078. };
  69079. getRequest.onerror = function (event) {
  69080. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69081. callback(-1);
  69082. };
  69083. }
  69084. catch (ex) {
  69085. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69086. callback(-1);
  69087. }
  69088. }
  69089. else {
  69090. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69091. callback(-1);
  69092. }
  69093. };
  69094. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69095. var _this = this;
  69096. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69097. try {
  69098. // Open a transaction to the database
  69099. var transaction = this.db.transaction(["versions"], "readwrite");
  69100. // the transaction could abort because of a QuotaExceededError error
  69101. transaction.onabort = function (event) {
  69102. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69103. var error = event.srcElement['error'];
  69104. if (error && error.name === "QuotaExceededError") {
  69105. _this.hasReachedQuota = true;
  69106. }
  69107. }
  69108. catch (ex) { }
  69109. callback(-1);
  69110. };
  69111. transaction.oncomplete = function (event) {
  69112. callback(_this.manifestVersionFound);
  69113. };
  69114. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69115. // Put the scene into the database
  69116. var addRequest = transaction.objectStore("versions").put(newVersion);
  69117. addRequest.onsuccess = function (event) {
  69118. };
  69119. addRequest.onerror = function (event) {
  69120. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69121. };
  69122. }
  69123. catch (ex) {
  69124. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69125. callback(-1);
  69126. }
  69127. }
  69128. else {
  69129. callback(-1);
  69130. }
  69131. };
  69132. /**
  69133. * Loads a file from database
  69134. * @param url defines the URL to load from
  69135. * @param sceneLoaded defines a callback to call on success
  69136. * @param progressCallBack defines a callback to call when progress changed
  69137. * @param errorCallback defines a callback to call on error
  69138. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69139. */
  69140. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69141. var _this = this;
  69142. var completeUrl = Database._ReturnFullUrlLocation(url);
  69143. var saveAndLoadFile = function () {
  69144. // the scene is not yet in the DB, let's try to save it
  69145. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69146. };
  69147. this._checkVersionFromDB(completeUrl, function (version) {
  69148. if (version !== -1) {
  69149. if (!_this.mustUpdateRessources) {
  69150. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69151. }
  69152. else {
  69153. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69154. }
  69155. }
  69156. else {
  69157. if (errorCallback) {
  69158. errorCallback();
  69159. }
  69160. }
  69161. });
  69162. };
  69163. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69164. if (this.isSupported && this.db) {
  69165. var targetStore;
  69166. if (url.indexOf(".babylon") !== -1) {
  69167. targetStore = "scenes";
  69168. }
  69169. else {
  69170. targetStore = "textures";
  69171. }
  69172. var file;
  69173. var transaction = this.db.transaction([targetStore]);
  69174. transaction.oncomplete = function (event) {
  69175. if (file) {
  69176. callback(file.data);
  69177. }
  69178. // file was not found in DB
  69179. else {
  69180. notInDBCallback();
  69181. }
  69182. };
  69183. transaction.onabort = function (event) {
  69184. notInDBCallback();
  69185. };
  69186. var getRequest = transaction.objectStore(targetStore).get(url);
  69187. getRequest.onsuccess = function (event) {
  69188. file = (event.target).result;
  69189. };
  69190. getRequest.onerror = function (event) {
  69191. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69192. notInDBCallback();
  69193. };
  69194. }
  69195. else {
  69196. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69197. callback();
  69198. }
  69199. };
  69200. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69201. var _this = this;
  69202. if (this.isSupported) {
  69203. var targetStore;
  69204. if (url.indexOf(".babylon") !== -1) {
  69205. targetStore = "scenes";
  69206. }
  69207. else {
  69208. targetStore = "textures";
  69209. }
  69210. // Create XHR
  69211. var xhr = new XMLHttpRequest();
  69212. var fileData;
  69213. xhr.open("GET", url, true);
  69214. if (useArrayBuffer) {
  69215. xhr.responseType = "arraybuffer";
  69216. }
  69217. if (progressCallback) {
  69218. xhr.onprogress = progressCallback;
  69219. }
  69220. xhr.addEventListener("load", function () {
  69221. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69222. // Blob as response (XHR2)
  69223. //fileData = xhr.responseText;
  69224. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69225. if (!_this.hasReachedQuota && _this.db) {
  69226. // Open a transaction to the database
  69227. var transaction = _this.db.transaction([targetStore], "readwrite");
  69228. // the transaction could abort because of a QuotaExceededError error
  69229. transaction.onabort = function (event) {
  69230. try {
  69231. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69232. var error = event.srcElement['error'];
  69233. if (error && error.name === "QuotaExceededError") {
  69234. _this.hasReachedQuota = true;
  69235. }
  69236. }
  69237. catch (ex) { }
  69238. callback(fileData);
  69239. };
  69240. transaction.oncomplete = function (event) {
  69241. callback(fileData);
  69242. };
  69243. var newFile;
  69244. if (targetStore === "scenes") {
  69245. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69246. }
  69247. else {
  69248. newFile = { textureUrl: url, data: fileData };
  69249. }
  69250. try {
  69251. // Put the scene into the database
  69252. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69253. addRequest.onsuccess = function (event) {
  69254. };
  69255. addRequest.onerror = function (event) {
  69256. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69257. };
  69258. }
  69259. catch (ex) {
  69260. callback(fileData);
  69261. }
  69262. }
  69263. else {
  69264. callback(fileData);
  69265. }
  69266. }
  69267. else {
  69268. callback();
  69269. }
  69270. }, false);
  69271. xhr.addEventListener("error", function (event) {
  69272. BABYLON.Tools.Error("error on XHR request.");
  69273. callback();
  69274. }, false);
  69275. xhr.send();
  69276. }
  69277. else {
  69278. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69279. callback();
  69280. }
  69281. };
  69282. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69283. Database.IsUASupportingBlobStorage = true;
  69284. /** Gets a boolean indicating if Database storate is enabled */
  69285. Database.IDBStorageEnabled = true;
  69286. Database._ParseURL = function (url) {
  69287. var a = document.createElement('a');
  69288. a.href = url;
  69289. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69290. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69291. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69292. return absLocation;
  69293. };
  69294. Database._ReturnFullUrlLocation = function (url) {
  69295. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69296. return (Database._ParseURL(window.location.href) + url);
  69297. }
  69298. else {
  69299. return url;
  69300. }
  69301. };
  69302. return Database;
  69303. }());
  69304. BABYLON.Database = Database;
  69305. })(BABYLON || (BABYLON = {}));
  69306. //# sourceMappingURL=babylon.database.js.map
  69307. var BABYLON;
  69308. (function (BABYLON) {
  69309. var FresnelParameters = /** @class */ (function () {
  69310. function FresnelParameters() {
  69311. this._isEnabled = true;
  69312. this.leftColor = BABYLON.Color3.White();
  69313. this.rightColor = BABYLON.Color3.Black();
  69314. this.bias = 0;
  69315. this.power = 1;
  69316. }
  69317. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69318. get: function () {
  69319. return this._isEnabled;
  69320. },
  69321. set: function (value) {
  69322. if (this._isEnabled === value) {
  69323. return;
  69324. }
  69325. this._isEnabled = value;
  69326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69327. },
  69328. enumerable: true,
  69329. configurable: true
  69330. });
  69331. FresnelParameters.prototype.clone = function () {
  69332. var newFresnelParameters = new FresnelParameters();
  69333. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69334. return newFresnelParameters;
  69335. };
  69336. FresnelParameters.prototype.serialize = function () {
  69337. var serializationObject = {};
  69338. serializationObject.isEnabled = this.isEnabled;
  69339. serializationObject.leftColor = this.leftColor.asArray();
  69340. serializationObject.rightColor = this.rightColor.asArray();
  69341. serializationObject.bias = this.bias;
  69342. serializationObject.power = this.power;
  69343. return serializationObject;
  69344. };
  69345. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69346. var fresnelParameters = new FresnelParameters();
  69347. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69348. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69349. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69350. fresnelParameters.bias = parsedFresnelParameters.bias;
  69351. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69352. return fresnelParameters;
  69353. };
  69354. return FresnelParameters;
  69355. }());
  69356. BABYLON.FresnelParameters = FresnelParameters;
  69357. })(BABYLON || (BABYLON = {}));
  69358. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69359. var BABYLON;
  69360. (function (BABYLON) {
  69361. var MultiMaterial = /** @class */ (function (_super) {
  69362. __extends(MultiMaterial, _super);
  69363. function MultiMaterial(name, scene) {
  69364. var _this = _super.call(this, name, scene, true) || this;
  69365. scene.multiMaterials.push(_this);
  69366. _this.subMaterials = new Array();
  69367. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69368. return _this;
  69369. }
  69370. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69371. get: function () {
  69372. return this._subMaterials;
  69373. },
  69374. set: function (value) {
  69375. this._subMaterials = value;
  69376. this._hookArray(value);
  69377. },
  69378. enumerable: true,
  69379. configurable: true
  69380. });
  69381. MultiMaterial.prototype._hookArray = function (array) {
  69382. var _this = this;
  69383. var oldPush = array.push;
  69384. array.push = function () {
  69385. var items = [];
  69386. for (var _i = 0; _i < arguments.length; _i++) {
  69387. items[_i] = arguments[_i];
  69388. }
  69389. var result = oldPush.apply(array, items);
  69390. _this._markAllSubMeshesAsTexturesDirty();
  69391. return result;
  69392. };
  69393. var oldSplice = array.splice;
  69394. array.splice = function (index, deleteCount) {
  69395. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69396. _this._markAllSubMeshesAsTexturesDirty();
  69397. return deleted;
  69398. };
  69399. };
  69400. // Properties
  69401. MultiMaterial.prototype.getSubMaterial = function (index) {
  69402. if (index < 0 || index >= this.subMaterials.length) {
  69403. return this.getScene().defaultMaterial;
  69404. }
  69405. return this.subMaterials[index];
  69406. };
  69407. MultiMaterial.prototype.getActiveTextures = function () {
  69408. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69409. if (subMaterial) {
  69410. return subMaterial.getActiveTextures();
  69411. }
  69412. else {
  69413. return [];
  69414. }
  69415. }));
  69416. var _a;
  69417. };
  69418. // Methods
  69419. MultiMaterial.prototype.getClassName = function () {
  69420. return "MultiMaterial";
  69421. };
  69422. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69423. for (var index = 0; index < this.subMaterials.length; index++) {
  69424. var subMaterial = this.subMaterials[index];
  69425. if (subMaterial) {
  69426. if (subMaterial.storeEffectOnSubMeshes) {
  69427. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69428. return false;
  69429. }
  69430. continue;
  69431. }
  69432. if (!subMaterial.isReady(mesh)) {
  69433. return false;
  69434. }
  69435. }
  69436. }
  69437. return true;
  69438. };
  69439. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69440. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69441. for (var index = 0; index < this.subMaterials.length; index++) {
  69442. var subMaterial = null;
  69443. var current = this.subMaterials[index];
  69444. if (cloneChildren && current) {
  69445. subMaterial = current.clone(name + "-" + current.name);
  69446. }
  69447. else {
  69448. subMaterial = this.subMaterials[index];
  69449. }
  69450. newMultiMaterial.subMaterials.push(subMaterial);
  69451. }
  69452. return newMultiMaterial;
  69453. };
  69454. MultiMaterial.prototype.serialize = function () {
  69455. var serializationObject = {};
  69456. serializationObject.name = this.name;
  69457. serializationObject.id = this.id;
  69458. if (BABYLON.Tags) {
  69459. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69460. }
  69461. serializationObject.materials = [];
  69462. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69463. var subMat = this.subMaterials[matIndex];
  69464. if (subMat) {
  69465. serializationObject.materials.push(subMat.id);
  69466. }
  69467. else {
  69468. serializationObject.materials.push(null);
  69469. }
  69470. }
  69471. return serializationObject;
  69472. };
  69473. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69474. var scene = this.getScene();
  69475. if (!scene) {
  69476. return;
  69477. }
  69478. var index = scene.multiMaterials.indexOf(this);
  69479. if (index >= 0) {
  69480. scene.multiMaterials.splice(index, 1);
  69481. }
  69482. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69483. };
  69484. return MultiMaterial;
  69485. }(BABYLON.Material));
  69486. BABYLON.MultiMaterial = MultiMaterial;
  69487. })(BABYLON || (BABYLON = {}));
  69488. //# sourceMappingURL=babylon.multiMaterial.js.map
  69489. var BABYLON;
  69490. (function (BABYLON) {
  69491. var FreeCameraTouchInput = /** @class */ (function () {
  69492. function FreeCameraTouchInput() {
  69493. this._offsetX = null;
  69494. this._offsetY = null;
  69495. this._pointerPressed = new Array();
  69496. this.touchAngularSensibility = 200000.0;
  69497. this.touchMoveSensibility = 250.0;
  69498. }
  69499. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69500. var _this = this;
  69501. var previousPosition = null;
  69502. if (this._pointerInput === undefined) {
  69503. this._onLostFocus = function (evt) {
  69504. _this._offsetX = null;
  69505. _this._offsetY = null;
  69506. };
  69507. this._pointerInput = function (p, s) {
  69508. var evt = p.event;
  69509. if (evt.pointerType === "mouse") {
  69510. return;
  69511. }
  69512. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69513. if (!noPreventDefault) {
  69514. evt.preventDefault();
  69515. }
  69516. _this._pointerPressed.push(evt.pointerId);
  69517. if (_this._pointerPressed.length !== 1) {
  69518. return;
  69519. }
  69520. previousPosition = {
  69521. x: evt.clientX,
  69522. y: evt.clientY
  69523. };
  69524. }
  69525. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69526. if (!noPreventDefault) {
  69527. evt.preventDefault();
  69528. }
  69529. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69530. if (index === -1) {
  69531. return;
  69532. }
  69533. _this._pointerPressed.splice(index, 1);
  69534. if (index != 0) {
  69535. return;
  69536. }
  69537. previousPosition = null;
  69538. _this._offsetX = null;
  69539. _this._offsetY = null;
  69540. }
  69541. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69542. if (!noPreventDefault) {
  69543. evt.preventDefault();
  69544. }
  69545. if (!previousPosition) {
  69546. return;
  69547. }
  69548. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69549. if (index != 0) {
  69550. return;
  69551. }
  69552. _this._offsetX = evt.clientX - previousPosition.x;
  69553. _this._offsetY = -(evt.clientY - previousPosition.y);
  69554. }
  69555. };
  69556. }
  69557. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69558. if (this._onLostFocus) {
  69559. element.addEventListener("blur", this._onLostFocus);
  69560. }
  69561. };
  69562. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69563. if (this._pointerInput && element) {
  69564. if (this._observer) {
  69565. this.camera.getScene().onPointerObservable.remove(this._observer);
  69566. this._observer = null;
  69567. }
  69568. if (this._onLostFocus) {
  69569. element.removeEventListener("blur", this._onLostFocus);
  69570. this._onLostFocus = null;
  69571. }
  69572. this._pointerPressed = [];
  69573. this._offsetX = null;
  69574. this._offsetY = null;
  69575. }
  69576. };
  69577. FreeCameraTouchInput.prototype.checkInputs = function () {
  69578. if (this._offsetX && this._offsetY) {
  69579. var camera = this.camera;
  69580. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69581. if (this._pointerPressed.length > 1) {
  69582. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69583. }
  69584. else {
  69585. var speed = camera._computeLocalCameraSpeed();
  69586. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69587. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69588. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69589. }
  69590. }
  69591. };
  69592. FreeCameraTouchInput.prototype.getClassName = function () {
  69593. return "FreeCameraTouchInput";
  69594. };
  69595. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69596. return "touch";
  69597. };
  69598. __decorate([
  69599. BABYLON.serialize()
  69600. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69601. __decorate([
  69602. BABYLON.serialize()
  69603. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69604. return FreeCameraTouchInput;
  69605. }());
  69606. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69607. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69608. })(BABYLON || (BABYLON = {}));
  69609. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69610. var BABYLON;
  69611. (function (BABYLON) {
  69612. // We're mainly based on the logic defined into the FreeCamera code
  69613. var TouchCamera = /** @class */ (function (_super) {
  69614. __extends(TouchCamera, _super);
  69615. //-- end properties for backward compatibility for inputs
  69616. function TouchCamera(name, position, scene) {
  69617. var _this = _super.call(this, name, position, scene) || this;
  69618. _this.inputs.addTouch();
  69619. _this._setupInputs();
  69620. return _this;
  69621. }
  69622. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69623. //-- Begin properties for backward compatibility for inputs
  69624. get: function () {
  69625. var touch = this.inputs.attached["touch"];
  69626. if (touch)
  69627. return touch.touchAngularSensibility;
  69628. return 0;
  69629. },
  69630. set: function (value) {
  69631. var touch = this.inputs.attached["touch"];
  69632. if (touch)
  69633. touch.touchAngularSensibility = value;
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69639. get: function () {
  69640. var touch = this.inputs.attached["touch"];
  69641. if (touch)
  69642. return touch.touchMoveSensibility;
  69643. return 0;
  69644. },
  69645. set: function (value) {
  69646. var touch = this.inputs.attached["touch"];
  69647. if (touch)
  69648. touch.touchMoveSensibility = value;
  69649. },
  69650. enumerable: true,
  69651. configurable: true
  69652. });
  69653. TouchCamera.prototype.getClassName = function () {
  69654. return "TouchCamera";
  69655. };
  69656. TouchCamera.prototype._setupInputs = function () {
  69657. var mouse = this.inputs.attached["mouse"];
  69658. if (mouse) {
  69659. mouse.touchEnabled = false;
  69660. }
  69661. };
  69662. return TouchCamera;
  69663. }(BABYLON.FreeCamera));
  69664. BABYLON.TouchCamera = TouchCamera;
  69665. })(BABYLON || (BABYLON = {}));
  69666. //# sourceMappingURL=babylon.touchCamera.js.map
  69667. var BABYLON;
  69668. (function (BABYLON) {
  69669. var ProceduralTexture = /** @class */ (function (_super) {
  69670. __extends(ProceduralTexture, _super);
  69671. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69672. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69673. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69674. if (isCube === void 0) { isCube = false; }
  69675. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69676. _this.isCube = isCube;
  69677. _this.isEnabled = true;
  69678. _this._currentRefreshId = -1;
  69679. _this._refreshRate = 1;
  69680. _this._vertexBuffers = {};
  69681. _this._uniforms = new Array();
  69682. _this._samplers = new Array();
  69683. _this._textures = {};
  69684. _this._floats = {};
  69685. _this._floatsArrays = {};
  69686. _this._colors3 = {};
  69687. _this._colors4 = {};
  69688. _this._vectors2 = {};
  69689. _this._vectors3 = {};
  69690. _this._matrices = {};
  69691. _this._fallbackTextureUsed = false;
  69692. scene.proceduralTextures.push(_this);
  69693. _this._engine = scene.getEngine();
  69694. _this.name = name;
  69695. _this.isRenderTarget = true;
  69696. _this._size = size;
  69697. _this._generateMipMaps = generateMipMaps;
  69698. _this.setFragment(fragment);
  69699. _this._fallbackTexture = fallbackTexture;
  69700. if (isCube) {
  69701. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69702. _this.setFloat("face", 0);
  69703. }
  69704. else {
  69705. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69706. }
  69707. // VBO
  69708. var vertices = [];
  69709. vertices.push(1, 1);
  69710. vertices.push(-1, 1);
  69711. vertices.push(-1, -1);
  69712. vertices.push(1, -1);
  69713. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69714. _this._createIndexBuffer();
  69715. return _this;
  69716. }
  69717. ProceduralTexture.prototype._createIndexBuffer = function () {
  69718. var engine = this._engine;
  69719. // Indices
  69720. var indices = [];
  69721. indices.push(0);
  69722. indices.push(1);
  69723. indices.push(2);
  69724. indices.push(0);
  69725. indices.push(2);
  69726. indices.push(3);
  69727. this._indexBuffer = engine.createIndexBuffer(indices);
  69728. };
  69729. ProceduralTexture.prototype._rebuild = function () {
  69730. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69731. if (vb) {
  69732. vb._rebuild();
  69733. }
  69734. this._createIndexBuffer();
  69735. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69736. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69737. }
  69738. };
  69739. ProceduralTexture.prototype.reset = function () {
  69740. if (this._effect === undefined) {
  69741. return;
  69742. }
  69743. var engine = this._engine;
  69744. engine._releaseEffect(this._effect);
  69745. };
  69746. ProceduralTexture.prototype.isReady = function () {
  69747. var _this = this;
  69748. var engine = this._engine;
  69749. var shaders;
  69750. if (!this._fragment) {
  69751. return false;
  69752. }
  69753. if (this._fallbackTextureUsed) {
  69754. return true;
  69755. }
  69756. if (this._fragment.fragmentElement !== undefined) {
  69757. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69758. }
  69759. else {
  69760. shaders = { vertex: "procedural", fragment: this._fragment };
  69761. }
  69762. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69763. _this.releaseInternalTexture();
  69764. if (_this._fallbackTexture) {
  69765. _this._texture = _this._fallbackTexture._texture;
  69766. if (_this._texture) {
  69767. _this._texture.incrementReferences();
  69768. }
  69769. }
  69770. _this._fallbackTextureUsed = true;
  69771. });
  69772. return this._effect.isReady();
  69773. };
  69774. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69775. this._currentRefreshId = -1;
  69776. };
  69777. ProceduralTexture.prototype.setFragment = function (fragment) {
  69778. this._fragment = fragment;
  69779. };
  69780. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69781. get: function () {
  69782. return this._refreshRate;
  69783. },
  69784. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69785. set: function (value) {
  69786. this._refreshRate = value;
  69787. this.resetRefreshCounter();
  69788. },
  69789. enumerable: true,
  69790. configurable: true
  69791. });
  69792. ProceduralTexture.prototype._shouldRender = function () {
  69793. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69794. return false;
  69795. }
  69796. if (this._fallbackTextureUsed) {
  69797. return false;
  69798. }
  69799. if (this._currentRefreshId === -1) { // At least render once
  69800. this._currentRefreshId = 1;
  69801. return true;
  69802. }
  69803. if (this.refreshRate === this._currentRefreshId) {
  69804. this._currentRefreshId = 1;
  69805. return true;
  69806. }
  69807. this._currentRefreshId++;
  69808. return false;
  69809. };
  69810. ProceduralTexture.prototype.getRenderSize = function () {
  69811. return this._size;
  69812. };
  69813. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69814. if (this._fallbackTextureUsed) {
  69815. return;
  69816. }
  69817. this.releaseInternalTexture();
  69818. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69819. // Update properties
  69820. this._size = size;
  69821. this._generateMipMaps = generateMipMaps;
  69822. };
  69823. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69824. if (this._uniforms.indexOf(uniformName) === -1) {
  69825. this._uniforms.push(uniformName);
  69826. }
  69827. };
  69828. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69829. if (this._samplers.indexOf(name) === -1) {
  69830. this._samplers.push(name);
  69831. }
  69832. this._textures[name] = texture;
  69833. return this;
  69834. };
  69835. ProceduralTexture.prototype.setFloat = function (name, value) {
  69836. this._checkUniform(name);
  69837. this._floats[name] = value;
  69838. return this;
  69839. };
  69840. ProceduralTexture.prototype.setFloats = function (name, value) {
  69841. this._checkUniform(name);
  69842. this._floatsArrays[name] = value;
  69843. return this;
  69844. };
  69845. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69846. this._checkUniform(name);
  69847. this._colors3[name] = value;
  69848. return this;
  69849. };
  69850. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69851. this._checkUniform(name);
  69852. this._colors4[name] = value;
  69853. return this;
  69854. };
  69855. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69856. this._checkUniform(name);
  69857. this._vectors2[name] = value;
  69858. return this;
  69859. };
  69860. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69861. this._checkUniform(name);
  69862. this._vectors3[name] = value;
  69863. return this;
  69864. };
  69865. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69866. this._checkUniform(name);
  69867. this._matrices[name] = value;
  69868. return this;
  69869. };
  69870. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69871. var scene = this.getScene();
  69872. if (!scene) {
  69873. return;
  69874. }
  69875. var engine = this._engine;
  69876. // Render
  69877. engine.enableEffect(this._effect);
  69878. engine.setState(false);
  69879. // Texture
  69880. for (var name in this._textures) {
  69881. this._effect.setTexture(name, this._textures[name]);
  69882. }
  69883. // Float
  69884. for (name in this._floats) {
  69885. this._effect.setFloat(name, this._floats[name]);
  69886. }
  69887. // Floats
  69888. for (name in this._floatsArrays) {
  69889. this._effect.setArray(name, this._floatsArrays[name]);
  69890. }
  69891. // Color3
  69892. for (name in this._colors3) {
  69893. this._effect.setColor3(name, this._colors3[name]);
  69894. }
  69895. // Color4
  69896. for (name in this._colors4) {
  69897. var color = this._colors4[name];
  69898. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69899. }
  69900. // Vector2
  69901. for (name in this._vectors2) {
  69902. this._effect.setVector2(name, this._vectors2[name]);
  69903. }
  69904. // Vector3
  69905. for (name in this._vectors3) {
  69906. this._effect.setVector3(name, this._vectors3[name]);
  69907. }
  69908. // Matrix
  69909. for (name in this._matrices) {
  69910. this._effect.setMatrix(name, this._matrices[name]);
  69911. }
  69912. if (!this._texture) {
  69913. return;
  69914. }
  69915. if (this.isCube) {
  69916. for (var face = 0; face < 6; face++) {
  69917. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69918. // VBOs
  69919. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69920. this._effect.setFloat("face", face);
  69921. // Clear
  69922. engine.clear(scene.clearColor, true, true, true);
  69923. // Draw order
  69924. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69925. // Mipmaps
  69926. if (face === 5) {
  69927. engine.generateMipMapsForCubemap(this._texture);
  69928. }
  69929. }
  69930. }
  69931. else {
  69932. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69933. // VBOs
  69934. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69935. // Clear
  69936. engine.clear(scene.clearColor, true, true, true);
  69937. // Draw order
  69938. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69939. }
  69940. // Unbind
  69941. engine.unBindFramebuffer(this._texture, this.isCube);
  69942. if (this.onGenerated) {
  69943. this.onGenerated();
  69944. }
  69945. };
  69946. ProceduralTexture.prototype.clone = function () {
  69947. var textureSize = this.getSize();
  69948. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69949. // Base texture
  69950. newTexture.hasAlpha = this.hasAlpha;
  69951. newTexture.level = this.level;
  69952. // RenderTarget Texture
  69953. newTexture.coordinatesMode = this.coordinatesMode;
  69954. return newTexture;
  69955. };
  69956. ProceduralTexture.prototype.dispose = function () {
  69957. var scene = this.getScene();
  69958. if (!scene) {
  69959. return;
  69960. }
  69961. var index = scene.proceduralTextures.indexOf(this);
  69962. if (index >= 0) {
  69963. scene.proceduralTextures.splice(index, 1);
  69964. }
  69965. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69966. if (vertexBuffer) {
  69967. vertexBuffer.dispose();
  69968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69969. }
  69970. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69971. this._indexBuffer = null;
  69972. }
  69973. _super.prototype.dispose.call(this);
  69974. };
  69975. __decorate([
  69976. BABYLON.serialize()
  69977. ], ProceduralTexture.prototype, "_size", void 0);
  69978. __decorate([
  69979. BABYLON.serialize()
  69980. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69981. __decorate([
  69982. BABYLON.serialize()
  69983. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69984. __decorate([
  69985. BABYLON.serialize()
  69986. ], ProceduralTexture.prototype, "refreshRate", null);
  69987. return ProceduralTexture;
  69988. }(BABYLON.Texture));
  69989. BABYLON.ProceduralTexture = ProceduralTexture;
  69990. })(BABYLON || (BABYLON = {}));
  69991. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69992. var BABYLON;
  69993. (function (BABYLON) {
  69994. var CustomProceduralTexture = /** @class */ (function (_super) {
  69995. __extends(CustomProceduralTexture, _super);
  69996. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69997. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69998. _this._animate = true;
  69999. _this._time = 0;
  70000. _this._texturePath = texturePath;
  70001. //Try to load json
  70002. _this.loadJson(texturePath);
  70003. _this.refreshRate = 1;
  70004. return _this;
  70005. }
  70006. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70007. var _this = this;
  70008. var noConfigFile = function () {
  70009. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70010. try {
  70011. _this.setFragment(_this._texturePath);
  70012. }
  70013. catch (ex) {
  70014. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70015. }
  70016. };
  70017. var configFileUrl = jsonUrl + "/config.json";
  70018. var xhr = new XMLHttpRequest();
  70019. xhr.open("GET", configFileUrl, true);
  70020. xhr.addEventListener("load", function () {
  70021. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70022. try {
  70023. _this._config = JSON.parse(xhr.response);
  70024. _this.updateShaderUniforms();
  70025. _this.updateTextures();
  70026. _this.setFragment(_this._texturePath + "/custom");
  70027. _this._animate = _this._config.animate;
  70028. _this.refreshRate = _this._config.refreshrate;
  70029. }
  70030. catch (ex) {
  70031. noConfigFile();
  70032. }
  70033. }
  70034. else {
  70035. noConfigFile();
  70036. }
  70037. }, false);
  70038. xhr.addEventListener("error", function () {
  70039. noConfigFile();
  70040. }, false);
  70041. try {
  70042. xhr.send();
  70043. }
  70044. catch (ex) {
  70045. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70046. }
  70047. };
  70048. CustomProceduralTexture.prototype.isReady = function () {
  70049. if (!_super.prototype.isReady.call(this)) {
  70050. return false;
  70051. }
  70052. for (var name in this._textures) {
  70053. var texture = this._textures[name];
  70054. if (!texture.isReady()) {
  70055. return false;
  70056. }
  70057. }
  70058. return true;
  70059. };
  70060. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70061. var scene = this.getScene();
  70062. if (this._animate && scene) {
  70063. this._time += scene.getAnimationRatio() * 0.03;
  70064. this.updateShaderUniforms();
  70065. }
  70066. _super.prototype.render.call(this, useCameraPostProcess);
  70067. };
  70068. CustomProceduralTexture.prototype.updateTextures = function () {
  70069. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70070. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70071. }
  70072. };
  70073. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70074. if (this._config) {
  70075. for (var j = 0; j < this._config.uniforms.length; j++) {
  70076. var uniform = this._config.uniforms[j];
  70077. switch (uniform.type) {
  70078. case "float":
  70079. this.setFloat(uniform.name, uniform.value);
  70080. break;
  70081. case "color3":
  70082. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70083. break;
  70084. case "color4":
  70085. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70086. break;
  70087. case "vector2":
  70088. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70089. break;
  70090. case "vector3":
  70091. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70092. break;
  70093. }
  70094. }
  70095. }
  70096. this.setFloat("time", this._time);
  70097. };
  70098. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70099. get: function () {
  70100. return this._animate;
  70101. },
  70102. set: function (value) {
  70103. this._animate = value;
  70104. },
  70105. enumerable: true,
  70106. configurable: true
  70107. });
  70108. return CustomProceduralTexture;
  70109. }(BABYLON.ProceduralTexture));
  70110. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70111. })(BABYLON || (BABYLON = {}));
  70112. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70113. var BABYLON;
  70114. (function (BABYLON) {
  70115. var FreeCameraGamepadInput = /** @class */ (function () {
  70116. function FreeCameraGamepadInput() {
  70117. this.gamepadAngularSensibility = 200;
  70118. this.gamepadMoveSensibility = 40;
  70119. // private members
  70120. this._cameraTransform = BABYLON.Matrix.Identity();
  70121. this._deltaTransform = BABYLON.Vector3.Zero();
  70122. this._vector3 = BABYLON.Vector3.Zero();
  70123. this._vector2 = BABYLON.Vector2.Zero();
  70124. }
  70125. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70126. var _this = this;
  70127. var manager = this.camera.getScene().gamepadManager;
  70128. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70129. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70130. // prioritize XBOX gamepads.
  70131. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70132. _this.gamepad = gamepad;
  70133. }
  70134. }
  70135. });
  70136. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70137. if (_this.gamepad === gamepad) {
  70138. _this.gamepad = null;
  70139. }
  70140. });
  70141. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70142. };
  70143. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70144. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70145. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70146. this.gamepad = null;
  70147. };
  70148. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70149. if (this.gamepad && this.gamepad.leftStick) {
  70150. var camera = this.camera;
  70151. var LSValues = this.gamepad.leftStick;
  70152. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70153. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70154. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70155. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70156. var RSValues = this.gamepad.rightStick;
  70157. if (RSValues) {
  70158. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70159. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70160. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70161. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70162. }
  70163. else {
  70164. RSValues = { x: 0, y: 0 };
  70165. }
  70166. if (!camera.rotationQuaternion) {
  70167. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70168. }
  70169. else {
  70170. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70171. }
  70172. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70173. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70174. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70175. camera.cameraDirection.addInPlace(this._deltaTransform);
  70176. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70177. camera.cameraRotation.addInPlace(this._vector2);
  70178. }
  70179. };
  70180. FreeCameraGamepadInput.prototype.getClassName = function () {
  70181. return "FreeCameraGamepadInput";
  70182. };
  70183. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70184. return "gamepad";
  70185. };
  70186. __decorate([
  70187. BABYLON.serialize()
  70188. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70189. __decorate([
  70190. BABYLON.serialize()
  70191. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70192. return FreeCameraGamepadInput;
  70193. }());
  70194. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70195. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70196. })(BABYLON || (BABYLON = {}));
  70197. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70198. var BABYLON;
  70199. (function (BABYLON) {
  70200. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70201. function ArcRotateCameraGamepadInput() {
  70202. this.gamepadRotationSensibility = 80;
  70203. this.gamepadMoveSensibility = 40;
  70204. }
  70205. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70206. var _this = this;
  70207. var manager = this.camera.getScene().gamepadManager;
  70208. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70209. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70210. // prioritize XBOX gamepads.
  70211. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70212. _this.gamepad = gamepad;
  70213. }
  70214. }
  70215. });
  70216. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70217. if (_this.gamepad === gamepad) {
  70218. _this.gamepad = null;
  70219. }
  70220. });
  70221. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70222. };
  70223. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70224. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70225. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70226. this.gamepad = null;
  70227. };
  70228. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70229. if (this.gamepad) {
  70230. var camera = this.camera;
  70231. var RSValues = this.gamepad.rightStick;
  70232. if (RSValues) {
  70233. if (RSValues.x != 0) {
  70234. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70235. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70236. camera.inertialAlphaOffset += normalizedRX;
  70237. }
  70238. }
  70239. if (RSValues.y != 0) {
  70240. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70241. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70242. camera.inertialBetaOffset += normalizedRY;
  70243. }
  70244. }
  70245. }
  70246. var LSValues = this.gamepad.leftStick;
  70247. if (LSValues && LSValues.y != 0) {
  70248. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70249. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70250. this.camera.inertialRadiusOffset -= normalizedLY;
  70251. }
  70252. }
  70253. }
  70254. };
  70255. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70256. return "ArcRotateCameraGamepadInput";
  70257. };
  70258. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70259. return "gamepad";
  70260. };
  70261. __decorate([
  70262. BABYLON.serialize()
  70263. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70264. __decorate([
  70265. BABYLON.serialize()
  70266. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70267. return ArcRotateCameraGamepadInput;
  70268. }());
  70269. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70270. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70271. })(BABYLON || (BABYLON = {}));
  70272. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70273. var BABYLON;
  70274. (function (BABYLON) {
  70275. var GamepadManager = /** @class */ (function () {
  70276. function GamepadManager(_scene) {
  70277. var _this = this;
  70278. this._scene = _scene;
  70279. this._babylonGamepads = [];
  70280. this._oneGamepadConnected = false;
  70281. this._isMonitoring = false;
  70282. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70283. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70284. this._gamepadEventSupported = false;
  70285. }
  70286. else {
  70287. this._gamepadEventSupported = 'GamepadEvent' in window;
  70288. this._gamepadSupport = (navigator.getGamepads ||
  70289. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70290. }
  70291. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70292. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70293. for (var i in _this._babylonGamepads) {
  70294. var gamepad = _this._babylonGamepads[i];
  70295. if (gamepad && gamepad._isConnected) {
  70296. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70297. }
  70298. }
  70299. });
  70300. this._onGamepadConnectedEvent = function (evt) {
  70301. var gamepad = evt.gamepad;
  70302. if (gamepad.index in _this._babylonGamepads) {
  70303. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70304. return;
  70305. }
  70306. }
  70307. var newGamepad;
  70308. if (_this._babylonGamepads[gamepad.index]) {
  70309. newGamepad = _this._babylonGamepads[gamepad.index];
  70310. newGamepad.browserGamepad = gamepad;
  70311. newGamepad._isConnected = true;
  70312. }
  70313. else {
  70314. newGamepad = _this._addNewGamepad(gamepad);
  70315. }
  70316. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70317. _this._startMonitoringGamepads();
  70318. };
  70319. this._onGamepadDisconnectedEvent = function (evt) {
  70320. var gamepad = evt.gamepad;
  70321. // Remove the gamepad from the list of gamepads to monitor.
  70322. for (var i in _this._babylonGamepads) {
  70323. if (_this._babylonGamepads[i].index === gamepad.index) {
  70324. var disconnectedGamepad = _this._babylonGamepads[i];
  70325. disconnectedGamepad._isConnected = false;
  70326. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70327. break;
  70328. }
  70329. }
  70330. };
  70331. if (this._gamepadSupport) {
  70332. //first add already-connected gamepads
  70333. this._updateGamepadObjects();
  70334. if (this._babylonGamepads.length) {
  70335. this._startMonitoringGamepads();
  70336. }
  70337. // Checking if the gamepad connected event is supported (like in Firefox)
  70338. if (this._gamepadEventSupported) {
  70339. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70340. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70341. }
  70342. else {
  70343. this._startMonitoringGamepads();
  70344. }
  70345. }
  70346. }
  70347. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70348. get: function () {
  70349. return this._babylonGamepads;
  70350. },
  70351. enumerable: true,
  70352. configurable: true
  70353. });
  70354. GamepadManager.prototype.getGamepadByType = function (type) {
  70355. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70356. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70357. var gamepad = _a[_i];
  70358. if (gamepad && gamepad.type === type) {
  70359. return gamepad;
  70360. }
  70361. }
  70362. return null;
  70363. };
  70364. GamepadManager.prototype.dispose = function () {
  70365. if (this._gamepadEventSupported) {
  70366. if (this._onGamepadConnectedEvent) {
  70367. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70368. }
  70369. if (this._onGamepadDisconnectedEvent) {
  70370. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70371. }
  70372. this._onGamepadConnectedEvent = null;
  70373. this._onGamepadDisconnectedEvent = null;
  70374. }
  70375. this._babylonGamepads.forEach(function (gamepad) {
  70376. gamepad.dispose();
  70377. });
  70378. this.onGamepadConnectedObservable.clear();
  70379. this.onGamepadDisconnectedObservable.clear();
  70380. this._oneGamepadConnected = false;
  70381. this._stopMonitoringGamepads();
  70382. this._babylonGamepads = [];
  70383. };
  70384. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70385. if (!this._oneGamepadConnected) {
  70386. this._oneGamepadConnected = true;
  70387. }
  70388. var newGamepad;
  70389. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70390. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70391. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70392. }
  70393. // if pose is supported, use the (WebVR) pose enabled controller
  70394. else if (gamepad.pose) {
  70395. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70396. }
  70397. else {
  70398. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70399. }
  70400. this._babylonGamepads[newGamepad.index] = newGamepad;
  70401. return newGamepad;
  70402. };
  70403. GamepadManager.prototype._startMonitoringGamepads = function () {
  70404. if (!this._isMonitoring) {
  70405. this._isMonitoring = true;
  70406. //back-comp
  70407. if (!this._scene) {
  70408. this._checkGamepadsStatus();
  70409. }
  70410. }
  70411. };
  70412. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70413. this._isMonitoring = false;
  70414. };
  70415. GamepadManager.prototype._checkGamepadsStatus = function () {
  70416. var _this = this;
  70417. // Hack to be compatible Chrome
  70418. this._updateGamepadObjects();
  70419. for (var i in this._babylonGamepads) {
  70420. var gamepad = this._babylonGamepads[i];
  70421. if (!gamepad || !gamepad.isConnected) {
  70422. continue;
  70423. }
  70424. gamepad.update();
  70425. }
  70426. if (this._isMonitoring && !this._scene) {
  70427. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70428. }
  70429. };
  70430. // This function is called only on Chrome, which does not properly support
  70431. // connection/disconnection events and forces you to recopy again the gamepad object
  70432. GamepadManager.prototype._updateGamepadObjects = function () {
  70433. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70434. for (var i = 0; i < gamepads.length; i++) {
  70435. var gamepad = gamepads[i];
  70436. if (gamepad) {
  70437. if (!this._babylonGamepads[gamepad.index]) {
  70438. var newGamepad = this._addNewGamepad(gamepad);
  70439. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70440. }
  70441. else {
  70442. // Forced to copy again this object for Chrome for unknown reason
  70443. this._babylonGamepads[i].browserGamepad = gamepad;
  70444. if (!this._babylonGamepads[i].isConnected) {
  70445. this._babylonGamepads[i]._isConnected = true;
  70446. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70447. }
  70448. }
  70449. }
  70450. }
  70451. };
  70452. return GamepadManager;
  70453. }());
  70454. BABYLON.GamepadManager = GamepadManager;
  70455. })(BABYLON || (BABYLON = {}));
  70456. //# sourceMappingURL=babylon.gamepadManager.js.map
  70457. var BABYLON;
  70458. (function (BABYLON) {
  70459. var StickValues = /** @class */ (function () {
  70460. function StickValues(x, y) {
  70461. this.x = x;
  70462. this.y = y;
  70463. }
  70464. return StickValues;
  70465. }());
  70466. BABYLON.StickValues = StickValues;
  70467. var Gamepad = /** @class */ (function () {
  70468. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70469. if (leftStickX === void 0) { leftStickX = 0; }
  70470. if (leftStickY === void 0) { leftStickY = 1; }
  70471. if (rightStickX === void 0) { rightStickX = 2; }
  70472. if (rightStickY === void 0) { rightStickY = 3; }
  70473. this.id = id;
  70474. this.index = index;
  70475. this.browserGamepad = browserGamepad;
  70476. this._isConnected = true;
  70477. this._invertLeftStickY = false;
  70478. this.type = Gamepad.GAMEPAD;
  70479. this._leftStickAxisX = leftStickX;
  70480. this._leftStickAxisY = leftStickY;
  70481. this._rightStickAxisX = rightStickX;
  70482. this._rightStickAxisY = rightStickY;
  70483. if (this.browserGamepad.axes.length >= 2) {
  70484. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70485. }
  70486. if (this.browserGamepad.axes.length >= 4) {
  70487. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70488. }
  70489. }
  70490. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70491. get: function () {
  70492. return this._isConnected;
  70493. },
  70494. enumerable: true,
  70495. configurable: true
  70496. });
  70497. Gamepad.prototype.onleftstickchanged = function (callback) {
  70498. this._onleftstickchanged = callback;
  70499. };
  70500. Gamepad.prototype.onrightstickchanged = function (callback) {
  70501. this._onrightstickchanged = callback;
  70502. };
  70503. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70504. get: function () {
  70505. return this._leftStick;
  70506. },
  70507. set: function (newValues) {
  70508. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70509. this._onleftstickchanged(newValues);
  70510. }
  70511. this._leftStick = newValues;
  70512. },
  70513. enumerable: true,
  70514. configurable: true
  70515. });
  70516. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70517. get: function () {
  70518. return this._rightStick;
  70519. },
  70520. set: function (newValues) {
  70521. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70522. this._onrightstickchanged(newValues);
  70523. }
  70524. this._rightStick = newValues;
  70525. },
  70526. enumerable: true,
  70527. configurable: true
  70528. });
  70529. Gamepad.prototype.update = function () {
  70530. if (this._leftStick) {
  70531. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70532. if (this._invertLeftStickY) {
  70533. this.leftStick.y *= -1;
  70534. }
  70535. }
  70536. if (this._rightStick) {
  70537. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70538. }
  70539. };
  70540. Gamepad.prototype.dispose = function () {
  70541. };
  70542. Gamepad.GAMEPAD = 0;
  70543. Gamepad.GENERIC = 1;
  70544. Gamepad.XBOX = 2;
  70545. Gamepad.POSE_ENABLED = 3;
  70546. return Gamepad;
  70547. }());
  70548. BABYLON.Gamepad = Gamepad;
  70549. var GenericPad = /** @class */ (function (_super) {
  70550. __extends(GenericPad, _super);
  70551. function GenericPad(id, index, browserGamepad) {
  70552. var _this = _super.call(this, id, index, browserGamepad) || this;
  70553. _this.onButtonDownObservable = new BABYLON.Observable();
  70554. _this.onButtonUpObservable = new BABYLON.Observable();
  70555. _this.type = Gamepad.GENERIC;
  70556. _this._buttons = new Array(browserGamepad.buttons.length);
  70557. return _this;
  70558. }
  70559. GenericPad.prototype.onbuttondown = function (callback) {
  70560. this._onbuttondown = callback;
  70561. };
  70562. GenericPad.prototype.onbuttonup = function (callback) {
  70563. this._onbuttonup = callback;
  70564. };
  70565. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70566. if (newValue !== currentValue) {
  70567. if (newValue === 1) {
  70568. if (this._onbuttondown) {
  70569. this._onbuttondown(buttonIndex);
  70570. }
  70571. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70572. }
  70573. if (newValue === 0) {
  70574. if (this._onbuttonup) {
  70575. this._onbuttonup(buttonIndex);
  70576. }
  70577. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70578. }
  70579. }
  70580. return newValue;
  70581. };
  70582. GenericPad.prototype.update = function () {
  70583. _super.prototype.update.call(this);
  70584. for (var index = 0; index < this._buttons.length; index++) {
  70585. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70586. }
  70587. };
  70588. GenericPad.prototype.dispose = function () {
  70589. _super.prototype.dispose.call(this);
  70590. this.onButtonDownObservable.clear();
  70591. this.onButtonUpObservable.clear();
  70592. };
  70593. return GenericPad;
  70594. }(Gamepad));
  70595. BABYLON.GenericPad = GenericPad;
  70596. })(BABYLON || (BABYLON = {}));
  70597. //# sourceMappingURL=babylon.gamepad.js.map
  70598. var BABYLON;
  70599. (function (BABYLON) {
  70600. /**
  70601. * Defines supported buttons for XBox360 compatible gamepads
  70602. */
  70603. var Xbox360Button;
  70604. (function (Xbox360Button) {
  70605. /** A */
  70606. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70607. /** B */
  70608. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70609. /** X */
  70610. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70611. /** Y */
  70612. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70613. /** Start */
  70614. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70615. /** Back */
  70616. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70617. /** Left button */
  70618. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70619. /** Right button */
  70620. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70621. /** Left stick */
  70622. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70623. /** Right stick */
  70624. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70625. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70626. /** Defines values for XBox360 DPad */
  70627. var Xbox360Dpad;
  70628. (function (Xbox360Dpad) {
  70629. /** Up */
  70630. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70631. /** Down */
  70632. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70633. /** Left */
  70634. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70635. /** Right */
  70636. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70637. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70638. /**
  70639. * Defines a XBox360 gamepad
  70640. */
  70641. var Xbox360Pad = /** @class */ (function (_super) {
  70642. __extends(Xbox360Pad, _super);
  70643. /**
  70644. * Creates a new XBox360 gamepad object
  70645. * @param id defines the id of this gamepad
  70646. * @param index defines its index
  70647. * @param gamepad defines the internal HTML gamepad object
  70648. * @param xboxOne defines if it is a XBox One gamepad
  70649. */
  70650. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70651. if (xboxOne === void 0) { xboxOne = false; }
  70652. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70653. _this._leftTrigger = 0;
  70654. _this._rightTrigger = 0;
  70655. /** Observable raised when a button is pressed */
  70656. _this.onButtonDownObservable = new BABYLON.Observable();
  70657. /** Observable raised when a button is released */
  70658. _this.onButtonUpObservable = new BABYLON.Observable();
  70659. /** Observable raised when a pad is pressed */
  70660. _this.onPadDownObservable = new BABYLON.Observable();
  70661. /** Observable raised when a pad is released */
  70662. _this.onPadUpObservable = new BABYLON.Observable();
  70663. _this._buttonA = 0;
  70664. _this._buttonB = 0;
  70665. _this._buttonX = 0;
  70666. _this._buttonY = 0;
  70667. _this._buttonBack = 0;
  70668. _this._buttonStart = 0;
  70669. _this._buttonLB = 0;
  70670. _this._buttonRB = 0;
  70671. _this._buttonLeftStick = 0;
  70672. _this._buttonRightStick = 0;
  70673. _this._dPadUp = 0;
  70674. _this._dPadDown = 0;
  70675. _this._dPadLeft = 0;
  70676. _this._dPadRight = 0;
  70677. _this._isXboxOnePad = false;
  70678. _this.type = BABYLON.Gamepad.XBOX;
  70679. _this._isXboxOnePad = xboxOne;
  70680. return _this;
  70681. }
  70682. /**
  70683. * Defines the callback to call when left trigger is pressed
  70684. * @param callback defines the callback to use
  70685. */
  70686. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70687. this._onlefttriggerchanged = callback;
  70688. };
  70689. /**
  70690. * Defines the callback to call when right trigger is pressed
  70691. * @param callback defines the callback to use
  70692. */
  70693. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70694. this._onrighttriggerchanged = callback;
  70695. };
  70696. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70697. /**
  70698. * Gets or sets left trigger value
  70699. */
  70700. get: function () {
  70701. return this._leftTrigger;
  70702. },
  70703. set: function (newValue) {
  70704. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70705. this._onlefttriggerchanged(newValue);
  70706. }
  70707. this._leftTrigger = newValue;
  70708. },
  70709. enumerable: true,
  70710. configurable: true
  70711. });
  70712. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70713. /**
  70714. * Gets or sets right trigger value
  70715. */
  70716. get: function () {
  70717. return this._rightTrigger;
  70718. },
  70719. set: function (newValue) {
  70720. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70721. this._onrighttriggerchanged(newValue);
  70722. }
  70723. this._rightTrigger = newValue;
  70724. },
  70725. enumerable: true,
  70726. configurable: true
  70727. });
  70728. /**
  70729. * Defines the callback to call when a button is pressed
  70730. * @param callback defines the callback to use
  70731. */
  70732. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70733. this._onbuttondown = callback;
  70734. };
  70735. /**
  70736. * Defines the callback to call when a button is released
  70737. * @param callback defines the callback to use
  70738. */
  70739. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70740. this._onbuttonup = callback;
  70741. };
  70742. /**
  70743. * Defines the callback to call when a pad is pressed
  70744. * @param callback defines the callback to use
  70745. */
  70746. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70747. this._ondpaddown = callback;
  70748. };
  70749. /**
  70750. * Defines the callback to call when a pad is released
  70751. * @param callback defines the callback to use
  70752. */
  70753. Xbox360Pad.prototype.ondpadup = function (callback) {
  70754. this._ondpadup = callback;
  70755. };
  70756. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70757. if (newValue !== currentValue) {
  70758. if (newValue === 1) {
  70759. if (this._onbuttondown) {
  70760. this._onbuttondown(buttonType);
  70761. }
  70762. this.onButtonDownObservable.notifyObservers(buttonType);
  70763. }
  70764. if (newValue === 0) {
  70765. if (this._onbuttonup) {
  70766. this._onbuttonup(buttonType);
  70767. }
  70768. this.onButtonUpObservable.notifyObservers(buttonType);
  70769. }
  70770. }
  70771. return newValue;
  70772. };
  70773. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70774. if (newValue !== currentValue) {
  70775. if (newValue === 1) {
  70776. if (this._ondpaddown) {
  70777. this._ondpaddown(buttonType);
  70778. }
  70779. this.onPadDownObservable.notifyObservers(buttonType);
  70780. }
  70781. if (newValue === 0) {
  70782. if (this._ondpadup) {
  70783. this._ondpadup(buttonType);
  70784. }
  70785. this.onPadUpObservable.notifyObservers(buttonType);
  70786. }
  70787. }
  70788. return newValue;
  70789. };
  70790. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70791. /** Gets or sets value of A button */
  70792. get: function () {
  70793. return this._buttonA;
  70794. },
  70795. set: function (value) {
  70796. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70797. },
  70798. enumerable: true,
  70799. configurable: true
  70800. });
  70801. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70802. /** Gets or sets value of B button */
  70803. get: function () {
  70804. return this._buttonB;
  70805. },
  70806. set: function (value) {
  70807. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70808. },
  70809. enumerable: true,
  70810. configurable: true
  70811. });
  70812. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70813. /** Gets or sets value of X button */
  70814. get: function () {
  70815. return this._buttonX;
  70816. },
  70817. set: function (value) {
  70818. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70819. },
  70820. enumerable: true,
  70821. configurable: true
  70822. });
  70823. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70824. /** Gets or sets value of Y button */
  70825. get: function () {
  70826. return this._buttonY;
  70827. },
  70828. set: function (value) {
  70829. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70830. },
  70831. enumerable: true,
  70832. configurable: true
  70833. });
  70834. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70835. /** Gets or sets value of Start button */
  70836. get: function () {
  70837. return this._buttonStart;
  70838. },
  70839. set: function (value) {
  70840. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70841. },
  70842. enumerable: true,
  70843. configurable: true
  70844. });
  70845. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70846. /** Gets or sets value of Back button */
  70847. get: function () {
  70848. return this._buttonBack;
  70849. },
  70850. set: function (value) {
  70851. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70852. },
  70853. enumerable: true,
  70854. configurable: true
  70855. });
  70856. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70857. /** Gets or sets value of Left button */
  70858. get: function () {
  70859. return this._buttonLB;
  70860. },
  70861. set: function (value) {
  70862. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70863. },
  70864. enumerable: true,
  70865. configurable: true
  70866. });
  70867. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70868. /** Gets or sets value of Right button */
  70869. get: function () {
  70870. return this._buttonRB;
  70871. },
  70872. set: function (value) {
  70873. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70874. },
  70875. enumerable: true,
  70876. configurable: true
  70877. });
  70878. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70879. /** Gets or sets value of left stick */
  70880. get: function () {
  70881. return this._buttonLeftStick;
  70882. },
  70883. set: function (value) {
  70884. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70885. },
  70886. enumerable: true,
  70887. configurable: true
  70888. });
  70889. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70890. /** Gets or sets value of right stick */
  70891. get: function () {
  70892. return this._buttonRightStick;
  70893. },
  70894. set: function (value) {
  70895. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70896. },
  70897. enumerable: true,
  70898. configurable: true
  70899. });
  70900. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70901. /** Gets or sets value of DPad up */
  70902. get: function () {
  70903. return this._dPadUp;
  70904. },
  70905. set: function (value) {
  70906. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70907. },
  70908. enumerable: true,
  70909. configurable: true
  70910. });
  70911. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70912. /** Gets or sets value of DPad down */
  70913. get: function () {
  70914. return this._dPadDown;
  70915. },
  70916. set: function (value) {
  70917. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70918. },
  70919. enumerable: true,
  70920. configurable: true
  70921. });
  70922. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70923. /** Gets or sets value of DPad left */
  70924. get: function () {
  70925. return this._dPadLeft;
  70926. },
  70927. set: function (value) {
  70928. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70929. },
  70930. enumerable: true,
  70931. configurable: true
  70932. });
  70933. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70934. /** Gets or sets value of DPad right */
  70935. get: function () {
  70936. return this._dPadRight;
  70937. },
  70938. set: function (value) {
  70939. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70940. },
  70941. enumerable: true,
  70942. configurable: true
  70943. });
  70944. /**
  70945. * Force the gamepad to synchronize with device values
  70946. */
  70947. Xbox360Pad.prototype.update = function () {
  70948. _super.prototype.update.call(this);
  70949. if (this._isXboxOnePad) {
  70950. this.buttonA = this.browserGamepad.buttons[0].value;
  70951. this.buttonB = this.browserGamepad.buttons[1].value;
  70952. this.buttonX = this.browserGamepad.buttons[2].value;
  70953. this.buttonY = this.browserGamepad.buttons[3].value;
  70954. this.buttonLB = this.browserGamepad.buttons[4].value;
  70955. this.buttonRB = this.browserGamepad.buttons[5].value;
  70956. this.leftTrigger = this.browserGamepad.axes[2];
  70957. this.rightTrigger = this.browserGamepad.axes[5];
  70958. this.buttonBack = this.browserGamepad.buttons[9].value;
  70959. this.buttonStart = this.browserGamepad.buttons[8].value;
  70960. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70961. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70962. this.dPadUp = this.browserGamepad.buttons[11].value;
  70963. this.dPadDown = this.browserGamepad.buttons[12].value;
  70964. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70965. this.dPadRight = this.browserGamepad.buttons[14].value;
  70966. }
  70967. else {
  70968. this.buttonA = this.browserGamepad.buttons[0].value;
  70969. this.buttonB = this.browserGamepad.buttons[1].value;
  70970. this.buttonX = this.browserGamepad.buttons[2].value;
  70971. this.buttonY = this.browserGamepad.buttons[3].value;
  70972. this.buttonLB = this.browserGamepad.buttons[4].value;
  70973. this.buttonRB = this.browserGamepad.buttons[5].value;
  70974. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70975. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70976. this.buttonBack = this.browserGamepad.buttons[8].value;
  70977. this.buttonStart = this.browserGamepad.buttons[9].value;
  70978. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70979. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70980. this.dPadUp = this.browserGamepad.buttons[12].value;
  70981. this.dPadDown = this.browserGamepad.buttons[13].value;
  70982. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70983. this.dPadRight = this.browserGamepad.buttons[15].value;
  70984. }
  70985. };
  70986. Xbox360Pad.prototype.dispose = function () {
  70987. _super.prototype.dispose.call(this);
  70988. this.onButtonDownObservable.clear();
  70989. this.onButtonUpObservable.clear();
  70990. this.onPadDownObservable.clear();
  70991. this.onPadUpObservable.clear();
  70992. };
  70993. return Xbox360Pad;
  70994. }(BABYLON.Gamepad));
  70995. BABYLON.Xbox360Pad = Xbox360Pad;
  70996. })(BABYLON || (BABYLON = {}));
  70997. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70998. var BABYLON;
  70999. (function (BABYLON) {
  71000. /**
  71001. * Defines the types of pose enabled controllers that are supported
  71002. */
  71003. var PoseEnabledControllerType;
  71004. (function (PoseEnabledControllerType) {
  71005. /**
  71006. * HTC Vive
  71007. */
  71008. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71009. /**
  71010. * Oculus Rift
  71011. */
  71012. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71013. /**
  71014. * Windows mixed reality
  71015. */
  71016. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71017. /**
  71018. * Samsung gear VR
  71019. */
  71020. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71021. /**
  71022. * Google Daydream
  71023. */
  71024. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71025. /**
  71026. * Generic
  71027. */
  71028. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71029. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71030. /**
  71031. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71032. */
  71033. var PoseEnabledControllerHelper = /** @class */ (function () {
  71034. function PoseEnabledControllerHelper() {
  71035. }
  71036. /**
  71037. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71038. * @param vrGamepad the gamepad to initialized
  71039. * @returns a vr controller of the type the gamepad identified as
  71040. */
  71041. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71042. // Oculus Touch
  71043. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71044. return new BABYLON.OculusTouchController(vrGamepad);
  71045. }
  71046. // Windows Mixed Reality controllers
  71047. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71048. return new BABYLON.WindowsMotionController(vrGamepad);
  71049. }
  71050. // HTC Vive
  71051. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71052. return new BABYLON.ViveController(vrGamepad);
  71053. }
  71054. // Samsung/Oculus Gear VR or Oculus Go
  71055. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71056. return new BABYLON.GearVRController(vrGamepad);
  71057. }
  71058. // Google Daydream
  71059. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71060. return new BABYLON.DaydreamController(vrGamepad);
  71061. }
  71062. // Generic
  71063. else {
  71064. return new BABYLON.GenericController(vrGamepad);
  71065. }
  71066. };
  71067. return PoseEnabledControllerHelper;
  71068. }());
  71069. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71070. /**
  71071. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71072. */
  71073. var PoseEnabledController = /** @class */ (function (_super) {
  71074. __extends(PoseEnabledController, _super);
  71075. /**
  71076. * Creates a new PoseEnabledController from a gamepad
  71077. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71078. */
  71079. function PoseEnabledController(browserGamepad) {
  71080. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71081. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71082. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71083. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71084. /**
  71085. * The device position in babylon space
  71086. */
  71087. _this.devicePosition = BABYLON.Vector3.Zero();
  71088. /**
  71089. * The device rotation in babylon space
  71090. */
  71091. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71092. /**
  71093. * The scale factor of the device in babylon space
  71094. */
  71095. _this.deviceScaleFactor = 1;
  71096. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71097. /**
  71098. * Internal, matrix used to convert room space to babylon space
  71099. */
  71100. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71101. /**
  71102. * Node to be used when casting a ray from the controller
  71103. */
  71104. _this._pointingPoseNode = null;
  71105. _this._workingMatrix = BABYLON.Matrix.Identity();
  71106. /**
  71107. * @hidden
  71108. */
  71109. _this._meshAttachedObservable = new BABYLON.Observable();
  71110. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71111. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71112. _this.position = BABYLON.Vector3.Zero();
  71113. _this.rotationQuaternion = new BABYLON.Quaternion();
  71114. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71115. _this._calculatedRotation = new BABYLON.Quaternion();
  71116. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71117. return _this;
  71118. }
  71119. /**
  71120. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71121. */
  71122. PoseEnabledController.prototype.update = function () {
  71123. _super.prototype.update.call(this);
  71124. var pose = this.browserGamepad.pose;
  71125. this.updateFromDevice(pose);
  71126. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71127. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71128. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71129. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71130. if (this._mesh) {
  71131. this._mesh.position.copyFrom(this.devicePosition);
  71132. if (this._mesh.rotationQuaternion) {
  71133. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71134. }
  71135. }
  71136. };
  71137. /**
  71138. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71139. * @param poseData raw pose fromthe device
  71140. */
  71141. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71142. if (poseData) {
  71143. this.rawPose = poseData;
  71144. if (poseData.position) {
  71145. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71146. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71147. this._deviceRoomPosition.z *= -1;
  71148. }
  71149. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71150. this._calculatedPosition.addInPlace(this.position);
  71151. }
  71152. var pose = this.rawPose;
  71153. if (poseData.orientation && pose.orientation) {
  71154. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71155. if (this._mesh) {
  71156. if (this._mesh.getScene().useRightHandedSystem) {
  71157. this._deviceRoomRotationQuaternion.z *= -1;
  71158. this._deviceRoomRotationQuaternion.w *= -1;
  71159. }
  71160. else {
  71161. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71162. }
  71163. }
  71164. // if the camera is set, rotate to the camera's rotation
  71165. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71166. }
  71167. }
  71168. };
  71169. /**
  71170. * Attaches a mesh to the controller
  71171. * @param mesh the mesh to be attached
  71172. */
  71173. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71174. if (this._mesh) {
  71175. this._mesh.parent = null;
  71176. }
  71177. this._mesh = mesh;
  71178. if (this._poseControlledCamera) {
  71179. this._mesh.parent = this._poseControlledCamera;
  71180. }
  71181. if (!this._mesh.rotationQuaternion) {
  71182. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71183. }
  71184. // Sync controller mesh and pointing pose node's state with controller
  71185. this.update();
  71186. if (this._pointingPoseNode) {
  71187. var parents = [];
  71188. var obj = this._pointingPoseNode;
  71189. while (obj.parent) {
  71190. parents.push(obj.parent);
  71191. obj = obj.parent;
  71192. }
  71193. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71194. }
  71195. this._meshAttachedObservable.notifyObservers(mesh);
  71196. };
  71197. /**
  71198. * Attaches the controllers mesh to a camera
  71199. * @param camera the camera the mesh should be attached to
  71200. */
  71201. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71202. this._poseControlledCamera = camera;
  71203. if (this._mesh) {
  71204. this._mesh.parent = this._poseControlledCamera;
  71205. }
  71206. };
  71207. /**
  71208. * Disposes of the controller
  71209. */
  71210. PoseEnabledController.prototype.dispose = function () {
  71211. if (this._mesh) {
  71212. this._mesh.dispose();
  71213. }
  71214. this._mesh = null;
  71215. _super.prototype.dispose.call(this);
  71216. };
  71217. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71218. /**
  71219. * The mesh that is attached to the controller
  71220. */
  71221. get: function () {
  71222. return this._mesh;
  71223. },
  71224. enumerable: true,
  71225. configurable: true
  71226. });
  71227. /**
  71228. * Gets the ray of the controller in the direction the controller is pointing
  71229. * @param length the length the resulting ray should be
  71230. * @returns a ray in the direction the controller is pointing
  71231. */
  71232. PoseEnabledController.prototype.getForwardRay = function (length) {
  71233. if (length === void 0) { length = 100; }
  71234. if (!this.mesh) {
  71235. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71236. }
  71237. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71238. var origin = m.getTranslation();
  71239. var forward = new BABYLON.Vector3(0, 0, -1);
  71240. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71241. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71242. return new BABYLON.Ray(origin, direction, length);
  71243. };
  71244. /**
  71245. * Name of the child mesh that can be used to cast a ray from the controller
  71246. */
  71247. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71248. return PoseEnabledController;
  71249. }(BABYLON.Gamepad));
  71250. BABYLON.PoseEnabledController = PoseEnabledController;
  71251. })(BABYLON || (BABYLON = {}));
  71252. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71253. var BABYLON;
  71254. (function (BABYLON) {
  71255. /**
  71256. * Defines the WebVRController object that represents controllers tracked in 3D space
  71257. */
  71258. var WebVRController = /** @class */ (function (_super) {
  71259. __extends(WebVRController, _super);
  71260. /**
  71261. * Creates a new WebVRController from a gamepad
  71262. * @param vrGamepad the gamepad that the WebVRController should be created from
  71263. */
  71264. function WebVRController(vrGamepad) {
  71265. var _this = _super.call(this, vrGamepad) || this;
  71266. // Observables
  71267. /**
  71268. * Fired when the trigger state has changed
  71269. */
  71270. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71271. /**
  71272. * Fired when the main button state has changed
  71273. */
  71274. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71275. /**
  71276. * Fired when the secondary button state has changed
  71277. */
  71278. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71279. /**
  71280. * Fired when the pad state has changed
  71281. */
  71282. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71283. /**
  71284. * Fired when controllers stick values have changed
  71285. */
  71286. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71287. /**
  71288. * X and Y axis corrisponding to the controllers joystick
  71289. */
  71290. _this.pad = { x: 0, y: 0 };
  71291. // avoid GC, store state in a tmp object
  71292. _this._changes = {
  71293. pressChanged: false,
  71294. touchChanged: false,
  71295. valueChanged: false,
  71296. changed: false
  71297. };
  71298. _this._buttons = new Array(vrGamepad.buttons.length);
  71299. _this.hand = vrGamepad.hand;
  71300. return _this;
  71301. }
  71302. /**
  71303. * Fired when a controller button's state has changed
  71304. * @param callback the callback containing the button that was modified
  71305. */
  71306. WebVRController.prototype.onButtonStateChange = function (callback) {
  71307. this._onButtonStateChange = callback;
  71308. };
  71309. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71310. /**
  71311. * The default controller model for the controller
  71312. */
  71313. get: function () {
  71314. return this._defaultModel;
  71315. },
  71316. enumerable: true,
  71317. configurable: true
  71318. });
  71319. /**
  71320. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71321. */
  71322. WebVRController.prototype.update = function () {
  71323. _super.prototype.update.call(this);
  71324. for (var index = 0; index < this._buttons.length; index++) {
  71325. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71326. }
  71327. ;
  71328. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71329. this.pad.x = this.leftStick.x;
  71330. this.pad.y = this.leftStick.y;
  71331. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71332. }
  71333. };
  71334. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71335. if (!newState) {
  71336. newState = {
  71337. pressed: false,
  71338. touched: false,
  71339. value: 0
  71340. };
  71341. }
  71342. if (!currentState) {
  71343. this._buttons[buttonIndex] = {
  71344. pressed: newState.pressed,
  71345. touched: newState.touched,
  71346. value: newState.value
  71347. };
  71348. return;
  71349. }
  71350. this._checkChanges(newState, currentState);
  71351. if (this._changes.changed) {
  71352. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71353. this._handleButtonChange(buttonIndex, newState, this._changes);
  71354. }
  71355. this._buttons[buttonIndex].pressed = newState.pressed;
  71356. this._buttons[buttonIndex].touched = newState.touched;
  71357. // oculus triggers are never 0, thou not touched.
  71358. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71359. };
  71360. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71361. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71362. this._changes.touchChanged = newState.touched !== currentState.touched;
  71363. this._changes.valueChanged = newState.value !== currentState.value;
  71364. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71365. return this._changes;
  71366. };
  71367. /**
  71368. * Disposes of th webVRCOntroller
  71369. */
  71370. WebVRController.prototype.dispose = function () {
  71371. _super.prototype.dispose.call(this);
  71372. this.onTriggerStateChangedObservable.clear();
  71373. this.onMainButtonStateChangedObservable.clear();
  71374. this.onSecondaryButtonStateChangedObservable.clear();
  71375. this.onPadStateChangedObservable.clear();
  71376. this.onPadValuesChangedObservable.clear();
  71377. };
  71378. return WebVRController;
  71379. }(BABYLON.PoseEnabledController));
  71380. BABYLON.WebVRController = WebVRController;
  71381. })(BABYLON || (BABYLON = {}));
  71382. //# sourceMappingURL=babylon.webVRController.js.map
  71383. var BABYLON;
  71384. (function (BABYLON) {
  71385. /**
  71386. * Oculus Touch Controller
  71387. */
  71388. var OculusTouchController = /** @class */ (function (_super) {
  71389. __extends(OculusTouchController, _super);
  71390. /**
  71391. * Creates a new OculusTouchController from a gamepad
  71392. * @param vrGamepad the gamepad that the controller should be created from
  71393. */
  71394. function OculusTouchController(vrGamepad) {
  71395. var _this = _super.call(this, vrGamepad) || this;
  71396. /**
  71397. * Fired when the secondary trigger on this controller is modified
  71398. */
  71399. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71400. /**
  71401. * Fired when the thumb rest on this controller is modified
  71402. */
  71403. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71404. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71405. return _this;
  71406. }
  71407. /**
  71408. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71409. * @param scene scene in which to add meshes
  71410. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71411. */
  71412. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71413. var _this = this;
  71414. var meshName;
  71415. // Hand
  71416. if (this.hand === 'left') {
  71417. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71418. }
  71419. else { // Right is the default if no hand is specified
  71420. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71421. }
  71422. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71423. /*
  71424. Parent Mesh name: oculus_touch_left
  71425. - body
  71426. - trigger
  71427. - thumbstick
  71428. - grip
  71429. - button_y
  71430. - button_x
  71431. - button_enter
  71432. */
  71433. _this._defaultModel = newMeshes[1];
  71434. _this.attachToMesh(_this._defaultModel);
  71435. if (meshLoaded) {
  71436. meshLoaded(_this._defaultModel);
  71437. }
  71438. });
  71439. };
  71440. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71441. /**
  71442. * Fired when the A button on this controller is modified
  71443. */
  71444. get: function () {
  71445. if (this.hand === 'right') {
  71446. return this.onMainButtonStateChangedObservable;
  71447. }
  71448. else {
  71449. throw new Error('No A button on left hand');
  71450. }
  71451. },
  71452. enumerable: true,
  71453. configurable: true
  71454. });
  71455. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71456. /**
  71457. * Fired when the B button on this controller is modified
  71458. */
  71459. get: function () {
  71460. if (this.hand === 'right') {
  71461. return this.onSecondaryButtonStateChangedObservable;
  71462. }
  71463. else {
  71464. throw new Error('No B button on left hand');
  71465. }
  71466. },
  71467. enumerable: true,
  71468. configurable: true
  71469. });
  71470. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71471. /**
  71472. * Fired when the X button on this controller is modified
  71473. */
  71474. get: function () {
  71475. if (this.hand === 'left') {
  71476. return this.onMainButtonStateChangedObservable;
  71477. }
  71478. else {
  71479. throw new Error('No X button on right hand');
  71480. }
  71481. },
  71482. enumerable: true,
  71483. configurable: true
  71484. });
  71485. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71486. /**
  71487. * Fired when the Y button on this controller is modified
  71488. */
  71489. get: function () {
  71490. if (this.hand === 'left') {
  71491. return this.onSecondaryButtonStateChangedObservable;
  71492. }
  71493. else {
  71494. throw new Error('No Y button on right hand');
  71495. }
  71496. },
  71497. enumerable: true,
  71498. configurable: true
  71499. });
  71500. /**
  71501. * Called once for each button that changed state since the last frame
  71502. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71503. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71504. * 2) secondary trigger (same)
  71505. * 3) A (right) X (left), touch, pressed = value
  71506. * 4) B / Y
  71507. * 5) thumb rest
  71508. * @param buttonIdx Which button index changed
  71509. * @param state New state of the button
  71510. * @param changes Which properties on the state changed since last frame
  71511. */
  71512. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71513. var notifyObject = state; //{ state: state, changes: changes };
  71514. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71515. switch (buttonIdx) {
  71516. case 0:
  71517. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71518. return;
  71519. case 1: // index trigger
  71520. if (this._defaultModel) {
  71521. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71522. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71523. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71524. }
  71525. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71526. return;
  71527. case 2: // secondary trigger
  71528. if (this._defaultModel) {
  71529. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71530. }
  71531. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71532. return;
  71533. case 3:
  71534. if (this._defaultModel) {
  71535. if (notifyObject.pressed) {
  71536. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71537. }
  71538. else {
  71539. (this._defaultModel.getChildren()[1]).position.y = 0;
  71540. }
  71541. }
  71542. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71543. return;
  71544. case 4:
  71545. if (this._defaultModel) {
  71546. if (notifyObject.pressed) {
  71547. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71548. }
  71549. else {
  71550. (this._defaultModel.getChildren()[2]).position.y = 0;
  71551. }
  71552. }
  71553. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71554. return;
  71555. case 5:
  71556. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71557. return;
  71558. }
  71559. };
  71560. /**
  71561. * Base Url for the controller model.
  71562. */
  71563. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71564. /**
  71565. * File name for the left controller model.
  71566. */
  71567. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71568. /**
  71569. * File name for the right controller model.
  71570. */
  71571. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71572. return OculusTouchController;
  71573. }(BABYLON.WebVRController));
  71574. BABYLON.OculusTouchController = OculusTouchController;
  71575. })(BABYLON || (BABYLON = {}));
  71576. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71577. var BABYLON;
  71578. (function (BABYLON) {
  71579. /**
  71580. * Vive Controller
  71581. */
  71582. var ViveController = /** @class */ (function (_super) {
  71583. __extends(ViveController, _super);
  71584. /**
  71585. * Creates a new ViveController from a gamepad
  71586. * @param vrGamepad the gamepad that the controller should be created from
  71587. */
  71588. function ViveController(vrGamepad) {
  71589. var _this = _super.call(this, vrGamepad) || this;
  71590. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71591. _this._invertLeftStickY = true;
  71592. return _this;
  71593. }
  71594. /**
  71595. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71596. * @param scene scene in which to add meshes
  71597. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71598. */
  71599. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71600. var _this = this;
  71601. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71602. /*
  71603. Parent Mesh name: ViveWand
  71604. - body
  71605. - r_gripper
  71606. - l_gripper
  71607. - menu_button
  71608. - system_button
  71609. - trackpad
  71610. - trigger
  71611. - LED
  71612. */
  71613. _this._defaultModel = newMeshes[1];
  71614. _this.attachToMesh(_this._defaultModel);
  71615. if (meshLoaded) {
  71616. meshLoaded(_this._defaultModel);
  71617. }
  71618. });
  71619. };
  71620. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71621. /**
  71622. * Fired when the left button on this controller is modified
  71623. */
  71624. get: function () {
  71625. return this.onMainButtonStateChangedObservable;
  71626. },
  71627. enumerable: true,
  71628. configurable: true
  71629. });
  71630. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71631. /**
  71632. * Fired when the right button on this controller is modified
  71633. */
  71634. get: function () {
  71635. return this.onMainButtonStateChangedObservable;
  71636. },
  71637. enumerable: true,
  71638. configurable: true
  71639. });
  71640. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71641. /**
  71642. * Fired when the menu button on this controller is modified
  71643. */
  71644. get: function () {
  71645. return this.onSecondaryButtonStateChangedObservable;
  71646. },
  71647. enumerable: true,
  71648. configurable: true
  71649. });
  71650. /**
  71651. * Called once for each button that changed state since the last frame
  71652. * Vive mapping:
  71653. * 0: touchpad
  71654. * 1: trigger
  71655. * 2: left AND right buttons
  71656. * 3: menu button
  71657. * @param buttonIdx Which button index changed
  71658. * @param state New state of the button
  71659. * @param changes Which properties on the state changed since last frame
  71660. */
  71661. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71662. var notifyObject = state; //{ state: state, changes: changes };
  71663. switch (buttonIdx) {
  71664. case 0:
  71665. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71666. return;
  71667. case 1: // index trigger
  71668. if (this._defaultModel) {
  71669. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71670. }
  71671. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71672. return;
  71673. case 2: // left AND right button
  71674. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71675. return;
  71676. case 3:
  71677. if (this._defaultModel) {
  71678. if (notifyObject.pressed) {
  71679. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71680. }
  71681. else {
  71682. (this._defaultModel.getChildren()[2]).position.y = 0;
  71683. }
  71684. }
  71685. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71686. return;
  71687. }
  71688. };
  71689. /**
  71690. * Base Url for the controller model.
  71691. */
  71692. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71693. /**
  71694. * File name for the controller model.
  71695. */
  71696. ViveController.MODEL_FILENAME = 'wand.babylon';
  71697. return ViveController;
  71698. }(BABYLON.WebVRController));
  71699. BABYLON.ViveController = ViveController;
  71700. })(BABYLON || (BABYLON = {}));
  71701. //# sourceMappingURL=babylon.viveController.js.map
  71702. var BABYLON;
  71703. (function (BABYLON) {
  71704. /**
  71705. * Generic Controller
  71706. */
  71707. var GenericController = /** @class */ (function (_super) {
  71708. __extends(GenericController, _super);
  71709. /**
  71710. * Creates a new GenericController from a gamepad
  71711. * @param vrGamepad the gamepad that the controller should be created from
  71712. */
  71713. function GenericController(vrGamepad) {
  71714. return _super.call(this, vrGamepad) || this;
  71715. }
  71716. /**
  71717. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71718. * @param scene scene in which to add meshes
  71719. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71720. */
  71721. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71722. var _this = this;
  71723. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71724. _this._defaultModel = newMeshes[1];
  71725. _this.attachToMesh(_this._defaultModel);
  71726. if (meshLoaded) {
  71727. meshLoaded(_this._defaultModel);
  71728. }
  71729. });
  71730. };
  71731. /**
  71732. * Called once for each button that changed state since the last frame
  71733. * @param buttonIdx Which button index changed
  71734. * @param state New state of the button
  71735. * @param changes Which properties on the state changed since last frame
  71736. */
  71737. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71738. console.log("Button id: " + buttonIdx + "state: ");
  71739. console.dir(state);
  71740. };
  71741. /**
  71742. * Base Url for the controller model.
  71743. */
  71744. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71745. /**
  71746. * File name for the controller model.
  71747. */
  71748. GenericController.MODEL_FILENAME = 'generic.babylon';
  71749. return GenericController;
  71750. }(BABYLON.WebVRController));
  71751. BABYLON.GenericController = GenericController;
  71752. })(BABYLON || (BABYLON = {}));
  71753. //# sourceMappingURL=babylon.genericController.js.map
  71754. var BABYLON;
  71755. (function (BABYLON) {
  71756. /**
  71757. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71758. */
  71759. var LoadedMeshInfo = /** @class */ (function () {
  71760. function LoadedMeshInfo() {
  71761. /**
  71762. * Map of the button meshes contained in the controller
  71763. */
  71764. this.buttonMeshes = {};
  71765. /**
  71766. * Map of the axis meshes contained in the controller
  71767. */
  71768. this.axisMeshes = {};
  71769. }
  71770. return LoadedMeshInfo;
  71771. }());
  71772. /**
  71773. * Defines the WindowsMotionController object that the state of the windows motion controller
  71774. */
  71775. var WindowsMotionController = /** @class */ (function (_super) {
  71776. __extends(WindowsMotionController, _super);
  71777. /**
  71778. * Creates a new WindowsMotionController from a gamepad
  71779. * @param vrGamepad the gamepad that the controller should be created from
  71780. */
  71781. function WindowsMotionController(vrGamepad) {
  71782. var _this = _super.call(this, vrGamepad) || this;
  71783. _this._mapping = {
  71784. // Semantic button names
  71785. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71786. // A mapping of the button name to glTF model node name
  71787. // that should be transformed by button value.
  71788. buttonMeshNames: {
  71789. 'trigger': 'SELECT',
  71790. 'menu': 'MENU',
  71791. 'grip': 'GRASP',
  71792. 'thumbstick': 'THUMBSTICK_PRESS',
  71793. 'trackpad': 'TOUCHPAD_PRESS'
  71794. },
  71795. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71796. buttonObservableNames: {
  71797. 'trigger': 'onTriggerStateChangedObservable',
  71798. 'menu': 'onSecondaryButtonStateChangedObservable',
  71799. 'grip': 'onMainButtonStateChangedObservable',
  71800. 'thumbstick': 'onPadStateChangedObservable',
  71801. 'trackpad': 'onTrackpadChangedObservable'
  71802. },
  71803. // A mapping of the axis name to glTF model node name
  71804. // that should be transformed by axis value.
  71805. // This array mirrors the browserGamepad.axes array, such that
  71806. // the mesh corresponding to axis 0 is in this array index 0.
  71807. axisMeshNames: [
  71808. 'THUMBSTICK_X',
  71809. 'THUMBSTICK_Y',
  71810. 'TOUCHPAD_TOUCH_X',
  71811. 'TOUCHPAD_TOUCH_Y'
  71812. ],
  71813. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71814. };
  71815. /**
  71816. * Fired when the trackpad on this controller is clicked
  71817. */
  71818. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71819. /**
  71820. * Fired when the trackpad on this controller is modified
  71821. */
  71822. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71823. /**
  71824. * The current x and y values of this controller's trackpad
  71825. */
  71826. _this.trackpad = { x: 0, y: 0 };
  71827. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71828. _this._loadedMeshInfo = null;
  71829. return _this;
  71830. }
  71831. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71832. /**
  71833. * Fired when the trigger on this controller is modified
  71834. */
  71835. get: function () {
  71836. return this.onTriggerStateChangedObservable;
  71837. },
  71838. enumerable: true,
  71839. configurable: true
  71840. });
  71841. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71842. /**
  71843. * Fired when the menu button on this controller is modified
  71844. */
  71845. get: function () {
  71846. return this.onSecondaryButtonStateChangedObservable;
  71847. },
  71848. enumerable: true,
  71849. configurable: true
  71850. });
  71851. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71852. /**
  71853. * Fired when the grip button on this controller is modified
  71854. */
  71855. get: function () {
  71856. return this.onMainButtonStateChangedObservable;
  71857. },
  71858. enumerable: true,
  71859. configurable: true
  71860. });
  71861. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71862. /**
  71863. * Fired when the thumbstick button on this controller is modified
  71864. */
  71865. get: function () {
  71866. return this.onPadStateChangedObservable;
  71867. },
  71868. enumerable: true,
  71869. configurable: true
  71870. });
  71871. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71872. /**
  71873. * Fired when the touchpad button on this controller is modified
  71874. */
  71875. get: function () {
  71876. return this.onTrackpadChangedObservable;
  71877. },
  71878. enumerable: true,
  71879. configurable: true
  71880. });
  71881. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71882. /**
  71883. * Fired when the touchpad values on this controller are modified
  71884. */
  71885. get: function () {
  71886. return this.onTrackpadValuesChangedObservable;
  71887. },
  71888. enumerable: true,
  71889. configurable: true
  71890. });
  71891. WindowsMotionController.prototype._updateTrackpad = function () {
  71892. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71893. this.trackpad.x = this.browserGamepad["axes"][2];
  71894. this.trackpad.y = this.browserGamepad["axes"][3];
  71895. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71896. }
  71897. };
  71898. /**
  71899. * Called once per frame by the engine.
  71900. */
  71901. WindowsMotionController.prototype.update = function () {
  71902. _super.prototype.update.call(this);
  71903. if (this.browserGamepad.axes) {
  71904. this._updateTrackpad();
  71905. // Only need to animate axes if there is a loaded mesh
  71906. if (this._loadedMeshInfo) {
  71907. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71908. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71909. }
  71910. }
  71911. }
  71912. };
  71913. /**
  71914. * Called once for each button that changed state since the last frame
  71915. * @param buttonIdx Which button index changed
  71916. * @param state New state of the button
  71917. * @param changes Which properties on the state changed since last frame
  71918. */
  71919. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71920. var buttonName = this._mapping.buttons[buttonIdx];
  71921. if (!buttonName) {
  71922. return;
  71923. }
  71924. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71925. this._updateTrackpad();
  71926. // Only emit events for buttons that we know how to map from index to name
  71927. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71928. if (observable) {
  71929. observable.notifyObservers(state);
  71930. }
  71931. this._lerpButtonTransform(buttonName, state.value);
  71932. };
  71933. /**
  71934. * Moves the buttons on the controller mesh based on their current state
  71935. * @param buttonName the name of the button to move
  71936. * @param buttonValue the value of the button which determines the buttons new position
  71937. */
  71938. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71939. // If there is no loaded mesh, there is nothing to transform.
  71940. if (!this._loadedMeshInfo) {
  71941. return;
  71942. }
  71943. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71944. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71945. return;
  71946. }
  71947. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71948. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71949. };
  71950. /**
  71951. * Moves the axis on the controller mesh based on its current state
  71952. * @param axis the index of the axis
  71953. * @param axisValue the value of the axis which determines the meshes new position
  71954. * @hidden
  71955. */
  71956. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71957. if (!this._loadedMeshInfo) {
  71958. return;
  71959. }
  71960. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71961. if (!meshInfo) {
  71962. return;
  71963. }
  71964. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71965. return;
  71966. }
  71967. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71968. var lerpValue = axisValue * 0.5 + 0.5;
  71969. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71970. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71971. };
  71972. /**
  71973. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71974. * @param scene scene in which to add meshes
  71975. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71976. */
  71977. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71978. var _this = this;
  71979. if (forceDefault === void 0) { forceDefault = false; }
  71980. var path;
  71981. var filename;
  71982. // Checking if GLB loader is present
  71983. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71984. // Determine the device specific folder based on the ID suffix
  71985. var device = 'default';
  71986. if (this.id && !forceDefault) {
  71987. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71988. device = ((match && match[0]) || device);
  71989. }
  71990. // Hand
  71991. if (this.hand === 'left') {
  71992. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71993. }
  71994. else { // Right is the default if no hand is specified
  71995. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71996. }
  71997. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71998. }
  71999. else {
  72000. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72001. path = BABYLON.GenericController.MODEL_BASE_URL;
  72002. filename = BABYLON.GenericController.MODEL_FILENAME;
  72003. }
  72004. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72005. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72006. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72007. if (!_this._loadedMeshInfo) {
  72008. return;
  72009. }
  72010. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72011. _this.attachToMesh(_this._defaultModel);
  72012. if (meshLoaded) {
  72013. meshLoaded(_this._defaultModel);
  72014. }
  72015. }, null, function (scene, message) {
  72016. BABYLON.Tools.Log(message);
  72017. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72018. if (!forceDefault) {
  72019. _this.initControllerMesh(scene, meshLoaded, true);
  72020. }
  72021. });
  72022. };
  72023. /**
  72024. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72025. * can be transformed by button presses and axes values, based on this._mapping.
  72026. *
  72027. * @param scene scene in which the meshes exist
  72028. * @param meshes list of meshes that make up the controller model to process
  72029. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72030. */
  72031. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72032. var loadedMeshInfo = null;
  72033. // Create a new mesh to contain the glTF hierarchy
  72034. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72035. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72036. var childMesh = null;
  72037. for (var i = 0; i < meshes.length; i++) {
  72038. var mesh = meshes[i];
  72039. if (!mesh.parent) {
  72040. // Exclude controller meshes from picking results
  72041. mesh.isPickable = false;
  72042. // Handle root node, attach to the new parentMesh
  72043. childMesh = mesh;
  72044. break;
  72045. }
  72046. }
  72047. if (childMesh) {
  72048. childMesh.setParent(parentMesh);
  72049. // Create our mesh info. Note that this method will always return non-null.
  72050. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72051. }
  72052. else {
  72053. BABYLON.Tools.Warn('Could not find root node in model file.');
  72054. }
  72055. return loadedMeshInfo;
  72056. };
  72057. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72058. var loadedMeshInfo = new LoadedMeshInfo();
  72059. var i;
  72060. loadedMeshInfo.rootNode = rootNode;
  72061. // Reset the caches
  72062. loadedMeshInfo.buttonMeshes = {};
  72063. loadedMeshInfo.axisMeshes = {};
  72064. // Button Meshes
  72065. for (i = 0; i < this._mapping.buttons.length; i++) {
  72066. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72067. if (!buttonMeshName) {
  72068. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72069. continue;
  72070. }
  72071. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72072. if (!buttonMesh) {
  72073. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72074. continue;
  72075. }
  72076. var buttonMeshInfo = {
  72077. index: i,
  72078. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72079. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72080. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72081. };
  72082. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72083. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72084. }
  72085. else {
  72086. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72087. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72088. '(VALUE: ' + !!buttonMeshInfo.value +
  72089. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72090. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72091. ')');
  72092. }
  72093. }
  72094. // Axis Meshes
  72095. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72096. var axisMeshName = this._mapping.axisMeshNames[i];
  72097. if (!axisMeshName) {
  72098. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72099. continue;
  72100. }
  72101. var axisMesh = getChildByName(rootNode, axisMeshName);
  72102. if (!axisMesh) {
  72103. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72104. continue;
  72105. }
  72106. var axisMeshInfo = {
  72107. index: i,
  72108. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72109. min: getImmediateChildByName(axisMesh, 'MIN'),
  72110. max: getImmediateChildByName(axisMesh, 'MAX')
  72111. };
  72112. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72113. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72114. }
  72115. else {
  72116. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72117. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72118. '(VALUE: ' + !!axisMeshInfo.value +
  72119. ', MIN: ' + !!axisMeshInfo.min +
  72120. ', MAX:' + !!axisMeshInfo.max +
  72121. ')');
  72122. }
  72123. }
  72124. // Pointing Ray
  72125. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72126. if (!loadedMeshInfo.pointingPoseNode) {
  72127. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72128. }
  72129. else {
  72130. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72131. }
  72132. return loadedMeshInfo;
  72133. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72134. function getChildByName(node, name) {
  72135. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72136. }
  72137. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72138. function getImmediateChildByName(node, name) {
  72139. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72140. }
  72141. };
  72142. /**
  72143. * Gets the ray of the controller in the direction the controller is pointing
  72144. * @param length the length the resulting ray should be
  72145. * @returns a ray in the direction the controller is pointing
  72146. */
  72147. WindowsMotionController.prototype.getForwardRay = function (length) {
  72148. if (length === void 0) { length = 100; }
  72149. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72150. return _super.prototype.getForwardRay.call(this, length);
  72151. }
  72152. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72153. var origin = m.getTranslation();
  72154. var forward = new BABYLON.Vector3(0, 0, -1);
  72155. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72156. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72157. return new BABYLON.Ray(origin, direction, length);
  72158. };
  72159. /**
  72160. * Disposes of the controller
  72161. */
  72162. WindowsMotionController.prototype.dispose = function () {
  72163. _super.prototype.dispose.call(this);
  72164. this.onTrackpadChangedObservable.clear();
  72165. };
  72166. /**
  72167. * The base url used to load the left and right controller models
  72168. */
  72169. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72170. /**
  72171. * The name of the left controller model file
  72172. */
  72173. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72174. /**
  72175. * The name of the right controller model file
  72176. */
  72177. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72178. /**
  72179. * The controller name prefix for this controller type
  72180. */
  72181. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72182. /**
  72183. * The controller id pattern for this controller type
  72184. */
  72185. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72186. return WindowsMotionController;
  72187. }(BABYLON.WebVRController));
  72188. BABYLON.WindowsMotionController = WindowsMotionController;
  72189. })(BABYLON || (BABYLON = {}));
  72190. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72191. var BABYLON;
  72192. (function (BABYLON) {
  72193. /**
  72194. * Gear VR Controller
  72195. */
  72196. var GearVRController = /** @class */ (function (_super) {
  72197. __extends(GearVRController, _super);
  72198. /**
  72199. * Creates a new GearVRController from a gamepad
  72200. * @param vrGamepad the gamepad that the controller should be created from
  72201. */
  72202. function GearVRController(vrGamepad) {
  72203. var _this = _super.call(this, vrGamepad) || this;
  72204. _this._buttonIndexToObservableNameMap = [
  72205. 'onTrackpadChangedObservable',
  72206. 'onTriggerStateChangedObservable' // Trigger
  72207. ];
  72208. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72209. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72210. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72211. return _this;
  72212. }
  72213. /**
  72214. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72215. * @param scene scene in which to add meshes
  72216. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72217. */
  72218. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72219. var _this = this;
  72220. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72221. _this._defaultModel = newMeshes[1];
  72222. _this.attachToMesh(_this._defaultModel);
  72223. if (meshLoaded) {
  72224. meshLoaded(_this._defaultModel);
  72225. }
  72226. });
  72227. };
  72228. /**
  72229. * Called once for each button that changed state since the last frame
  72230. * @param buttonIdx Which button index changed
  72231. * @param state New state of the button
  72232. * @param changes Which properties on the state changed since last frame
  72233. */
  72234. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72235. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72236. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72237. // Only emit events for buttons that we know how to map from index to observable
  72238. var observable = this[observableName];
  72239. if (observable) {
  72240. observable.notifyObservers(state);
  72241. }
  72242. }
  72243. };
  72244. /**
  72245. * Base Url for the controller model.
  72246. */
  72247. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72248. /**
  72249. * File name for the controller model.
  72250. */
  72251. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72252. /**
  72253. * Gamepad Id prefix used to identify this controller.
  72254. */
  72255. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72256. return GearVRController;
  72257. }(BABYLON.WebVRController));
  72258. BABYLON.GearVRController = GearVRController;
  72259. })(BABYLON || (BABYLON = {}));
  72260. //# sourceMappingURL=babylon.gearVRController.js.map
  72261. var BABYLON;
  72262. (function (BABYLON) {
  72263. /**
  72264. * Google Daydream controller
  72265. */
  72266. var DaydreamController = /** @class */ (function (_super) {
  72267. __extends(DaydreamController, _super);
  72268. /**
  72269. * Creates a new DaydreamController from a gamepad
  72270. * @param vrGamepad the gamepad that the controller should be created from
  72271. */
  72272. function DaydreamController(vrGamepad) {
  72273. var _this = _super.call(this, vrGamepad) || this;
  72274. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72275. return _this;
  72276. }
  72277. /**
  72278. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72279. * @param scene scene in which to add meshes
  72280. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72281. */
  72282. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72283. var _this = this;
  72284. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72285. _this._defaultModel = newMeshes[1];
  72286. _this.attachToMesh(_this._defaultModel);
  72287. if (meshLoaded) {
  72288. meshLoaded(_this._defaultModel);
  72289. }
  72290. });
  72291. };
  72292. /**
  72293. * Called once for each button that changed state since the last frame
  72294. * @param buttonIdx Which button index changed
  72295. * @param state New state of the button
  72296. * @param changes Which properties on the state changed since last frame
  72297. */
  72298. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72299. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72300. if (buttonIdx === 0) {
  72301. var observable = this.onTriggerStateChangedObservable;
  72302. if (observable) {
  72303. observable.notifyObservers(state);
  72304. }
  72305. }
  72306. else {
  72307. // If the app or home buttons are ever made available
  72308. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72309. }
  72310. };
  72311. /**
  72312. * Base Url for the controller model.
  72313. */
  72314. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72315. /**
  72316. * File name for the controller model.
  72317. */
  72318. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72319. /**
  72320. * Gamepad Id prefix used to identify Daydream Controller.
  72321. */
  72322. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72323. return DaydreamController;
  72324. }(BABYLON.WebVRController));
  72325. BABYLON.DaydreamController = DaydreamController;
  72326. })(BABYLON || (BABYLON = {}));
  72327. //# sourceMappingURL=babylon.daydreamController.js.map
  72328. var BABYLON;
  72329. (function (BABYLON) {
  72330. var FollowCamera = /** @class */ (function (_super) {
  72331. __extends(FollowCamera, _super);
  72332. function FollowCamera(name, position, scene, lockedTarget) {
  72333. if (lockedTarget === void 0) { lockedTarget = null; }
  72334. var _this = _super.call(this, name, position, scene) || this;
  72335. _this.radius = 12;
  72336. _this.rotationOffset = 0;
  72337. _this.heightOffset = 4;
  72338. _this.cameraAcceleration = 0.05;
  72339. _this.maxCameraSpeed = 20;
  72340. _this.lockedTarget = lockedTarget;
  72341. return _this;
  72342. }
  72343. FollowCamera.prototype.getRadians = function (degrees) {
  72344. return degrees * Math.PI / 180;
  72345. };
  72346. FollowCamera.prototype.follow = function (cameraTarget) {
  72347. if (!cameraTarget)
  72348. return;
  72349. var yRotation;
  72350. if (cameraTarget.rotationQuaternion) {
  72351. var rotMatrix = new BABYLON.Matrix();
  72352. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72353. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72354. }
  72355. else {
  72356. yRotation = cameraTarget.rotation.y;
  72357. }
  72358. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72359. var targetPosition = cameraTarget.getAbsolutePosition();
  72360. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72361. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72362. var dx = targetX - this.position.x;
  72363. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72364. var dz = (targetZ) - this.position.z;
  72365. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72366. var vy = dy * this.cameraAcceleration;
  72367. var vz = dz * this.cameraAcceleration * 2;
  72368. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72369. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72370. }
  72371. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72372. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72373. }
  72374. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72375. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72376. }
  72377. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72378. this.setTarget(targetPosition);
  72379. };
  72380. FollowCamera.prototype._checkInputs = function () {
  72381. _super.prototype._checkInputs.call(this);
  72382. if (this.lockedTarget) {
  72383. this.follow(this.lockedTarget);
  72384. }
  72385. };
  72386. FollowCamera.prototype.getClassName = function () {
  72387. return "FollowCamera";
  72388. };
  72389. __decorate([
  72390. BABYLON.serialize()
  72391. ], FollowCamera.prototype, "radius", void 0);
  72392. __decorate([
  72393. BABYLON.serialize()
  72394. ], FollowCamera.prototype, "rotationOffset", void 0);
  72395. __decorate([
  72396. BABYLON.serialize()
  72397. ], FollowCamera.prototype, "heightOffset", void 0);
  72398. __decorate([
  72399. BABYLON.serialize()
  72400. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72401. __decorate([
  72402. BABYLON.serialize()
  72403. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72404. __decorate([
  72405. BABYLON.serializeAsMeshReference("lockedTargetId")
  72406. ], FollowCamera.prototype, "lockedTarget", void 0);
  72407. return FollowCamera;
  72408. }(BABYLON.TargetCamera));
  72409. BABYLON.FollowCamera = FollowCamera;
  72410. var ArcFollowCamera = /** @class */ (function (_super) {
  72411. __extends(ArcFollowCamera, _super);
  72412. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72413. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72414. _this.alpha = alpha;
  72415. _this.beta = beta;
  72416. _this.radius = radius;
  72417. _this.target = target;
  72418. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72419. _this.follow();
  72420. return _this;
  72421. }
  72422. ArcFollowCamera.prototype.follow = function () {
  72423. if (!this.target) {
  72424. return;
  72425. }
  72426. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72427. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72428. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72429. var targetPosition = this.target.getAbsolutePosition();
  72430. this.position = targetPosition.add(this._cartesianCoordinates);
  72431. this.setTarget(targetPosition);
  72432. };
  72433. ArcFollowCamera.prototype._checkInputs = function () {
  72434. _super.prototype._checkInputs.call(this);
  72435. this.follow();
  72436. };
  72437. ArcFollowCamera.prototype.getClassName = function () {
  72438. return "ArcFollowCamera";
  72439. };
  72440. return ArcFollowCamera;
  72441. }(BABYLON.TargetCamera));
  72442. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72443. })(BABYLON || (BABYLON = {}));
  72444. //# sourceMappingURL=babylon.followCamera.js.map
  72445. var BABYLON;
  72446. (function (BABYLON) {
  72447. // We're mainly based on the logic defined into the FreeCamera code
  72448. var UniversalCamera = /** @class */ (function (_super) {
  72449. __extends(UniversalCamera, _super);
  72450. //-- end properties for backward compatibility for inputs
  72451. function UniversalCamera(name, position, scene) {
  72452. var _this = _super.call(this, name, position, scene) || this;
  72453. _this.inputs.addGamepad();
  72454. return _this;
  72455. }
  72456. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72457. //-- Begin properties for backward compatibility for inputs
  72458. get: function () {
  72459. var gamepad = this.inputs.attached["gamepad"];
  72460. if (gamepad)
  72461. return gamepad.gamepadAngularSensibility;
  72462. return 0;
  72463. },
  72464. set: function (value) {
  72465. var gamepad = this.inputs.attached["gamepad"];
  72466. if (gamepad)
  72467. gamepad.gamepadAngularSensibility = value;
  72468. },
  72469. enumerable: true,
  72470. configurable: true
  72471. });
  72472. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72473. get: function () {
  72474. var gamepad = this.inputs.attached["gamepad"];
  72475. if (gamepad)
  72476. return gamepad.gamepadMoveSensibility;
  72477. return 0;
  72478. },
  72479. set: function (value) {
  72480. var gamepad = this.inputs.attached["gamepad"];
  72481. if (gamepad)
  72482. gamepad.gamepadMoveSensibility = value;
  72483. },
  72484. enumerable: true,
  72485. configurable: true
  72486. });
  72487. UniversalCamera.prototype.getClassName = function () {
  72488. return "UniversalCamera";
  72489. };
  72490. return UniversalCamera;
  72491. }(BABYLON.TouchCamera));
  72492. BABYLON.UniversalCamera = UniversalCamera;
  72493. })(BABYLON || (BABYLON = {}));
  72494. //# sourceMappingURL=babylon.universalCamera.js.map
  72495. var BABYLON;
  72496. (function (BABYLON) {
  72497. // We're mainly based on the logic defined into the FreeCamera code
  72498. var GamepadCamera = /** @class */ (function (_super) {
  72499. __extends(GamepadCamera, _super);
  72500. //-- end properties for backward compatibility for inputs
  72501. function GamepadCamera(name, position, scene) {
  72502. return _super.call(this, name, position, scene) || this;
  72503. }
  72504. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72505. //-- Begin properties for backward compatibility for inputs
  72506. get: function () {
  72507. var gamepad = this.inputs.attached["gamepad"];
  72508. if (gamepad)
  72509. return gamepad.gamepadAngularSensibility;
  72510. return 0;
  72511. },
  72512. set: function (value) {
  72513. var gamepad = this.inputs.attached["gamepad"];
  72514. if (gamepad)
  72515. gamepad.gamepadAngularSensibility = value;
  72516. },
  72517. enumerable: true,
  72518. configurable: true
  72519. });
  72520. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72521. get: function () {
  72522. var gamepad = this.inputs.attached["gamepad"];
  72523. if (gamepad)
  72524. return gamepad.gamepadMoveSensibility;
  72525. return 0;
  72526. },
  72527. set: function (value) {
  72528. var gamepad = this.inputs.attached["gamepad"];
  72529. if (gamepad)
  72530. gamepad.gamepadMoveSensibility = value;
  72531. },
  72532. enumerable: true,
  72533. configurable: true
  72534. });
  72535. GamepadCamera.prototype.getClassName = function () {
  72536. return "GamepadCamera";
  72537. };
  72538. return GamepadCamera;
  72539. }(BABYLON.UniversalCamera));
  72540. BABYLON.GamepadCamera = GamepadCamera;
  72541. })(BABYLON || (BABYLON = {}));
  72542. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72543. var BABYLON;
  72544. (function (BABYLON) {
  72545. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72546. function PostProcessRenderPipelineManager() {
  72547. this._renderPipelines = {};
  72548. }
  72549. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72550. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72551. };
  72552. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72553. if (unique === void 0) { unique = false; }
  72554. var renderPipeline = this._renderPipelines[renderPipelineName];
  72555. if (!renderPipeline) {
  72556. return;
  72557. }
  72558. renderPipeline._attachCameras(cameras, unique);
  72559. };
  72560. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72561. var renderPipeline = this._renderPipelines[renderPipelineName];
  72562. if (!renderPipeline) {
  72563. return;
  72564. }
  72565. renderPipeline._detachCameras(cameras);
  72566. };
  72567. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72568. var renderPipeline = this._renderPipelines[renderPipelineName];
  72569. if (!renderPipeline) {
  72570. return;
  72571. }
  72572. renderPipeline._enableEffect(renderEffectName, cameras);
  72573. };
  72574. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72575. var renderPipeline = this._renderPipelines[renderPipelineName];
  72576. if (!renderPipeline) {
  72577. return;
  72578. }
  72579. renderPipeline._disableEffect(renderEffectName, cameras);
  72580. };
  72581. PostProcessRenderPipelineManager.prototype.update = function () {
  72582. for (var renderPipelineName in this._renderPipelines) {
  72583. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72584. var pipeline = this._renderPipelines[renderPipelineName];
  72585. if (!pipeline.isSupported) {
  72586. pipeline.dispose();
  72587. delete this._renderPipelines[renderPipelineName];
  72588. }
  72589. else {
  72590. pipeline._update();
  72591. }
  72592. }
  72593. }
  72594. };
  72595. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72596. for (var renderPipelineName in this._renderPipelines) {
  72597. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72598. var pipeline = this._renderPipelines[renderPipelineName];
  72599. pipeline._rebuild();
  72600. }
  72601. }
  72602. };
  72603. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72604. for (var renderPipelineName in this._renderPipelines) {
  72605. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72606. var pipeline = this._renderPipelines[renderPipelineName];
  72607. pipeline.dispose();
  72608. }
  72609. }
  72610. };
  72611. return PostProcessRenderPipelineManager;
  72612. }());
  72613. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72614. })(BABYLON || (BABYLON = {}));
  72615. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72616. var BABYLON;
  72617. (function (BABYLON) {
  72618. /**
  72619. * This represents a set of one or more post processes in Babylon.
  72620. * A post process can be used to apply a shader to a texture after it is rendered.
  72621. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72622. */
  72623. var PostProcessRenderEffect = /** @class */ (function () {
  72624. /**
  72625. * Instantiates a post process render effect.
  72626. * A post process can be used to apply a shader to a texture after it is rendered.
  72627. * @param engine The engine the effect is tied to
  72628. * @param name The name of the effect
  72629. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72630. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72631. */
  72632. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72633. this._name = name;
  72634. this._singleInstance = singleInstance || true;
  72635. this._getPostProcesses = getPostProcesses;
  72636. this._cameras = {};
  72637. this._indicesForCamera = {};
  72638. this._postProcesses = {};
  72639. }
  72640. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72641. /**
  72642. * Checks if all the post processes in the effect are supported.
  72643. */
  72644. get: function () {
  72645. for (var index in this._postProcesses) {
  72646. if (this._postProcesses.hasOwnProperty(index)) {
  72647. var pps = this._postProcesses[index];
  72648. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72649. if (!pps[ppIndex].isSupported) {
  72650. return false;
  72651. }
  72652. }
  72653. }
  72654. }
  72655. return true;
  72656. },
  72657. enumerable: true,
  72658. configurable: true
  72659. });
  72660. /**
  72661. * Updates the current state of the effect
  72662. */
  72663. PostProcessRenderEffect.prototype._update = function () {
  72664. };
  72665. /**
  72666. * Attaches the effect on cameras
  72667. * @param cameras The camera to attach to.
  72668. */
  72669. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72670. var _this = this;
  72671. var cameraKey;
  72672. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72673. if (!cams) {
  72674. return;
  72675. }
  72676. for (var i = 0; i < cams.length; i++) {
  72677. var camera = cams[i];
  72678. var cameraName = camera.name;
  72679. if (this._singleInstance) {
  72680. cameraKey = 0;
  72681. }
  72682. else {
  72683. cameraKey = cameraName;
  72684. }
  72685. if (!this._postProcesses[cameraKey]) {
  72686. var postProcess = this._getPostProcesses();
  72687. if (postProcess) {
  72688. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72689. }
  72690. }
  72691. if (!this._indicesForCamera[cameraName]) {
  72692. this._indicesForCamera[cameraName] = [];
  72693. }
  72694. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72695. var index = camera.attachPostProcess(postProcess);
  72696. _this._indicesForCamera[cameraName].push(index);
  72697. });
  72698. if (!this._cameras[cameraName]) {
  72699. this._cameras[cameraName] = camera;
  72700. }
  72701. }
  72702. };
  72703. /**
  72704. * Detatches the effect on cameras
  72705. * @param cameras The camera to detatch from.
  72706. */
  72707. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72708. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72709. if (!cams) {
  72710. return;
  72711. }
  72712. for (var i = 0; i < cams.length; i++) {
  72713. var camera = cams[i];
  72714. var cameraName = camera.name;
  72715. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72716. camera.detachPostProcess(postProcess);
  72717. });
  72718. if (this._cameras[cameraName]) {
  72719. //this._indicesForCamera.splice(index, 1);
  72720. this._cameras[cameraName] = null;
  72721. }
  72722. }
  72723. };
  72724. /**
  72725. * Enables the effect on given cameras
  72726. * @param cameras The camera to enable.
  72727. */
  72728. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72729. var _this = this;
  72730. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72731. if (!cams) {
  72732. return;
  72733. }
  72734. for (var i = 0; i < cams.length; i++) {
  72735. var camera = cams[i];
  72736. var cameraName = camera.name;
  72737. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72738. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72739. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72740. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72741. });
  72742. }
  72743. }
  72744. }
  72745. };
  72746. /**
  72747. * Disables the effect on the given cameras
  72748. * @param cameras The camera to disable.
  72749. */
  72750. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72751. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72752. if (!cams) {
  72753. return;
  72754. }
  72755. for (var i = 0; i < cams.length; i++) {
  72756. var camera = cams[i];
  72757. var cameraName = camera.name;
  72758. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72759. camera.detachPostProcess(postProcess);
  72760. });
  72761. }
  72762. };
  72763. /**
  72764. * Gets a list of the post processes contained in the effect.
  72765. * @param camera The camera to get the post processes on.
  72766. * @returns The list of the post processes in the effect.
  72767. */
  72768. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72769. if (this._singleInstance) {
  72770. return this._postProcesses[0];
  72771. }
  72772. else {
  72773. if (!camera) {
  72774. return null;
  72775. }
  72776. return this._postProcesses[camera.name];
  72777. }
  72778. };
  72779. return PostProcessRenderEffect;
  72780. }());
  72781. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72782. })(BABYLON || (BABYLON = {}));
  72783. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72784. var BABYLON;
  72785. (function (BABYLON) {
  72786. var PostProcessRenderPipeline = /** @class */ (function () {
  72787. function PostProcessRenderPipeline(engine, name) {
  72788. this.engine = engine;
  72789. this._name = name;
  72790. this._renderEffects = {};
  72791. this._renderEffectsForIsolatedPass = new Array();
  72792. this._cameras = [];
  72793. }
  72794. PostProcessRenderPipeline.prototype.getClassName = function () {
  72795. return "PostProcessRenderPipeline";
  72796. };
  72797. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72798. get: function () {
  72799. for (var renderEffectName in this._renderEffects) {
  72800. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72801. if (!this._renderEffects[renderEffectName].isSupported) {
  72802. return false;
  72803. }
  72804. }
  72805. }
  72806. return true;
  72807. },
  72808. enumerable: true,
  72809. configurable: true
  72810. });
  72811. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72812. this._renderEffects[renderEffect._name] = renderEffect;
  72813. };
  72814. // private
  72815. PostProcessRenderPipeline.prototype._rebuild = function () {
  72816. };
  72817. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72818. var renderEffects = this._renderEffects[renderEffectName];
  72819. if (!renderEffects) {
  72820. return;
  72821. }
  72822. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72823. };
  72824. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72825. var renderEffects = this._renderEffects[renderEffectName];
  72826. if (!renderEffects) {
  72827. return;
  72828. }
  72829. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72830. };
  72831. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72832. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72833. if (!cams) {
  72834. return;
  72835. }
  72836. var indicesToDelete = [];
  72837. var i;
  72838. for (i = 0; i < cams.length; i++) {
  72839. var camera = cams[i];
  72840. var cameraName = camera.name;
  72841. if (this._cameras.indexOf(camera) === -1) {
  72842. this._cameras[cameraName] = camera;
  72843. }
  72844. else if (unique) {
  72845. indicesToDelete.push(i);
  72846. }
  72847. }
  72848. for (i = 0; i < indicesToDelete.length; i++) {
  72849. cameras.splice(indicesToDelete[i], 1);
  72850. }
  72851. for (var renderEffectName in this._renderEffects) {
  72852. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72853. this._renderEffects[renderEffectName]._attachCameras(cams);
  72854. }
  72855. }
  72856. };
  72857. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72858. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72859. if (!cams) {
  72860. return;
  72861. }
  72862. for (var renderEffectName in this._renderEffects) {
  72863. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72864. this._renderEffects[renderEffectName]._detachCameras(cams);
  72865. }
  72866. }
  72867. for (var i = 0; i < cams.length; i++) {
  72868. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72869. }
  72870. };
  72871. PostProcessRenderPipeline.prototype._update = function () {
  72872. for (var renderEffectName in this._renderEffects) {
  72873. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72874. this._renderEffects[renderEffectName]._update();
  72875. }
  72876. }
  72877. for (var i = 0; i < this._cameras.length; i++) {
  72878. var cameraName = this._cameras[i].name;
  72879. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72880. this._renderEffectsForIsolatedPass[cameraName]._update();
  72881. }
  72882. }
  72883. };
  72884. PostProcessRenderPipeline.prototype._reset = function () {
  72885. this._renderEffects = {};
  72886. this._renderEffectsForIsolatedPass = new Array();
  72887. };
  72888. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72889. // 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)
  72890. var effectKeys = Object.keys(this._renderEffects);
  72891. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72892. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72893. if (postProcesses) {
  72894. postProcesses[0].samples = sampleCount;
  72895. return true;
  72896. }
  72897. }
  72898. return false;
  72899. };
  72900. PostProcessRenderPipeline.prototype.dispose = function () {
  72901. // Must be implemented by children
  72902. };
  72903. __decorate([
  72904. BABYLON.serialize()
  72905. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72906. return PostProcessRenderPipeline;
  72907. }());
  72908. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72909. })(BABYLON || (BABYLON = {}));
  72910. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72911. var BABYLON;
  72912. (function (BABYLON) {
  72913. /**
  72914. * This represents a depth renderer in Babylon.
  72915. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72916. */
  72917. var DepthRenderer = /** @class */ (function () {
  72918. /**
  72919. * Instantiates a depth renderer
  72920. * @param scene The scene the renderer belongs to
  72921. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72922. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72923. */
  72924. function DepthRenderer(scene, type, camera) {
  72925. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72926. if (camera === void 0) { camera = null; }
  72927. var _this = this;
  72928. this._scene = scene;
  72929. this._camera = camera;
  72930. var engine = scene.getEngine();
  72931. // Render target
  72932. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72933. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72934. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72935. this._depthMap.refreshRate = 1;
  72936. this._depthMap.renderParticles = false;
  72937. this._depthMap.renderList = null;
  72938. // Camera to get depth map from to support multiple concurrent cameras
  72939. this._depthMap.activeCamera = this._camera;
  72940. this._depthMap.ignoreCameraViewport = true;
  72941. this._depthMap.useCameraPostProcesses = false;
  72942. // set default depth value to 1.0 (far away)
  72943. this._depthMap.onClearObservable.add(function (engine) {
  72944. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72945. });
  72946. // Custom render function
  72947. var renderSubMesh = function (subMesh) {
  72948. var mesh = subMesh.getRenderingMesh();
  72949. var scene = _this._scene;
  72950. var engine = scene.getEngine();
  72951. var material = subMesh.getMaterial();
  72952. if (!material) {
  72953. return;
  72954. }
  72955. // Culling and reverse (right handed system)
  72956. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72957. // Managing instances
  72958. var batch = mesh._getInstancesRenderList(subMesh._id);
  72959. if (batch.mustReturn) {
  72960. return;
  72961. }
  72962. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72963. var camera = _this._camera || scene.activeCamera;
  72964. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72965. engine.enableEffect(_this._effect);
  72966. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72967. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72968. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72969. // Alpha test
  72970. if (material && material.needAlphaTesting()) {
  72971. var alphaTexture = material.getAlphaTestTexture();
  72972. if (alphaTexture) {
  72973. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72974. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72975. }
  72976. }
  72977. // Bones
  72978. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72979. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72980. }
  72981. // Draw
  72982. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72983. }
  72984. };
  72985. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72986. var index;
  72987. if (depthOnlySubMeshes.length) {
  72988. engine.setColorWrite(false);
  72989. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72990. renderSubMesh(depthOnlySubMeshes.data[index]);
  72991. }
  72992. engine.setColorWrite(true);
  72993. }
  72994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72995. renderSubMesh(opaqueSubMeshes.data[index]);
  72996. }
  72997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72998. renderSubMesh(alphaTestSubMeshes.data[index]);
  72999. }
  73000. };
  73001. }
  73002. /**
  73003. * Creates the depth rendering effect and checks if the effect is ready.
  73004. * @param subMesh The submesh to be used to render the depth map of
  73005. * @param useInstances If multiple world instances should be used
  73006. * @returns if the depth renderer is ready to render the depth map
  73007. */
  73008. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73009. var material = subMesh.getMaterial();
  73010. if (material.disableDepthWrite) {
  73011. return false;
  73012. }
  73013. var defines = [];
  73014. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73015. var mesh = subMesh.getMesh();
  73016. // Alpha test
  73017. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73018. defines.push("#define ALPHATEST");
  73019. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73020. attribs.push(BABYLON.VertexBuffer.UVKind);
  73021. defines.push("#define UV1");
  73022. }
  73023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73024. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73025. defines.push("#define UV2");
  73026. }
  73027. }
  73028. // Bones
  73029. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73030. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73031. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73032. if (mesh.numBoneInfluencers > 4) {
  73033. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73034. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73035. }
  73036. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73037. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73038. }
  73039. else {
  73040. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73041. }
  73042. // Instances
  73043. if (useInstances) {
  73044. defines.push("#define INSTANCES");
  73045. attribs.push("world0");
  73046. attribs.push("world1");
  73047. attribs.push("world2");
  73048. attribs.push("world3");
  73049. }
  73050. // Get correct effect
  73051. var join = defines.join("\n");
  73052. if (this._cachedDefines !== join) {
  73053. this._cachedDefines = join;
  73054. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73055. }
  73056. return this._effect.isReady();
  73057. };
  73058. /**
  73059. * Gets the texture which the depth map will be written to.
  73060. * @returns The depth map texture
  73061. */
  73062. DepthRenderer.prototype.getDepthMap = function () {
  73063. return this._depthMap;
  73064. };
  73065. /**
  73066. * Disposes of the depth renderer.
  73067. */
  73068. DepthRenderer.prototype.dispose = function () {
  73069. this._depthMap.dispose();
  73070. };
  73071. return DepthRenderer;
  73072. }());
  73073. BABYLON.DepthRenderer = DepthRenderer;
  73074. })(BABYLON || (BABYLON = {}));
  73075. //# sourceMappingURL=babylon.depthRenderer.js.map
  73076. var BABYLON;
  73077. (function (BABYLON) {
  73078. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73079. __extends(SSAORenderingPipeline, _super);
  73080. /**
  73081. * @constructor
  73082. * @param {string} name - The rendering pipeline name
  73083. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73084. * @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 }
  73085. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73086. */
  73087. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73088. var _this = _super.call(this, scene.getEngine(), name) || this;
  73089. // Members
  73090. /**
  73091. * The PassPostProcess id in the pipeline that contains the original scene color
  73092. */
  73093. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73094. /**
  73095. * The SSAO PostProcess id in the pipeline
  73096. */
  73097. _this.SSAORenderEffect = "SSAORenderEffect";
  73098. /**
  73099. * The horizontal blur PostProcess id in the pipeline
  73100. */
  73101. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73102. /**
  73103. * The vertical blur PostProcess id in the pipeline
  73104. */
  73105. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73106. /**
  73107. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73108. */
  73109. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73110. /**
  73111. * The output strength of the SSAO post-process. Default value is 1.0.
  73112. */
  73113. _this.totalStrength = 1.0;
  73114. /**
  73115. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73116. */
  73117. _this.radius = 0.0001;
  73118. /**
  73119. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73120. * Must not be equal to fallOff and superior to fallOff.
  73121. * Default value is 0.975
  73122. */
  73123. _this.area = 0.0075;
  73124. /**
  73125. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73126. * Must not be equal to area and inferior to area.
  73127. * Default value is 0.0
  73128. */
  73129. _this.fallOff = 0.000001;
  73130. /**
  73131. * The base color of the SSAO post-process
  73132. * The final result is "base + ssao" between [0, 1]
  73133. */
  73134. _this.base = 0.5;
  73135. _this._firstUpdate = true;
  73136. _this._scene = scene;
  73137. // Set up assets
  73138. _this._createRandomTexture();
  73139. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73140. var ssaoRatio = ratio.ssaoRatio || ratio;
  73141. var combineRatio = ratio.combineRatio || ratio;
  73142. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73143. _this._createSSAOPostProcess(ssaoRatio);
  73144. _this._createBlurPostProcess(ssaoRatio);
  73145. _this._createSSAOCombinePostProcess(combineRatio);
  73146. // Set up pipeline
  73147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73148. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73149. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73150. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73151. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73152. // Finish
  73153. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73154. if (cameras)
  73155. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73156. return _this;
  73157. }
  73158. // Public Methods
  73159. /**
  73160. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73161. */
  73162. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73163. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73164. for (var i = 0; i < this._scene.cameras.length; i++) {
  73165. var camera = this._scene.cameras[i];
  73166. this._originalColorPostProcess.dispose(camera);
  73167. this._ssaoPostProcess.dispose(camera);
  73168. this._blurHPostProcess.dispose(camera);
  73169. this._blurVPostProcess.dispose(camera);
  73170. this._ssaoCombinePostProcess.dispose(camera);
  73171. }
  73172. this._randomTexture.dispose();
  73173. if (disableDepthRender)
  73174. this._scene.disableDepthRenderer();
  73175. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73176. _super.prototype.dispose.call(this);
  73177. };
  73178. // Private Methods
  73179. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73180. var _this = this;
  73181. var size = 16;
  73182. 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);
  73183. 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);
  73184. this._blurHPostProcess.onActivateObservable.add(function () {
  73185. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73186. _this._blurHPostProcess.kernel = size * dw;
  73187. });
  73188. this._blurVPostProcess.onActivateObservable.add(function () {
  73189. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73190. _this._blurVPostProcess.kernel = size * dw;
  73191. });
  73192. };
  73193. SSAORenderingPipeline.prototype._rebuild = function () {
  73194. this._firstUpdate = true;
  73195. _super.prototype._rebuild.call(this);
  73196. };
  73197. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73198. var _this = this;
  73199. var numSamples = 16;
  73200. var sampleSphere = [
  73201. 0.5381, 0.1856, -0.4319,
  73202. 0.1379, 0.2486, 0.4430,
  73203. 0.3371, 0.5679, -0.0057,
  73204. -0.6999, -0.0451, -0.0019,
  73205. 0.0689, -0.1598, -0.8547,
  73206. 0.0560, 0.0069, -0.1843,
  73207. -0.0146, 0.1402, 0.0762,
  73208. 0.0100, -0.1924, -0.0344,
  73209. -0.3577, -0.5301, -0.4358,
  73210. -0.3169, 0.1063, 0.0158,
  73211. 0.0103, -0.5869, 0.0046,
  73212. -0.0897, -0.4940, 0.3287,
  73213. 0.7119, -0.0154, -0.0918,
  73214. -0.0533, 0.0596, -0.5411,
  73215. 0.0352, -0.0631, 0.5460,
  73216. -0.4776, 0.2847, -0.0271
  73217. ];
  73218. var samplesFactor = 1.0 / numSamples;
  73219. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73220. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73221. "area", "fallOff", "base", "range", "viewport"
  73222. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73223. this._ssaoPostProcess.onApply = function (effect) {
  73224. if (_this._firstUpdate) {
  73225. effect.setArray3("sampleSphere", sampleSphere);
  73226. effect.setFloat("samplesFactor", samplesFactor);
  73227. effect.setFloat("randTextureTiles", 4.0);
  73228. }
  73229. effect.setFloat("totalStrength", _this.totalStrength);
  73230. effect.setFloat("radius", _this.radius);
  73231. effect.setFloat("area", _this.area);
  73232. effect.setFloat("fallOff", _this.fallOff);
  73233. effect.setFloat("base", _this.base);
  73234. effect.setTexture("textureSampler", _this._depthTexture);
  73235. effect.setTexture("randomSampler", _this._randomTexture);
  73236. };
  73237. };
  73238. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73239. var _this = this;
  73240. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73241. this._ssaoCombinePostProcess.onApply = function (effect) {
  73242. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73243. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73244. };
  73245. };
  73246. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73247. var size = 512;
  73248. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73249. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73250. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73251. var context = this._randomTexture.getContext();
  73252. var rand = function (min, max) {
  73253. return Math.random() * (max - min) + min;
  73254. };
  73255. var randVector = BABYLON.Vector3.Zero();
  73256. for (var x = 0; x < size; x++) {
  73257. for (var y = 0; y < size; y++) {
  73258. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73259. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73260. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73261. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73262. context.fillRect(x, y, 1, 1);
  73263. }
  73264. }
  73265. this._randomTexture.update(false);
  73266. };
  73267. __decorate([
  73268. BABYLON.serialize()
  73269. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73270. __decorate([
  73271. BABYLON.serialize()
  73272. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73273. __decorate([
  73274. BABYLON.serialize()
  73275. ], SSAORenderingPipeline.prototype, "area", void 0);
  73276. __decorate([
  73277. BABYLON.serialize()
  73278. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73279. __decorate([
  73280. BABYLON.serialize()
  73281. ], SSAORenderingPipeline.prototype, "base", void 0);
  73282. return SSAORenderingPipeline;
  73283. }(BABYLON.PostProcessRenderPipeline));
  73284. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73285. })(BABYLON || (BABYLON = {}));
  73286. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73287. var BABYLON;
  73288. (function (BABYLON) {
  73289. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73290. __extends(SSAO2RenderingPipeline, _super);
  73291. /**
  73292. * @constructor
  73293. * @param {string} name - The rendering pipeline name
  73294. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73295. * @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 }
  73296. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73297. */
  73298. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73299. var _this = _super.call(this, scene.getEngine(), name) || this;
  73300. // Members
  73301. /**
  73302. * The PassPostProcess id in the pipeline that contains the original scene color
  73303. */
  73304. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73305. /**
  73306. * The SSAO PostProcess id in the pipeline
  73307. */
  73308. _this.SSAORenderEffect = "SSAORenderEffect";
  73309. /**
  73310. * The horizontal blur PostProcess id in the pipeline
  73311. */
  73312. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73313. /**
  73314. * The vertical blur PostProcess id in the pipeline
  73315. */
  73316. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73317. /**
  73318. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73319. */
  73320. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73321. /**
  73322. * The output strength of the SSAO post-process. Default value is 1.0.
  73323. */
  73324. _this.totalStrength = 1.0;
  73325. /**
  73326. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73327. */
  73328. _this.maxZ = 100.0;
  73329. /**
  73330. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73331. */
  73332. _this.minZAspect = 0.2;
  73333. /**
  73334. * Number of samples used for the SSAO calculations. Default value is 8
  73335. */
  73336. _this._samples = 8;
  73337. /**
  73338. * Are we using bilateral blur ?
  73339. */
  73340. _this._expensiveBlur = true;
  73341. /**
  73342. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73343. */
  73344. _this.radius = 2.0;
  73345. /**
  73346. * The base color of the SSAO post-process
  73347. * The final result is "base + ssao" between [0, 1]
  73348. */
  73349. _this.base = 0.1;
  73350. _this._firstUpdate = true;
  73351. _this._scene = scene;
  73352. _this._ratio = ratio;
  73353. if (!_this.isSupported) {
  73354. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73355. return _this;
  73356. }
  73357. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73358. var blurRatio = _this._ratio.blurRatio || ratio;
  73359. // Set up assets
  73360. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73361. _this._createRandomTexture();
  73362. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73363. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73364. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73365. _this._createSSAOPostProcess(1.0);
  73366. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73367. _this._createSSAOCombinePostProcess(blurRatio);
  73368. // Set up pipeline
  73369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73370. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73371. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73374. // Finish
  73375. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73376. if (cameras)
  73377. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73378. return _this;
  73379. }
  73380. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73381. get: function () {
  73382. return this._samples;
  73383. },
  73384. set: function (n) {
  73385. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73386. this._samples = n;
  73387. this._sampleSphere = this._generateHemisphere();
  73388. this._firstUpdate = true;
  73389. },
  73390. enumerable: true,
  73391. configurable: true
  73392. });
  73393. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73394. get: function () {
  73395. return this._expensiveBlur;
  73396. },
  73397. set: function (b) {
  73398. 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"]);
  73399. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73400. this._expensiveBlur = b;
  73401. this._firstUpdate = true;
  73402. },
  73403. enumerable: true,
  73404. configurable: true
  73405. });
  73406. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73407. /**
  73408. * Support test.
  73409. */
  73410. get: function () {
  73411. var engine = BABYLON.Engine.LastCreatedEngine;
  73412. if (!engine) {
  73413. return false;
  73414. }
  73415. return engine.getCaps().drawBuffersExtension;
  73416. },
  73417. enumerable: true,
  73418. configurable: true
  73419. });
  73420. // Public Methods
  73421. /**
  73422. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73423. */
  73424. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73425. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73426. for (var i = 0; i < this._scene.cameras.length; i++) {
  73427. var camera = this._scene.cameras[i];
  73428. this._originalColorPostProcess.dispose(camera);
  73429. this._ssaoPostProcess.dispose(camera);
  73430. this._blurHPostProcess.dispose(camera);
  73431. this._blurVPostProcess.dispose(camera);
  73432. this._ssaoCombinePostProcess.dispose(camera);
  73433. }
  73434. this._randomTexture.dispose();
  73435. if (disableGeometryBufferRenderer)
  73436. this._scene.disableGeometryBufferRenderer();
  73437. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73438. _super.prototype.dispose.call(this);
  73439. };
  73440. // Private Methods
  73441. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73442. var _this = this;
  73443. this._samplerOffsets = [];
  73444. var expensive = this.expensiveBlur;
  73445. for (var i = -8; i < 8; i++) {
  73446. this._samplerOffsets.push(i * 2 + 0.5);
  73447. }
  73448. 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");
  73449. this._blurHPostProcess.onApply = function (effect) {
  73450. if (!_this._scene.activeCamera) {
  73451. return;
  73452. }
  73453. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73454. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73455. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73456. effect.setFloat("radius", _this.radius);
  73457. effect.setTexture("depthSampler", _this._depthTexture);
  73458. if (_this._firstUpdate) {
  73459. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73460. }
  73461. };
  73462. 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");
  73463. this._blurVPostProcess.onApply = function (effect) {
  73464. if (!_this._scene.activeCamera) {
  73465. return;
  73466. }
  73467. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73468. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73469. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73470. effect.setFloat("radius", _this.radius);
  73471. effect.setTexture("depthSampler", _this._depthTexture);
  73472. if (_this._firstUpdate) {
  73473. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73474. _this._firstUpdate = false;
  73475. }
  73476. };
  73477. };
  73478. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73479. this._firstUpdate = true;
  73480. _super.prototype._rebuild.call(this);
  73481. };
  73482. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73483. var numSamples = this.samples;
  73484. var result = [];
  73485. var vector, scale;
  73486. var rand = function (min, max) {
  73487. return Math.random() * (max - min) + min;
  73488. };
  73489. var i = 0;
  73490. while (i < numSamples) {
  73491. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73492. vector.normalize();
  73493. scale = i / numSamples;
  73494. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73495. vector.scaleInPlace(scale);
  73496. result.push(vector.x, vector.y, vector.z);
  73497. i++;
  73498. }
  73499. return result;
  73500. };
  73501. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73502. var _this = this;
  73503. var numSamples = this.samples;
  73504. this._sampleSphere = this._generateHemisphere();
  73505. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73506. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73507. "base", "range", "projection", "near", "far", "texelSize",
  73508. "xViewport", "yViewport", "maxZ", "minZAspect"
  73509. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73510. this._ssaoPostProcess.onApply = function (effect) {
  73511. if (_this._firstUpdate) {
  73512. effect.setArray3("sampleSphere", _this._sampleSphere);
  73513. effect.setFloat("randTextureTiles", 4.0);
  73514. }
  73515. if (!_this._scene.activeCamera) {
  73516. return;
  73517. }
  73518. effect.setFloat("samplesFactor", 1 / _this.samples);
  73519. effect.setFloat("totalStrength", _this.totalStrength);
  73520. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73521. effect.setFloat("radius", _this.radius);
  73522. effect.setFloat("maxZ", _this.maxZ);
  73523. effect.setFloat("minZAspect", _this.minZAspect);
  73524. effect.setFloat("base", _this.base);
  73525. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73526. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73527. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73528. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73529. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73530. effect.setTexture("textureSampler", _this._depthTexture);
  73531. effect.setTexture("normalSampler", _this._normalTexture);
  73532. effect.setTexture("randomSampler", _this._randomTexture);
  73533. };
  73534. };
  73535. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73536. var _this = this;
  73537. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73538. this._ssaoCombinePostProcess.onApply = function (effect) {
  73539. var viewport = _this._scene.activeCamera.viewport;
  73540. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73541. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73542. };
  73543. };
  73544. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73545. var size = 512;
  73546. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73547. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73548. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73549. var context = this._randomTexture.getContext();
  73550. var rand = function (min, max) {
  73551. return Math.random() * (max - min) + min;
  73552. };
  73553. var randVector = BABYLON.Vector3.Zero();
  73554. for (var x = 0; x < size; x++) {
  73555. for (var y = 0; y < size; y++) {
  73556. randVector.x = rand(0.0, 1.0);
  73557. randVector.y = rand(0.0, 1.0);
  73558. randVector.z = 0.0;
  73559. randVector.normalize();
  73560. randVector.scaleInPlace(255);
  73561. randVector.x = Math.floor(randVector.x);
  73562. randVector.y = Math.floor(randVector.y);
  73563. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73564. context.fillRect(x, y, 1, 1);
  73565. }
  73566. }
  73567. this._randomTexture.update(false);
  73568. };
  73569. /**
  73570. * Serialize the rendering pipeline (Used when exporting)
  73571. * @returns the serialized object
  73572. */
  73573. SSAO2RenderingPipeline.prototype.serialize = function () {
  73574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73575. serializationObject.customType = "SSAO2RenderingPipeline";
  73576. return serializationObject;
  73577. };
  73578. /**
  73579. * Parse the serialized pipeline
  73580. * @param source Source pipeline.
  73581. * @param scene The scene to load the pipeline to.
  73582. * @param rootUrl The URL of the serialized pipeline.
  73583. * @returns An instantiated pipeline from the serialized object.
  73584. */
  73585. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73586. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73587. };
  73588. __decorate([
  73589. BABYLON.serialize()
  73590. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73591. __decorate([
  73592. BABYLON.serialize()
  73593. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73594. __decorate([
  73595. BABYLON.serialize()
  73596. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73597. __decorate([
  73598. BABYLON.serialize("samples")
  73599. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73600. __decorate([
  73601. BABYLON.serialize()
  73602. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73603. __decorate([
  73604. BABYLON.serialize("expensiveBlur")
  73605. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73606. __decorate([
  73607. BABYLON.serialize()
  73608. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73609. __decorate([
  73610. BABYLON.serialize()
  73611. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73612. return SSAO2RenderingPipeline;
  73613. }(BABYLON.PostProcessRenderPipeline));
  73614. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73615. })(BABYLON || (BABYLON = {}));
  73616. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73617. // BABYLON.JS Chromatic Aberration GLSL Shader
  73618. // Author: Olivier Guyot
  73619. // Separates very slightly R, G and B colors on the edges of the screen
  73620. // Inspired by Francois Tarlier & Martins Upitis
  73621. var BABYLON;
  73622. (function (BABYLON) {
  73623. var LensRenderingPipeline = /** @class */ (function (_super) {
  73624. __extends(LensRenderingPipeline, _super);
  73625. /**
  73626. * @constructor
  73627. *
  73628. * Effect parameters are as follow:
  73629. * {
  73630. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73631. * edge_blur: number; // from 0 to x (1 for realism)
  73632. * distortion: number; // from 0 to x (1 for realism)
  73633. * grain_amount: number; // from 0 to 1
  73634. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73635. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73636. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73637. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73638. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73639. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73640. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73641. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73642. * }
  73643. * Note: if an effect parameter is unset, effect is disabled
  73644. *
  73645. * @param {string} name - The rendering pipeline name
  73646. * @param {object} parameters - An object containing all parameters (see above)
  73647. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73648. * @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)
  73649. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73650. */
  73651. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73652. if (ratio === void 0) { ratio = 1.0; }
  73653. var _this = _super.call(this, scene.getEngine(), name) || this;
  73654. // Lens effects can be of the following:
  73655. // - chromatic aberration (slight shift of RGB colors)
  73656. // - blur on the edge of the lens
  73657. // - lens distortion
  73658. // - depth-of-field blur & highlights enhancing
  73659. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73660. // - grain effect (noise or custom texture)
  73661. // Two additional texture samplers are needed:
  73662. // - depth map (for depth-of-field)
  73663. // - grain texture
  73664. /**
  73665. * The chromatic aberration PostProcess id in the pipeline
  73666. */
  73667. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73668. /**
  73669. * The highlights enhancing PostProcess id in the pipeline
  73670. */
  73671. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73672. /**
  73673. * The depth-of-field PostProcess id in the pipeline
  73674. */
  73675. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73676. _this._scene = scene;
  73677. // Fetch texture samplers
  73678. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73679. if (parameters.grain_texture) {
  73680. _this._grainTexture = parameters.grain_texture;
  73681. }
  73682. else {
  73683. _this._createGrainTexture();
  73684. }
  73685. // save parameters
  73686. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73687. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73688. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73689. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73690. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73691. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73692. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73693. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73694. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73695. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73696. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73697. // Create effects
  73698. _this._createChromaticAberrationPostProcess(ratio);
  73699. _this._createHighlightsPostProcess(ratio);
  73700. _this._createDepthOfFieldPostProcess(ratio / 4);
  73701. // Set up pipeline
  73702. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73703. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73704. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73705. if (_this._highlightsGain === -1) {
  73706. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73707. }
  73708. // Finish
  73709. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73710. if (cameras) {
  73711. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73712. }
  73713. return _this;
  73714. }
  73715. // public methods (self explanatory)
  73716. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73717. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73718. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73719. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73720. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73721. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73722. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73723. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73724. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73725. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73726. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73727. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73728. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73729. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73730. };
  73731. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73732. this._highlightsPostProcess.updateEffect();
  73733. };
  73734. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73735. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73736. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73737. this._highlightsGain = amount;
  73738. };
  73739. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73740. if (this._highlightsGain === -1) {
  73741. this._highlightsGain = 1.0;
  73742. }
  73743. this._highlightsThreshold = amount;
  73744. };
  73745. LensRenderingPipeline.prototype.disableHighlights = function () {
  73746. this._highlightsGain = -1;
  73747. };
  73748. /**
  73749. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73750. */
  73751. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73752. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73753. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73754. this._chromaticAberrationPostProcess = null;
  73755. this._highlightsPostProcess = null;
  73756. this._depthOfFieldPostProcess = null;
  73757. this._grainTexture.dispose();
  73758. if (disableDepthRender)
  73759. this._scene.disableDepthRenderer();
  73760. };
  73761. // colors shifting and distortion
  73762. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73763. var _this = this;
  73764. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73765. [], // samplers
  73766. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73767. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73768. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73769. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73770. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73771. effect.setFloat('radialIntensity', 1);
  73772. effect.setFloat2('direction', 17, 17);
  73773. effect.setFloat2('centerPosition', 0.5, 0.5);
  73774. };
  73775. };
  73776. // highlights enhancing
  73777. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73778. var _this = this;
  73779. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73780. [], // samplers
  73781. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73782. this._highlightsPostProcess.onApply = function (effect) {
  73783. effect.setFloat('gain', _this._highlightsGain);
  73784. effect.setFloat('threshold', _this._highlightsThreshold);
  73785. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73786. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73787. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73788. };
  73789. };
  73790. // colors shifting and distortion
  73791. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73792. var _this = this;
  73793. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73794. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73795. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73796. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73797. this._depthOfFieldPostProcess.onApply = function (effect) {
  73798. effect.setTexture("depthSampler", _this._depthTexture);
  73799. effect.setTexture("grainSampler", _this._grainTexture);
  73800. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73801. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73802. effect.setFloat('grain_amount', _this._grainAmount);
  73803. effect.setBool('blur_noise', _this._blurNoise);
  73804. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73805. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73806. effect.setFloat('distortion', _this._distortion);
  73807. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73808. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73809. effect.setFloat('aperture', _this._dofAperture);
  73810. effect.setFloat('darken', _this._dofDarken);
  73811. effect.setFloat('edge_blur', _this._edgeBlur);
  73812. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73813. if (_this._scene.activeCamera) {
  73814. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73815. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73816. }
  73817. };
  73818. };
  73819. // creates a black and white random noise texture, 512x512
  73820. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73821. var size = 512;
  73822. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73823. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73824. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73825. var context = this._grainTexture.getContext();
  73826. var rand = function (min, max) {
  73827. return Math.random() * (max - min) + min;
  73828. };
  73829. var value;
  73830. for (var x = 0; x < size; x++) {
  73831. for (var y = 0; y < size; y++) {
  73832. value = Math.floor(rand(0.42, 0.58) * 255);
  73833. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73834. context.fillRect(x, y, 1, 1);
  73835. }
  73836. }
  73837. this._grainTexture.update(false);
  73838. };
  73839. return LensRenderingPipeline;
  73840. }(BABYLON.PostProcessRenderPipeline));
  73841. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73842. })(BABYLON || (BABYLON = {}));
  73843. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73844. var BABYLON;
  73845. (function (BABYLON) {
  73846. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73847. __extends(StandardRenderingPipeline, _super);
  73848. /**
  73849. * @constructor
  73850. * @param {string} name - The rendering pipeline name
  73851. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73852. * @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)
  73853. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73854. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73855. */
  73856. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73857. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73858. var _this = _super.call(this, scene.getEngine(), name) || this;
  73859. _this.downSampleX4PostProcess = null;
  73860. _this.brightPassPostProcess = null;
  73861. _this.blurHPostProcesses = [];
  73862. _this.blurVPostProcesses = [];
  73863. _this.textureAdderPostProcess = null;
  73864. _this.volumetricLightPostProcess = null;
  73865. _this.volumetricLightSmoothXPostProcess = null;
  73866. _this.volumetricLightSmoothYPostProcess = null;
  73867. _this.volumetricLightMergePostProces = null;
  73868. _this.volumetricLightFinalPostProcess = null;
  73869. _this.luminancePostProcess = null;
  73870. _this.luminanceDownSamplePostProcesses = [];
  73871. _this.hdrPostProcess = null;
  73872. _this.textureAdderFinalPostProcess = null;
  73873. _this.lensFlareFinalPostProcess = null;
  73874. _this.hdrFinalPostProcess = null;
  73875. _this.lensFlarePostProcess = null;
  73876. _this.lensFlareComposePostProcess = null;
  73877. _this.motionBlurPostProcess = null;
  73878. _this.depthOfFieldPostProcess = null;
  73879. // Values
  73880. _this.brightThreshold = 1.0;
  73881. _this.blurWidth = 512.0;
  73882. _this.horizontalBlur = false;
  73883. _this.exposure = 1.0;
  73884. _this.lensTexture = null;
  73885. _this.volumetricLightCoefficient = 0.2;
  73886. _this.volumetricLightPower = 4.0;
  73887. _this.volumetricLightBlurScale = 64.0;
  73888. _this.sourceLight = null;
  73889. _this.hdrMinimumLuminance = 1.0;
  73890. _this.hdrDecreaseRate = 0.5;
  73891. _this.hdrIncreaseRate = 0.5;
  73892. _this.lensColorTexture = null;
  73893. _this.lensFlareStrength = 20.0;
  73894. _this.lensFlareGhostDispersal = 1.4;
  73895. _this.lensFlareHaloWidth = 0.7;
  73896. _this.lensFlareDistortionStrength = 16.0;
  73897. _this.lensStarTexture = null;
  73898. _this.lensFlareDirtTexture = null;
  73899. _this.depthOfFieldDistance = 10.0;
  73900. _this.depthOfFieldBlurWidth = 64.0;
  73901. _this.motionStrength = 1.0;
  73902. // IAnimatable
  73903. _this.animations = [];
  73904. _this._currentDepthOfFieldSource = null;
  73905. _this._hdrCurrentLuminance = 1.0;
  73906. // Getters and setters
  73907. _this._bloomEnabled = true;
  73908. _this._depthOfFieldEnabled = false;
  73909. _this._vlsEnabled = false;
  73910. _this._lensFlareEnabled = false;
  73911. _this._hdrEnabled = false;
  73912. _this._motionBlurEnabled = false;
  73913. _this._motionBlurSamples = 64.0;
  73914. _this._volumetricLightStepsCount = 50.0;
  73915. _this._cameras = cameras || [];
  73916. // Initialize
  73917. _this._scene = scene;
  73918. _this._basePostProcess = originalPostProcess;
  73919. _this._ratio = ratio;
  73920. // Misc
  73921. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73922. // Finish
  73923. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73924. _this._buildPipeline();
  73925. return _this;
  73926. }
  73927. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73928. get: function () {
  73929. return this._bloomEnabled;
  73930. },
  73931. set: function (enabled) {
  73932. if (this._bloomEnabled === enabled) {
  73933. return;
  73934. }
  73935. this._bloomEnabled = enabled;
  73936. this._buildPipeline();
  73937. },
  73938. enumerable: true,
  73939. configurable: true
  73940. });
  73941. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73942. get: function () {
  73943. return this._depthOfFieldEnabled;
  73944. },
  73945. set: function (enabled) {
  73946. if (this._depthOfFieldEnabled === enabled) {
  73947. return;
  73948. }
  73949. this._depthOfFieldEnabled = enabled;
  73950. this._buildPipeline();
  73951. },
  73952. enumerable: true,
  73953. configurable: true
  73954. });
  73955. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73956. get: function () {
  73957. return this._lensFlareEnabled;
  73958. },
  73959. set: function (enabled) {
  73960. if (this._lensFlareEnabled === enabled) {
  73961. return;
  73962. }
  73963. this._lensFlareEnabled = enabled;
  73964. this._buildPipeline();
  73965. },
  73966. enumerable: true,
  73967. configurable: true
  73968. });
  73969. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73970. get: function () {
  73971. return this._hdrEnabled;
  73972. },
  73973. set: function (enabled) {
  73974. if (this._hdrEnabled === enabled) {
  73975. return;
  73976. }
  73977. this._hdrEnabled = enabled;
  73978. this._buildPipeline();
  73979. },
  73980. enumerable: true,
  73981. configurable: true
  73982. });
  73983. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73984. get: function () {
  73985. return this._vlsEnabled;
  73986. },
  73987. set: function (enabled) {
  73988. if (this._vlsEnabled === enabled) {
  73989. return;
  73990. }
  73991. if (enabled) {
  73992. var geometry = this._scene.enableGeometryBufferRenderer();
  73993. if (!geometry) {
  73994. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73995. return;
  73996. }
  73997. }
  73998. this._vlsEnabled = enabled;
  73999. this._buildPipeline();
  74000. },
  74001. enumerable: true,
  74002. configurable: true
  74003. });
  74004. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74005. get: function () {
  74006. return this._motionBlurEnabled;
  74007. },
  74008. set: function (enabled) {
  74009. if (this._motionBlurEnabled === enabled) {
  74010. return;
  74011. }
  74012. this._motionBlurEnabled = enabled;
  74013. this._buildPipeline();
  74014. },
  74015. enumerable: true,
  74016. configurable: true
  74017. });
  74018. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74019. get: function () {
  74020. return this._volumetricLightStepsCount;
  74021. },
  74022. set: function (count) {
  74023. if (this.volumetricLightPostProcess) {
  74024. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74025. }
  74026. this._volumetricLightStepsCount = count;
  74027. },
  74028. enumerable: true,
  74029. configurable: true
  74030. });
  74031. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74032. get: function () {
  74033. return this._motionBlurSamples;
  74034. },
  74035. set: function (samples) {
  74036. if (this.motionBlurPostProcess) {
  74037. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74038. }
  74039. this._motionBlurSamples = samples;
  74040. },
  74041. enumerable: true,
  74042. configurable: true
  74043. });
  74044. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74045. var _this = this;
  74046. var ratio = this._ratio;
  74047. var scene = this._scene;
  74048. this._disposePostProcesses();
  74049. this._reset();
  74050. // Create pass post-process
  74051. if (!this._basePostProcess) {
  74052. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74053. this.originalPostProcess.onApply = function (effect) {
  74054. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74055. };
  74056. }
  74057. else {
  74058. this.originalPostProcess = this._basePostProcess;
  74059. }
  74060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74061. this._currentDepthOfFieldSource = this.originalPostProcess;
  74062. if (this._bloomEnabled) {
  74063. // Create down sample X4 post-process
  74064. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74065. // Create bright pass post-process
  74066. this._createBrightPassPostProcess(scene, ratio / 2);
  74067. // Create gaussian blur post-processes (down sampling blurs)
  74068. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74069. // Create texture adder post-process
  74070. this._createTextureAdderPostProcess(scene, ratio);
  74071. // Create depth-of-field source post-process
  74072. 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);
  74073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74074. }
  74075. if (this._vlsEnabled) {
  74076. // Create volumetric light
  74077. this._createVolumetricLightPostProcess(scene, ratio);
  74078. // Create volumetric light final post-process
  74079. 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);
  74080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74081. }
  74082. if (this._lensFlareEnabled) {
  74083. // Create lens flare post-process
  74084. this._createLensFlarePostProcess(scene, ratio);
  74085. // Create depth-of-field source post-process post lens-flare and disable it now
  74086. 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);
  74087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74088. }
  74089. if (this._hdrEnabled) {
  74090. // Create luminance
  74091. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74092. // Create HDR
  74093. this._createHdrPostProcess(scene, ratio);
  74094. // Create depth-of-field source post-process post hdr and disable it now
  74095. 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);
  74096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74097. }
  74098. if (this._depthOfFieldEnabled) {
  74099. // Create gaussian blur used by depth-of-field
  74100. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74101. // Create depth-of-field post-process
  74102. this._createDepthOfFieldPostProcess(scene, ratio);
  74103. }
  74104. if (this._motionBlurEnabled) {
  74105. // Create motion blur post-process
  74106. this._createMotionBlurPostProcess(scene, ratio);
  74107. }
  74108. if (this._cameras !== null) {
  74109. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74110. }
  74111. };
  74112. // Down Sample X4 Post-Processs
  74113. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74114. var _this = this;
  74115. var downSampleX4Offsets = new Array(32);
  74116. 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);
  74117. this.downSampleX4PostProcess.onApply = function (effect) {
  74118. var id = 0;
  74119. var width = _this.downSampleX4PostProcess.width;
  74120. var height = _this.downSampleX4PostProcess.height;
  74121. for (var i = -2; i < 2; i++) {
  74122. for (var j = -2; j < 2; j++) {
  74123. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74124. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74125. id += 2;
  74126. }
  74127. }
  74128. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74129. };
  74130. // Add to pipeline
  74131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74132. };
  74133. // Brightpass Post-Process
  74134. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74135. var _this = this;
  74136. var brightOffsets = new Array(8);
  74137. 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);
  74138. this.brightPassPostProcess.onApply = function (effect) {
  74139. var sU = (1.0 / _this.brightPassPostProcess.width);
  74140. var sV = (1.0 / _this.brightPassPostProcess.height);
  74141. brightOffsets[0] = -0.5 * sU;
  74142. brightOffsets[1] = 0.5 * sV;
  74143. brightOffsets[2] = 0.5 * sU;
  74144. brightOffsets[3] = 0.5 * sV;
  74145. brightOffsets[4] = -0.5 * sU;
  74146. brightOffsets[5] = -0.5 * sV;
  74147. brightOffsets[6] = 0.5 * sU;
  74148. brightOffsets[7] = -0.5 * sV;
  74149. effect.setArray2("dsOffsets", brightOffsets);
  74150. effect.setFloat("brightThreshold", _this.brightThreshold);
  74151. };
  74152. // Add to pipeline
  74153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74154. };
  74155. // Create blur H&V post-processes
  74156. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74157. var _this = this;
  74158. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74159. var engine = scene.getEngine();
  74160. 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);
  74161. 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);
  74162. blurX.onActivateObservable.add(function () {
  74163. var dw = blurX.width / engine.getRenderWidth();
  74164. blurX.kernel = _this[blurWidthKey] * dw;
  74165. });
  74166. blurY.onActivateObservable.add(function () {
  74167. var dw = blurY.height / engine.getRenderHeight();
  74168. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74169. });
  74170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74172. this.blurHPostProcesses.push(blurX);
  74173. this.blurVPostProcesses.push(blurY);
  74174. };
  74175. // Create texture adder post-process
  74176. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74177. var _this = this;
  74178. 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);
  74179. this.textureAdderPostProcess.onApply = function (effect) {
  74180. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74181. effect.setTexture("lensSampler", _this.lensTexture);
  74182. effect.setFloat("exposure", _this.exposure);
  74183. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74184. };
  74185. // Add to pipeline
  74186. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74187. };
  74188. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74189. var _this = this;
  74190. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74191. geometryRenderer.enablePosition = true;
  74192. var geometry = geometryRenderer.getGBuffer();
  74193. // Base post-process
  74194. 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));
  74195. var depthValues = BABYLON.Vector2.Zero();
  74196. this.volumetricLightPostProcess.onApply = function (effect) {
  74197. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74198. var generator = _this.sourceLight.getShadowGenerator();
  74199. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74200. effect.setTexture("positionSampler", geometry.textures[2]);
  74201. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74202. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74203. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74204. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74205. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74206. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74207. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74208. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74209. effect.setVector2("depthValues", depthValues);
  74210. }
  74211. };
  74212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74213. // Smooth
  74214. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74215. // Merge
  74216. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74217. this.volumetricLightMergePostProces.onApply = function (effect) {
  74218. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74219. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74220. };
  74221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74222. };
  74223. // Create luminance
  74224. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74225. var _this = this;
  74226. // Create luminance
  74227. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74228. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74229. var offsets = [];
  74230. this.luminancePostProcess.onApply = function (effect) {
  74231. var sU = (1.0 / _this.luminancePostProcess.width);
  74232. var sV = (1.0 / _this.luminancePostProcess.height);
  74233. offsets[0] = -0.5 * sU;
  74234. offsets[1] = 0.5 * sV;
  74235. offsets[2] = 0.5 * sU;
  74236. offsets[3] = 0.5 * sV;
  74237. offsets[4] = -0.5 * sU;
  74238. offsets[5] = -0.5 * sV;
  74239. offsets[6] = 0.5 * sU;
  74240. offsets[7] = -0.5 * sV;
  74241. effect.setArray2("lumOffsets", offsets);
  74242. };
  74243. // Add to pipeline
  74244. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74245. // Create down sample luminance
  74246. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74247. var size = Math.pow(3, i);
  74248. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74249. if (i === 0) {
  74250. defines += "#define FINAL_DOWN_SAMPLER";
  74251. }
  74252. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74253. this.luminanceDownSamplePostProcesses.push(postProcess);
  74254. }
  74255. // Create callbacks and add effects
  74256. var lastLuminance = this.luminancePostProcess;
  74257. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74258. var downSampleOffsets = new Array(18);
  74259. pp.onApply = function (effect) {
  74260. if (!lastLuminance) {
  74261. return;
  74262. }
  74263. var id = 0;
  74264. for (var x = -1; x < 2; x++) {
  74265. for (var y = -1; y < 2; y++) {
  74266. downSampleOffsets[id] = x / lastLuminance.width;
  74267. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74268. id += 2;
  74269. }
  74270. }
  74271. effect.setArray2("dsOffsets", downSampleOffsets);
  74272. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74273. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74274. lastLuminance = _this.luminancePostProcess;
  74275. }
  74276. else {
  74277. lastLuminance = pp;
  74278. }
  74279. };
  74280. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74281. pp.onAfterRender = function (effect) {
  74282. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74283. 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);
  74284. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74285. };
  74286. }
  74287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74288. });
  74289. };
  74290. // Create HDR post-process
  74291. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74292. var _this = this;
  74293. 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);
  74294. var outputLiminance = 1;
  74295. var time = 0;
  74296. var lastTime = 0;
  74297. this.hdrPostProcess.onApply = function (effect) {
  74298. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74299. time += scene.getEngine().getDeltaTime();
  74300. if (outputLiminance < 0) {
  74301. outputLiminance = _this._hdrCurrentLuminance;
  74302. }
  74303. else {
  74304. var dt = (lastTime - time) / 1000.0;
  74305. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74306. outputLiminance += _this.hdrDecreaseRate * dt;
  74307. }
  74308. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74309. outputLiminance -= _this.hdrIncreaseRate * dt;
  74310. }
  74311. else {
  74312. outputLiminance = _this._hdrCurrentLuminance;
  74313. }
  74314. }
  74315. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74316. effect.setFloat("averageLuminance", outputLiminance);
  74317. lastTime = time;
  74318. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74319. };
  74320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74321. };
  74322. // Create lens flare post-process
  74323. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74324. var _this = this;
  74325. 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);
  74326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74327. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74328. 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);
  74329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74330. var resolution = new BABYLON.Vector2(0, 0);
  74331. // Lens flare
  74332. this.lensFlarePostProcess.onApply = function (effect) {
  74333. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74334. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74335. effect.setFloat("strength", _this.lensFlareStrength);
  74336. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74337. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74338. // Shift
  74339. resolution.x = _this.lensFlarePostProcess.width;
  74340. resolution.y = _this.lensFlarePostProcess.height;
  74341. effect.setVector2("resolution", resolution);
  74342. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74343. };
  74344. // Compose
  74345. 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);
  74346. 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);
  74347. this.lensFlareComposePostProcess.onApply = function (effect) {
  74348. if (!_this._scene.activeCamera) {
  74349. return;
  74350. }
  74351. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74352. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74353. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74354. // Lens start rotation matrix
  74355. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74356. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74357. 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));
  74358. camRot *= 4.0;
  74359. 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);
  74360. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74361. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74362. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74363. };
  74364. };
  74365. // Create depth-of-field post-process
  74366. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74367. var _this = this;
  74368. 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);
  74369. this.depthOfFieldPostProcess.onApply = function (effect) {
  74370. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74371. effect.setTexture("depthSampler", _this._getDepthTexture());
  74372. effect.setFloat("distance", _this.depthOfFieldDistance);
  74373. };
  74374. // Add to pipeline
  74375. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74376. };
  74377. // Create motion blur post-process
  74378. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74379. var _this = this;
  74380. 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);
  74381. var motionScale = 0;
  74382. var prevViewProjection = BABYLON.Matrix.Identity();
  74383. var invViewProjection = BABYLON.Matrix.Identity();
  74384. var viewProjection = BABYLON.Matrix.Identity();
  74385. var screenSize = BABYLON.Vector2.Zero();
  74386. this.motionBlurPostProcess.onApply = function (effect) {
  74387. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74388. viewProjection.invertToRef(invViewProjection);
  74389. effect.setMatrix("inverseViewProjection", invViewProjection);
  74390. effect.setMatrix("prevViewProjection", prevViewProjection);
  74391. prevViewProjection = viewProjection;
  74392. screenSize.x = _this.motionBlurPostProcess.width;
  74393. screenSize.y = _this.motionBlurPostProcess.height;
  74394. effect.setVector2("screenSize", screenSize);
  74395. motionScale = scene.getEngine().getFps() / 60.0;
  74396. effect.setFloat("motionScale", motionScale);
  74397. effect.setFloat("motionStrength", _this.motionStrength);
  74398. effect.setTexture("depthSampler", _this._getDepthTexture());
  74399. };
  74400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74401. };
  74402. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74403. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74404. var renderer = this._scene.enableGeometryBufferRenderer();
  74405. return renderer.getGBuffer().textures[0];
  74406. }
  74407. return this._scene.enableDepthRenderer().getDepthMap();
  74408. };
  74409. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74410. for (var i = 0; i < this._cameras.length; i++) {
  74411. var camera = this._cameras[i];
  74412. if (this.originalPostProcess) {
  74413. this.originalPostProcess.dispose(camera);
  74414. }
  74415. if (this.downSampleX4PostProcess) {
  74416. this.downSampleX4PostProcess.dispose(camera);
  74417. }
  74418. if (this.brightPassPostProcess) {
  74419. this.brightPassPostProcess.dispose(camera);
  74420. }
  74421. if (this.textureAdderPostProcess) {
  74422. this.textureAdderPostProcess.dispose(camera);
  74423. }
  74424. if (this.textureAdderFinalPostProcess) {
  74425. this.textureAdderFinalPostProcess.dispose(camera);
  74426. }
  74427. if (this.volumetricLightPostProcess) {
  74428. this.volumetricLightPostProcess.dispose(camera);
  74429. }
  74430. if (this.volumetricLightSmoothXPostProcess) {
  74431. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74432. }
  74433. if (this.volumetricLightSmoothYPostProcess) {
  74434. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74435. }
  74436. if (this.volumetricLightMergePostProces) {
  74437. this.volumetricLightMergePostProces.dispose(camera);
  74438. }
  74439. if (this.volumetricLightFinalPostProcess) {
  74440. this.volumetricLightFinalPostProcess.dispose(camera);
  74441. }
  74442. if (this.lensFlarePostProcess) {
  74443. this.lensFlarePostProcess.dispose(camera);
  74444. }
  74445. if (this.lensFlareComposePostProcess) {
  74446. this.lensFlareComposePostProcess.dispose(camera);
  74447. }
  74448. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74449. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74450. }
  74451. if (this.luminancePostProcess) {
  74452. this.luminancePostProcess.dispose(camera);
  74453. }
  74454. if (this.hdrPostProcess) {
  74455. this.hdrPostProcess.dispose(camera);
  74456. }
  74457. if (this.hdrFinalPostProcess) {
  74458. this.hdrFinalPostProcess.dispose(camera);
  74459. }
  74460. if (this.depthOfFieldPostProcess) {
  74461. this.depthOfFieldPostProcess.dispose(camera);
  74462. }
  74463. if (this.motionBlurPostProcess) {
  74464. this.motionBlurPostProcess.dispose(camera);
  74465. }
  74466. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74467. this.blurHPostProcesses[j].dispose(camera);
  74468. }
  74469. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74470. this.blurVPostProcesses[j].dispose(camera);
  74471. }
  74472. }
  74473. this.originalPostProcess = null;
  74474. this.downSampleX4PostProcess = null;
  74475. this.brightPassPostProcess = null;
  74476. this.textureAdderPostProcess = null;
  74477. this.textureAdderFinalPostProcess = null;
  74478. this.volumetricLightPostProcess = null;
  74479. this.volumetricLightSmoothXPostProcess = null;
  74480. this.volumetricLightSmoothYPostProcess = null;
  74481. this.volumetricLightMergePostProces = null;
  74482. this.volumetricLightFinalPostProcess = null;
  74483. this.lensFlarePostProcess = null;
  74484. this.lensFlareComposePostProcess = null;
  74485. this.luminancePostProcess = null;
  74486. this.hdrPostProcess = null;
  74487. this.hdrFinalPostProcess = null;
  74488. this.depthOfFieldPostProcess = null;
  74489. this.motionBlurPostProcess = null;
  74490. this.luminanceDownSamplePostProcesses = [];
  74491. this.blurHPostProcesses = [];
  74492. this.blurVPostProcesses = [];
  74493. };
  74494. /**
  74495. * Dispose of the pipeline and stop all post processes
  74496. */
  74497. StandardRenderingPipeline.prototype.dispose = function () {
  74498. this._disposePostProcesses();
  74499. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74500. _super.prototype.dispose.call(this);
  74501. };
  74502. /**
  74503. * Serialize the rendering pipeline (Used when exporting)
  74504. * @returns the serialized object
  74505. */
  74506. StandardRenderingPipeline.prototype.serialize = function () {
  74507. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74508. if (this.sourceLight) {
  74509. serializationObject.sourceLightId = this.sourceLight.id;
  74510. }
  74511. serializationObject.customType = "StandardRenderingPipeline";
  74512. return serializationObject;
  74513. };
  74514. /**
  74515. * Parse the serialized pipeline
  74516. * @param source Source pipeline.
  74517. * @param scene The scene to load the pipeline to.
  74518. * @param rootUrl The URL of the serialized pipeline.
  74519. * @returns An instantiated pipeline from the serialized object.
  74520. */
  74521. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74522. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74523. if (source.sourceLightId) {
  74524. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74525. }
  74526. return p;
  74527. };
  74528. // Luminance steps
  74529. StandardRenderingPipeline.LuminanceSteps = 6;
  74530. __decorate([
  74531. BABYLON.serialize()
  74532. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74533. __decorate([
  74534. BABYLON.serialize()
  74535. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74536. __decorate([
  74537. BABYLON.serialize()
  74538. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74539. __decorate([
  74540. BABYLON.serialize()
  74541. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74542. __decorate([
  74543. BABYLON.serializeAsTexture("lensTexture")
  74544. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74545. __decorate([
  74546. BABYLON.serialize()
  74547. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74548. __decorate([
  74549. BABYLON.serialize()
  74550. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74551. __decorate([
  74552. BABYLON.serialize()
  74553. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74554. __decorate([
  74555. BABYLON.serialize()
  74556. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74557. __decorate([
  74558. BABYLON.serialize()
  74559. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74560. __decorate([
  74561. BABYLON.serialize()
  74562. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74563. __decorate([
  74564. BABYLON.serializeAsTexture("lensColorTexture")
  74565. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74566. __decorate([
  74567. BABYLON.serialize()
  74568. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74569. __decorate([
  74570. BABYLON.serialize()
  74571. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74572. __decorate([
  74573. BABYLON.serialize()
  74574. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74575. __decorate([
  74576. BABYLON.serialize()
  74577. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74578. __decorate([
  74579. BABYLON.serializeAsTexture("lensStarTexture")
  74580. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74581. __decorate([
  74582. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74583. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74584. __decorate([
  74585. BABYLON.serialize()
  74586. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74587. __decorate([
  74588. BABYLON.serialize()
  74589. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74590. __decorate([
  74591. BABYLON.serialize()
  74592. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74593. __decorate([
  74594. BABYLON.serialize()
  74595. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74596. __decorate([
  74597. BABYLON.serialize()
  74598. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74599. __decorate([
  74600. BABYLON.serialize()
  74601. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74602. __decorate([
  74603. BABYLON.serialize()
  74604. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74605. __decorate([
  74606. BABYLON.serialize()
  74607. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74608. __decorate([
  74609. BABYLON.serialize()
  74610. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74611. __decorate([
  74612. BABYLON.serialize()
  74613. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74614. __decorate([
  74615. BABYLON.serialize()
  74616. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74617. __decorate([
  74618. BABYLON.serialize()
  74619. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74620. return StandardRenderingPipeline;
  74621. }(BABYLON.PostProcessRenderPipeline));
  74622. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74623. })(BABYLON || (BABYLON = {}));
  74624. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74625. var BABYLON;
  74626. (function (BABYLON) {
  74627. var FxaaPostProcess = /** @class */ (function (_super) {
  74628. __extends(FxaaPostProcess, _super);
  74629. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74630. if (camera === void 0) { camera = null; }
  74631. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74632. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74633. var defines = _this._getDefines();
  74634. _this.updateEffect(defines);
  74635. _this.onApplyObservable.add(function (effect) {
  74636. var texelSize = _this.texelSize;
  74637. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74638. });
  74639. return _this;
  74640. }
  74641. FxaaPostProcess.prototype._getDefines = function () {
  74642. var engine = this.getEngine();
  74643. if (!engine) {
  74644. return null;
  74645. }
  74646. var glInfo = engine.getGlInfo();
  74647. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74648. return "#define MALI 1\n";
  74649. }
  74650. return null;
  74651. };
  74652. return FxaaPostProcess;
  74653. }(BABYLON.PostProcess));
  74654. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74655. })(BABYLON || (BABYLON = {}));
  74656. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74657. var BABYLON;
  74658. (function (BABYLON) {
  74659. /**
  74660. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74661. */
  74662. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74663. __extends(ChromaticAberrationPostProcess, _super);
  74664. /**
  74665. * Creates a new instance ChromaticAberrationPostProcess
  74666. * @param name The name of the effect.
  74667. * @param screenWidth The width of the screen to apply the effect on.
  74668. * @param screenHeight The height of the screen to apply the effect on.
  74669. * @param options The required width/height ratio to downsize to before computing the render pass.
  74670. * @param camera The camera to apply the render pass to.
  74671. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74672. * @param engine The engine which the post process will be applied. (default: current engine)
  74673. * @param reusable If the post process can be reused on the same frame. (default: false)
  74674. * @param textureType Type of textures used when performing the post process. (default: 0)
  74675. * @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)
  74676. */
  74677. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74678. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74679. if (blockCompilation === void 0) { blockCompilation = false; }
  74680. 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;
  74681. /**
  74682. * The amount of seperation of rgb channels (default: 30)
  74683. */
  74684. _this.aberrationAmount = 30;
  74685. /**
  74686. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74687. */
  74688. _this.radialIntensity = 0;
  74689. /**
  74690. * 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))
  74691. */
  74692. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74693. /**
  74694. * 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))
  74695. */
  74696. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74697. _this.onApplyObservable.add(function (effect) {
  74698. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74699. effect.setFloat('screen_width', screenWidth);
  74700. effect.setFloat('screen_height', screenHeight);
  74701. effect.setFloat('radialIntensity', _this.radialIntensity);
  74702. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74703. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74704. });
  74705. return _this;
  74706. }
  74707. return ChromaticAberrationPostProcess;
  74708. }(BABYLON.PostProcess));
  74709. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74710. })(BABYLON || (BABYLON = {}));
  74711. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74712. var BABYLON;
  74713. (function (BABYLON) {
  74714. /**
  74715. * The GrainPostProcess adds noise to the image at mid luminance levels
  74716. */
  74717. var GrainPostProcess = /** @class */ (function (_super) {
  74718. __extends(GrainPostProcess, _super);
  74719. /**
  74720. * Creates a new instance of @see GrainPostProcess
  74721. * @param name The name of the effect.
  74722. * @param options The required width/height ratio to downsize to before computing the render pass.
  74723. * @param camera The camera to apply the render pass to.
  74724. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74725. * @param engine The engine which the post process will be applied. (default: current engine)
  74726. * @param reusable If the post process can be reused on the same frame. (default: false)
  74727. * @param textureType Type of textures used when performing the post process. (default: 0)
  74728. * @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)
  74729. */
  74730. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74731. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74732. if (blockCompilation === void 0) { blockCompilation = false; }
  74733. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74734. /**
  74735. * The intensity of the grain added (default: 30)
  74736. */
  74737. _this.intensity = 30;
  74738. /**
  74739. * If the grain should be randomized on every frame
  74740. */
  74741. _this.animated = false;
  74742. _this.onApplyObservable.add(function (effect) {
  74743. effect.setFloat('intensity', _this.intensity);
  74744. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74745. });
  74746. return _this;
  74747. }
  74748. return GrainPostProcess;
  74749. }(BABYLON.PostProcess));
  74750. BABYLON.GrainPostProcess = GrainPostProcess;
  74751. })(BABYLON || (BABYLON = {}));
  74752. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74753. var BABYLON;
  74754. (function (BABYLON) {
  74755. /**
  74756. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74757. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74758. */
  74759. var SharpenPostProcess = /** @class */ (function (_super) {
  74760. __extends(SharpenPostProcess, _super);
  74761. /**
  74762. * Creates a new instance ConvolutionPostProcess
  74763. * @param name The name of the effect.
  74764. * @param options The required width/height ratio to downsize to before computing the render pass.
  74765. * @param camera The camera to apply the render pass to.
  74766. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74767. * @param engine The engine which the post process will be applied. (default: current engine)
  74768. * @param reusable If the post process can be reused on the same frame. (default: false)
  74769. * @param textureType Type of textures used when performing the post process. (default: 0)
  74770. * @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)
  74771. */
  74772. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74773. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74774. if (blockCompilation === void 0) { blockCompilation = false; }
  74775. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74776. /**
  74777. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74778. */
  74779. _this.colorAmount = 1.0;
  74780. /**
  74781. * How much sharpness should be applied (default: 0.3)
  74782. */
  74783. _this.edgeAmount = 0.3;
  74784. _this.onApply = function (effect) {
  74785. effect.setFloat2("screenSize", _this.width, _this.height);
  74786. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74787. };
  74788. return _this;
  74789. }
  74790. return SharpenPostProcess;
  74791. }(BABYLON.PostProcess));
  74792. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74793. })(BABYLON || (BABYLON = {}));
  74794. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74795. var BABYLON;
  74796. (function (BABYLON) {
  74797. /**
  74798. * The Blur Post Process which blurs an image based on a kernel and direction.
  74799. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74800. */
  74801. var BlurPostProcess = /** @class */ (function (_super) {
  74802. __extends(BlurPostProcess, _super);
  74803. /**
  74804. * Creates a new instance BlurPostProcess
  74805. * @param name The name of the effect.
  74806. * @param direction The direction in which to blur the image.
  74807. * @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.
  74808. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74809. * @param camera The camera to apply the render pass to.
  74810. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74811. * @param engine The engine which the post process will be applied. (default: current engine)
  74812. * @param reusable If the post process can be reused on the same frame. (default: false)
  74813. * @param textureType Type of textures used when performing the post process. (default: 0)
  74814. * @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)
  74815. */
  74816. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74818. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74819. if (defines === void 0) { defines = ""; }
  74820. if (blockCompilation === void 0) { blockCompilation = false; }
  74821. 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;
  74822. _this.direction = direction;
  74823. _this.blockCompilation = blockCompilation;
  74824. _this._packedFloat = false;
  74825. _this._staticDefines = "";
  74826. _this._staticDefines = defines;
  74827. _this.onApplyObservable.add(function (effect) {
  74828. if (_this._outputTexture) {
  74829. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74830. }
  74831. else {
  74832. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74833. }
  74834. });
  74835. _this.kernel = kernel;
  74836. return _this;
  74837. }
  74838. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74839. /**
  74840. * Gets the length in pixels of the blur sample region
  74841. */
  74842. get: function () {
  74843. return this._idealKernel;
  74844. },
  74845. /**
  74846. * Sets the length in pixels of the blur sample region
  74847. */
  74848. set: function (v) {
  74849. if (this._idealKernel === v) {
  74850. return;
  74851. }
  74852. v = Math.max(v, 1);
  74853. this._idealKernel = v;
  74854. this._kernel = this._nearestBestKernel(v);
  74855. if (!this.blockCompilation) {
  74856. this._updateParameters();
  74857. }
  74858. },
  74859. enumerable: true,
  74860. configurable: true
  74861. });
  74862. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74863. /**
  74864. * Gets wether or not the blur is unpacking/repacking floats
  74865. */
  74866. get: function () {
  74867. return this._packedFloat;
  74868. },
  74869. /**
  74870. * Sets wether or not the blur needs to unpack/repack floats
  74871. */
  74872. set: function (v) {
  74873. if (this._packedFloat === v) {
  74874. return;
  74875. }
  74876. this._packedFloat = v;
  74877. if (!this.blockCompilation) {
  74878. this._updateParameters();
  74879. }
  74880. },
  74881. enumerable: true,
  74882. configurable: true
  74883. });
  74884. /**
  74885. * Updates the effect with the current post process compile time values and recompiles the shader.
  74886. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74887. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74888. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74889. * @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
  74890. * @param onCompiled Called when the shader has been compiled.
  74891. * @param onError Called if there is an error when compiling a shader.
  74892. */
  74893. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74894. if (defines === void 0) { defines = null; }
  74895. if (uniforms === void 0) { uniforms = null; }
  74896. if (samplers === void 0) { samplers = null; }
  74897. this._updateParameters(onCompiled, onError);
  74898. };
  74899. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74900. // Generate sampling offsets and weights
  74901. var N = this._kernel;
  74902. var centerIndex = (N - 1) / 2;
  74903. // Generate Gaussian sampling weights over kernel
  74904. var offsets = [];
  74905. var weights = [];
  74906. var totalWeight = 0;
  74907. for (var i = 0; i < N; i++) {
  74908. var u = i / (N - 1);
  74909. var w = this._gaussianWeight(u * 2.0 - 1);
  74910. offsets[i] = (i - centerIndex);
  74911. weights[i] = w;
  74912. totalWeight += w;
  74913. }
  74914. // Normalize weights
  74915. for (var i = 0; i < weights.length; i++) {
  74916. weights[i] /= totalWeight;
  74917. }
  74918. // Optimize: combine samples to take advantage of hardware linear sampling
  74919. // Walk from left to center, combining pairs (symmetrically)
  74920. var linearSamplingWeights = [];
  74921. var linearSamplingOffsets = [];
  74922. var linearSamplingMap = [];
  74923. for (var i = 0; i <= centerIndex; i += 2) {
  74924. var j = Math.min(i + 1, Math.floor(centerIndex));
  74925. var singleCenterSample = i === j;
  74926. if (singleCenterSample) {
  74927. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74928. }
  74929. else {
  74930. var sharedCell = j === centerIndex;
  74931. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74932. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74933. if (offsetLinear === 0) {
  74934. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74935. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74936. }
  74937. else {
  74938. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74939. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74940. }
  74941. }
  74942. }
  74943. for (var i = 0; i < linearSamplingMap.length; i++) {
  74944. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74945. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74946. }
  74947. // Replace with optimized
  74948. offsets = linearSamplingOffsets;
  74949. weights = linearSamplingWeights;
  74950. // Generate shaders
  74951. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74952. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74953. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74954. var defines = "";
  74955. defines += this._staticDefines;
  74956. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74957. if (this._staticDefines.indexOf("DOF") != -1) {
  74958. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74959. varyingCount--;
  74960. }
  74961. for (var i = 0; i < varyingCount; i++) {
  74962. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74963. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74964. }
  74965. var depCount = 0;
  74966. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74967. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74968. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74969. depCount++;
  74970. }
  74971. if (this.packedFloat) {
  74972. defines += "#define PACKEDFLOAT 1";
  74973. }
  74974. this.blockCompilation = false;
  74975. _super.prototype.updateEffect.call(this, defines, null, null, {
  74976. varyingCount: varyingCount,
  74977. depCount: depCount
  74978. }, onCompiled, onError);
  74979. };
  74980. /**
  74981. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74982. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74983. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74984. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74985. * The gaps between physical kernels are compensated for in the weighting of the samples
  74986. * @param idealKernel Ideal blur kernel.
  74987. * @return Nearest best kernel.
  74988. */
  74989. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74990. var v = Math.round(idealKernel);
  74991. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74992. var k = _a[_i];
  74993. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74994. return Math.max(k, 3);
  74995. }
  74996. }
  74997. return Math.max(v, 3);
  74998. };
  74999. /**
  75000. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75001. * @param x The point on the Gaussian distribution to sample.
  75002. * @return the value of the Gaussian function at x.
  75003. */
  75004. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75005. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75006. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75007. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75008. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75009. // truncated at around 1.3% of peak strength.
  75010. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75011. var sigma = (1 / 3);
  75012. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75013. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75014. var weight = (1.0 / denominator) * Math.exp(exponent);
  75015. return weight;
  75016. };
  75017. /**
  75018. * Generates a string that can be used as a floating point number in GLSL.
  75019. * @param x Value to print.
  75020. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75021. * @return GLSL float string.
  75022. */
  75023. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75024. if (decimalFigures === void 0) { decimalFigures = 8; }
  75025. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75026. };
  75027. return BlurPostProcess;
  75028. }(BABYLON.PostProcess));
  75029. BABYLON.BlurPostProcess = BlurPostProcess;
  75030. })(BABYLON || (BABYLON = {}));
  75031. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75032. var BABYLON;
  75033. (function (BABYLON) {
  75034. /**
  75035. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75036. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75037. * based on samples that have a large difference in distance than the center pixel.
  75038. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75039. */
  75040. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75041. __extends(DepthOfFieldBlurPostProcess, _super);
  75042. /**
  75043. * Creates a new instance CircleOfConfusionPostProcess
  75044. * @param name The name of the effect.
  75045. * @param scene The scene the effect belongs to.
  75046. * @param direction The direction the blur should be applied.
  75047. * @param kernel The size of the kernel used to blur.
  75048. * @param options The required width/height ratio to downsize to before computing the render pass.
  75049. * @param camera The camera to apply the render pass to.
  75050. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75051. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75052. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75053. * @param engine The engine which the post process will be applied. (default: current engine)
  75054. * @param reusable If the post process can be reused on the same frame. (default: false)
  75055. * @param textureType Type of textures used when performing the post process. (default: 0)
  75056. * @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)
  75057. */
  75058. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75059. if (imageToBlur === void 0) { imageToBlur = null; }
  75060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75061. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75062. if (blockCompilation === void 0) { blockCompilation = false; }
  75063. 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;
  75064. _this.direction = direction;
  75065. _this.onApplyObservable.add(function (effect) {
  75066. if (imageToBlur != null) {
  75067. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75068. }
  75069. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75070. if (scene.activeCamera) {
  75071. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75072. }
  75073. });
  75074. return _this;
  75075. }
  75076. return DepthOfFieldBlurPostProcess;
  75077. }(BABYLON.BlurPostProcess));
  75078. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75079. })(BABYLON || (BABYLON = {}));
  75080. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75081. var BABYLON;
  75082. (function (BABYLON) {
  75083. /**
  75084. * Options to be set when merging outputs from the default pipeline.
  75085. */
  75086. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75087. function DepthOfFieldMergePostProcessOptions() {
  75088. }
  75089. return DepthOfFieldMergePostProcessOptions;
  75090. }());
  75091. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75092. /**
  75093. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75094. */
  75095. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75096. __extends(DepthOfFieldMergePostProcess, _super);
  75097. /**
  75098. * Creates a new instance of DepthOfFieldMergePostProcess
  75099. * @param name The name of the effect.
  75100. * @param originalFromInput Post process which's input will be used for the merge.
  75101. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75102. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75103. * @param options The required width/height ratio to downsize to before computing the render pass.
  75104. * @param camera The camera to apply the render pass to.
  75105. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75106. * @param engine The engine which the post process will be applied. (default: current engine)
  75107. * @param reusable If the post process can be reused on the same frame. (default: false)
  75108. * @param textureType Type of textures used when performing the post process. (default: 0)
  75109. * @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)
  75110. */
  75111. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75112. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75113. if (blockCompilation === void 0) { blockCompilation = false; }
  75114. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75115. _this.blurSteps = blurSteps;
  75116. _this.onApplyObservable.add(function (effect) {
  75117. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75118. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75119. blurSteps.forEach(function (step, index) {
  75120. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75121. });
  75122. });
  75123. if (!blockCompilation) {
  75124. _this.updateEffect();
  75125. }
  75126. return _this;
  75127. }
  75128. /**
  75129. * Updates the effect with the current post process compile time values and recompiles the shader.
  75130. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75131. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75132. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75133. * @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
  75134. * @param onCompiled Called when the shader has been compiled.
  75135. * @param onError Called if there is an error when compiling a shader.
  75136. */
  75137. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75138. if (defines === void 0) { defines = null; }
  75139. if (uniforms === void 0) { uniforms = null; }
  75140. if (samplers === void 0) { samplers = null; }
  75141. if (!defines) {
  75142. defines = "";
  75143. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75144. }
  75145. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75146. };
  75147. return DepthOfFieldMergePostProcess;
  75148. }(BABYLON.PostProcess));
  75149. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75150. })(BABYLON || (BABYLON = {}));
  75151. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75152. var BABYLON;
  75153. (function (BABYLON) {
  75154. /**
  75155. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75156. */
  75157. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75158. __extends(CircleOfConfusionPostProcess, _super);
  75159. /**
  75160. * Creates a new instance CircleOfConfusionPostProcess
  75161. * @param name The name of the effect.
  75162. * @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.
  75163. * @param options The required width/height ratio to downsize to before computing the render pass.
  75164. * @param camera The camera to apply the render pass to.
  75165. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75166. * @param engine The engine which the post process will be applied. (default: current engine)
  75167. * @param reusable If the post process can be reused on the same frame. (default: false)
  75168. * @param textureType Type of textures used when performing the post process. (default: 0)
  75169. * @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)
  75170. */
  75171. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75172. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75173. if (blockCompilation === void 0) { blockCompilation = false; }
  75174. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75175. /**
  75176. * 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.
  75177. */
  75178. _this.lensSize = 50;
  75179. /**
  75180. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75181. */
  75182. _this.fStop = 1.4;
  75183. /**
  75184. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75185. */
  75186. _this.focusDistance = 2000;
  75187. /**
  75188. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75189. */
  75190. _this.focalLength = 50;
  75191. _this._depthTexture = null;
  75192. _this._depthTexture = depthTexture;
  75193. _this.onApplyObservable.add(function (effect) {
  75194. if (!_this._depthTexture) {
  75195. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75196. return;
  75197. }
  75198. effect.setTexture("depthSampler", _this._depthTexture);
  75199. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75200. var aperture = _this.lensSize / _this.fStop;
  75201. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75202. effect.setFloat('focusDistance', _this.focusDistance);
  75203. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75204. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75205. });
  75206. return _this;
  75207. }
  75208. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75209. /**
  75210. * 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.
  75211. */
  75212. set: function (value) {
  75213. this._depthTexture = value;
  75214. },
  75215. enumerable: true,
  75216. configurable: true
  75217. });
  75218. return CircleOfConfusionPostProcess;
  75219. }(BABYLON.PostProcess));
  75220. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75221. })(BABYLON || (BABYLON = {}));
  75222. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75223. var BABYLON;
  75224. (function (BABYLON) {
  75225. /**
  75226. * Specifies the level of max blur that should be applied when using the depth of field effect
  75227. */
  75228. var DepthOfFieldEffectBlurLevel;
  75229. (function (DepthOfFieldEffectBlurLevel) {
  75230. /**
  75231. * Subtle blur
  75232. */
  75233. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75234. /**
  75235. * Medium blur
  75236. */
  75237. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75238. /**
  75239. * Large blur
  75240. */
  75241. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75242. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75243. ;
  75244. /**
  75245. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75246. */
  75247. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75248. __extends(DepthOfFieldEffect, _super);
  75249. /**
  75250. * Creates a new instance DepthOfFieldEffect
  75251. * @param scene The scene the effect belongs to.
  75252. * @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.
  75253. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75254. * @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)
  75255. */
  75256. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75257. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75258. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75259. if (blockCompilation === void 0) { blockCompilation = false; }
  75260. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75261. return _this._effects;
  75262. }, true) || this;
  75263. /**
  75264. * Internal post processes in depth of field effect
  75265. */
  75266. _this._effects = [];
  75267. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75268. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75269. // 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)
  75270. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75271. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75272. _this._depthOfFieldBlurY = [];
  75273. _this._depthOfFieldBlurX = [];
  75274. var blurCount = 1;
  75275. var kernelSize = 15;
  75276. switch (blurLevel) {
  75277. case DepthOfFieldEffectBlurLevel.High: {
  75278. blurCount = 3;
  75279. kernelSize = 51;
  75280. break;
  75281. }
  75282. case DepthOfFieldEffectBlurLevel.Medium: {
  75283. blurCount = 2;
  75284. kernelSize = 31;
  75285. break;
  75286. }
  75287. default: {
  75288. kernelSize = 15;
  75289. blurCount = 1;
  75290. break;
  75291. }
  75292. }
  75293. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75294. var ratio = 1.0;
  75295. for (var i = 0; i < blurCount; i++) {
  75296. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75297. blurY.autoClear = false;
  75298. ratio = 0.75 / Math.pow(2, i);
  75299. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75300. blurX.autoClear = false;
  75301. _this._depthOfFieldBlurY.push(blurY);
  75302. _this._depthOfFieldBlurX.push(blurX);
  75303. }
  75304. // Set all post processes on the effect.
  75305. _this._effects = [_this._circleOfConfusion];
  75306. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75307. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75308. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75309. }
  75310. // Merge blurred images with original image based on circleOfConfusion
  75311. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75312. _this._dofMerge.autoClear = false;
  75313. _this._effects.push(_this._dofMerge);
  75314. return _this;
  75315. }
  75316. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75317. get: function () {
  75318. return this._circleOfConfusion.focalLength;
  75319. },
  75320. /**
  75321. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75322. */
  75323. set: function (value) {
  75324. this._circleOfConfusion.focalLength = value;
  75325. },
  75326. enumerable: true,
  75327. configurable: true
  75328. });
  75329. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75330. get: function () {
  75331. return this._circleOfConfusion.fStop;
  75332. },
  75333. /**
  75334. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75335. */
  75336. set: function (value) {
  75337. this._circleOfConfusion.fStop = value;
  75338. },
  75339. enumerable: true,
  75340. configurable: true
  75341. });
  75342. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75343. get: function () {
  75344. return this._circleOfConfusion.focusDistance;
  75345. },
  75346. /**
  75347. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75348. */
  75349. set: function (value) {
  75350. this._circleOfConfusion.focusDistance = value;
  75351. },
  75352. enumerable: true,
  75353. configurable: true
  75354. });
  75355. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75356. get: function () {
  75357. return this._circleOfConfusion.lensSize;
  75358. },
  75359. /**
  75360. * 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.
  75361. */
  75362. set: function (value) {
  75363. this._circleOfConfusion.lensSize = value;
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75369. /**
  75370. * 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.
  75371. */
  75372. set: function (value) {
  75373. this._circleOfConfusion.depthTexture = value;
  75374. },
  75375. enumerable: true,
  75376. configurable: true
  75377. });
  75378. /**
  75379. * Disposes each of the internal effects for a given camera.
  75380. * @param camera The camera to dispose the effect on.
  75381. */
  75382. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75383. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75384. this._effects[effectIndex].dispose(camera);
  75385. }
  75386. };
  75387. /**
  75388. * Internal
  75389. */
  75390. DepthOfFieldEffect.prototype._updateEffects = function () {
  75391. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75392. this._effects[effectIndex].updateEffect();
  75393. }
  75394. };
  75395. /**
  75396. * Internal
  75397. * @returns if all the contained post processes are ready.
  75398. */
  75399. DepthOfFieldEffect.prototype._isReady = function () {
  75400. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75401. if (!this._effects[effectIndex].isReady()) {
  75402. return false;
  75403. }
  75404. }
  75405. return true;
  75406. };
  75407. return DepthOfFieldEffect;
  75408. }(BABYLON.PostProcessRenderEffect));
  75409. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75410. })(BABYLON || (BABYLON = {}));
  75411. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75412. var BABYLON;
  75413. (function (BABYLON) {
  75414. /**
  75415. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75416. */
  75417. var BloomMergePostProcess = /** @class */ (function (_super) {
  75418. __extends(BloomMergePostProcess, _super);
  75419. /**
  75420. * Creates a new instance of @see BloomMergePostProcess
  75421. * @param name The name of the effect.
  75422. * @param originalFromInput Post process which's input will be used for the merge.
  75423. * @param blurred Blurred highlights post process which's output will be used.
  75424. * @param weight Weight of the bloom to be added to the original input.
  75425. * @param options The required width/height ratio to downsize to before computing the render pass.
  75426. * @param camera The camera to apply the render pass to.
  75427. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75428. * @param engine The engine which the post process will be applied. (default: current engine)
  75429. * @param reusable If the post process can be reused on the same frame. (default: false)
  75430. * @param textureType Type of textures used when performing the post process. (default: 0)
  75431. * @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)
  75432. */
  75433. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75434. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75435. if (blockCompilation === void 0) { blockCompilation = false; }
  75436. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75437. _this.weight = weight;
  75438. _this.onApplyObservable.add(function (effect) {
  75439. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75440. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75441. effect.setFloat("bloomWeight", _this.weight);
  75442. });
  75443. if (!blockCompilation) {
  75444. _this.updateEffect();
  75445. }
  75446. return _this;
  75447. }
  75448. return BloomMergePostProcess;
  75449. }(BABYLON.PostProcess));
  75450. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75451. })(BABYLON || (BABYLON = {}));
  75452. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75453. var BABYLON;
  75454. (function (BABYLON) {
  75455. /**
  75456. * 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.
  75457. */
  75458. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75459. __extends(ExtractHighlightsPostProcess, _super);
  75460. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75461. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75462. if (blockCompilation === void 0) { blockCompilation = false; }
  75463. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75464. /**
  75465. * The luminance threshold, pixels below this value will be set to black.
  75466. */
  75467. _this.threshold = 0.9;
  75468. /**
  75469. * Internal
  75470. */
  75471. _this._exposure = 1;
  75472. /**
  75473. * Post process which has the input texture to be used when performing highlight extraction
  75474. */
  75475. _this._inputPostProcess = null;
  75476. _this.onApplyObservable.add(function (effect) {
  75477. if (_this._inputPostProcess) {
  75478. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75479. }
  75480. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75481. effect.setFloat('exposure', _this._exposure);
  75482. });
  75483. return _this;
  75484. }
  75485. return ExtractHighlightsPostProcess;
  75486. }(BABYLON.PostProcess));
  75487. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75488. })(BABYLON || (BABYLON = {}));
  75489. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75490. var BABYLON;
  75491. (function (BABYLON) {
  75492. /**
  75493. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75494. */
  75495. var BloomEffect = /** @class */ (function (_super) {
  75496. __extends(BloomEffect, _super);
  75497. /**
  75498. * Creates a new instance of @see BloomEffect
  75499. * @param scene The scene the effect belongs to.
  75500. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75501. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75502. * @param bloomWeight The the strength of bloom.
  75503. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75504. * @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)
  75505. */
  75506. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75507. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75508. if (blockCompilation === void 0) { blockCompilation = false; }
  75509. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75510. return _this._effects;
  75511. }, true) || this;
  75512. _this.bloomScale = bloomScale;
  75513. /**
  75514. * Internal
  75515. */
  75516. _this._effects = [];
  75517. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75518. _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);
  75519. _this._blurX.alwaysForcePOT = true;
  75520. _this._blurX.autoClear = false;
  75521. _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);
  75522. _this._blurY.alwaysForcePOT = true;
  75523. _this._blurY.autoClear = false;
  75524. _this.kernel = bloomKernel;
  75525. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75526. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75527. _this._merge.autoClear = false;
  75528. _this._effects.push(_this._merge);
  75529. return _this;
  75530. }
  75531. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75532. /**
  75533. * The luminance threshold to find bright areas of the image to bloom.
  75534. */
  75535. get: function () {
  75536. return this._downscale.threshold;
  75537. },
  75538. set: function (value) {
  75539. this._downscale.threshold = value;
  75540. },
  75541. enumerable: true,
  75542. configurable: true
  75543. });
  75544. Object.defineProperty(BloomEffect.prototype, "weight", {
  75545. /**
  75546. * The strength of the bloom.
  75547. */
  75548. get: function () {
  75549. return this._merge.weight;
  75550. },
  75551. set: function (value) {
  75552. this._merge.weight = value;
  75553. },
  75554. enumerable: true,
  75555. configurable: true
  75556. });
  75557. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75558. /**
  75559. * Specifies the size of the bloom blur kernel, relative to the final output size
  75560. */
  75561. get: function () {
  75562. return this._blurX.kernel / this.bloomScale;
  75563. },
  75564. set: function (value) {
  75565. this._blurX.kernel = value * this.bloomScale;
  75566. this._blurY.kernel = value * this.bloomScale;
  75567. },
  75568. enumerable: true,
  75569. configurable: true
  75570. });
  75571. /**
  75572. * Disposes each of the internal effects for a given camera.
  75573. * @param camera The camera to dispose the effect on.
  75574. */
  75575. BloomEffect.prototype.disposeEffects = function (camera) {
  75576. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75577. this._effects[effectIndex].dispose(camera);
  75578. }
  75579. };
  75580. /**
  75581. * Internal
  75582. */
  75583. BloomEffect.prototype._updateEffects = function () {
  75584. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75585. this._effects[effectIndex].updateEffect();
  75586. }
  75587. };
  75588. /**
  75589. * Internal
  75590. * @returns if all the contained post processes are ready.
  75591. */
  75592. BloomEffect.prototype._isReady = function () {
  75593. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75594. if (!this._effects[effectIndex].isReady()) {
  75595. return false;
  75596. }
  75597. }
  75598. return true;
  75599. };
  75600. return BloomEffect;
  75601. }(BABYLON.PostProcessRenderEffect));
  75602. BABYLON.BloomEffect = BloomEffect;
  75603. })(BABYLON || (BABYLON = {}));
  75604. //# sourceMappingURL=babylon.bloomEffect.js.map
  75605. var BABYLON;
  75606. (function (BABYLON) {
  75607. /**
  75608. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75609. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75610. */
  75611. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75612. __extends(DefaultRenderingPipeline, _super);
  75613. /**
  75614. * @constructor
  75615. * @param {string} name - The rendering pipeline name (default: "")
  75616. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75617. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75618. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75619. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75620. */
  75621. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75622. if (name === void 0) { name = ""; }
  75623. if (hdr === void 0) { hdr = true; }
  75624. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75625. if (automaticBuild === void 0) { automaticBuild = true; }
  75626. var _this = _super.call(this, scene.getEngine(), name) || this;
  75627. _this._originalCameras = [];
  75628. /**
  75629. * ID of the sharpen post process,
  75630. */
  75631. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75632. /**
  75633. * ID of the image processing post process;
  75634. */
  75635. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75636. /**
  75637. * ID of the Fast Approximate Anti-Aliasing post process;
  75638. */
  75639. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75640. /**
  75641. * ID of the chromatic aberration post process,
  75642. */
  75643. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75644. /**
  75645. * ID of the grain post process
  75646. */
  75647. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75648. /**
  75649. * Glow post process which adds a glow to emmisive areas of the image
  75650. */
  75651. _this._glowLayer = null;
  75652. /**
  75653. * Animations which can be used to tweak settings over a period of time
  75654. */
  75655. _this.animations = [];
  75656. _this._imageProcessingConfigurationObserver = null;
  75657. // Values
  75658. _this._sharpenEnabled = false;
  75659. _this._bloomEnabled = false;
  75660. _this._depthOfFieldEnabled = false;
  75661. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75662. _this._fxaaEnabled = false;
  75663. _this._imageProcessingEnabled = true;
  75664. _this._bloomScale = 0.5;
  75665. _this._chromaticAberrationEnabled = false;
  75666. _this._grainEnabled = false;
  75667. _this._buildAllowed = true;
  75668. _this._resizeObserver = null;
  75669. _this._hardwareScaleLevel = 1.0;
  75670. _this._bloomKernel = 64;
  75671. /**
  75672. * Specifies the weight of the bloom in the final rendering
  75673. */
  75674. _this._bloomWeight = 0.15;
  75675. /**
  75676. * Specifies the luma threshold for the area that will be blurred by the bloom
  75677. */
  75678. _this._bloomThreshold = 0.9;
  75679. _this._samples = 1;
  75680. _this._hasCleared = false;
  75681. _this._prevPostProcess = null;
  75682. _this._prevPrevPostProcess = null;
  75683. _this._cameras = cameras || scene.cameras;
  75684. _this._originalCameras = _this._cameras.slice();
  75685. _this._buildAllowed = automaticBuild;
  75686. // Initialize
  75687. _this._scene = scene;
  75688. var caps = _this._scene.getEngine().getCaps();
  75689. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75690. // Misc
  75691. if (_this._hdr) {
  75692. if (caps.textureHalfFloatRender) {
  75693. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75694. }
  75695. else if (caps.textureFloatRender) {
  75696. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75697. }
  75698. }
  75699. else {
  75700. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75701. }
  75702. // Attach
  75703. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75704. var engine = _this._scene.getEngine();
  75705. // Create post processes before hand so they can be modified before enabled.
  75706. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75707. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75708. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75709. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75710. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75711. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75712. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75713. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75714. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75715. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75716. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75717. _this.bloomKernel = _this.bloomKernel;
  75718. });
  75719. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75720. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75721. });
  75722. _this._buildPipeline();
  75723. return _this;
  75724. }
  75725. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75726. get: function () {
  75727. return this._sharpenEnabled;
  75728. },
  75729. /**
  75730. * Enable or disable the sharpen process from the pipeline
  75731. */
  75732. set: function (enabled) {
  75733. if (this._sharpenEnabled === enabled) {
  75734. return;
  75735. }
  75736. this._sharpenEnabled = enabled;
  75737. this._buildPipeline();
  75738. },
  75739. enumerable: true,
  75740. configurable: true
  75741. });
  75742. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75743. /**
  75744. * Specifies the size of the bloom blur kernel, relative to the final output size
  75745. */
  75746. get: function () {
  75747. return this._bloomKernel;
  75748. },
  75749. set: function (value) {
  75750. this._bloomKernel = value;
  75751. this.bloom.kernel = value / this._hardwareScaleLevel;
  75752. },
  75753. enumerable: true,
  75754. configurable: true
  75755. });
  75756. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75757. get: function () {
  75758. return this._bloomWeight;
  75759. },
  75760. /**
  75761. * The strength of the bloom.
  75762. */
  75763. set: function (value) {
  75764. if (this._bloomWeight === value) {
  75765. return;
  75766. }
  75767. this.bloom.weight = value;
  75768. this._bloomWeight = value;
  75769. },
  75770. enumerable: true,
  75771. configurable: true
  75772. });
  75773. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75774. get: function () {
  75775. return this._bloomThreshold;
  75776. },
  75777. /**
  75778. * The strength of the bloom.
  75779. */
  75780. set: function (value) {
  75781. if (this._bloomThreshold === value) {
  75782. return;
  75783. }
  75784. this.bloom.threshold = value;
  75785. this._bloomThreshold = value;
  75786. },
  75787. enumerable: true,
  75788. configurable: true
  75789. });
  75790. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75791. get: function () {
  75792. return this._bloomScale;
  75793. },
  75794. /**
  75795. * The scale of the bloom, lower value will provide better performance.
  75796. */
  75797. set: function (value) {
  75798. if (this._bloomScale === value) {
  75799. return;
  75800. }
  75801. this._bloomScale = value;
  75802. // recreate bloom and dispose old as this setting is not dynamic
  75803. this._rebuildBloom();
  75804. this._buildPipeline();
  75805. },
  75806. enumerable: true,
  75807. configurable: true
  75808. });
  75809. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75810. get: function () {
  75811. return this._bloomEnabled;
  75812. },
  75813. /**
  75814. * Enable or disable the bloom from the pipeline
  75815. */
  75816. set: function (enabled) {
  75817. if (this._bloomEnabled === enabled) {
  75818. return;
  75819. }
  75820. this._bloomEnabled = enabled;
  75821. this._buildPipeline();
  75822. },
  75823. enumerable: true,
  75824. configurable: true
  75825. });
  75826. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75827. // recreate bloom and dispose old as this setting is not dynamic
  75828. var oldBloom = this.bloom;
  75829. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75830. this.bloom.threshold = oldBloom.threshold;
  75831. for (var i = 0; i < this._cameras.length; i++) {
  75832. oldBloom.disposeEffects(this._cameras[i]);
  75833. }
  75834. };
  75835. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75836. /**
  75837. * If the depth of field is enabled.
  75838. */
  75839. get: function () {
  75840. return this._depthOfFieldEnabled;
  75841. },
  75842. set: function (enabled) {
  75843. if (this._depthOfFieldEnabled === enabled) {
  75844. return;
  75845. }
  75846. this._depthOfFieldEnabled = enabled;
  75847. this._buildPipeline();
  75848. },
  75849. enumerable: true,
  75850. configurable: true
  75851. });
  75852. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75853. /**
  75854. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75855. */
  75856. get: function () {
  75857. return this._depthOfFieldBlurLevel;
  75858. },
  75859. set: function (value) {
  75860. if (this._depthOfFieldBlurLevel === value) {
  75861. return;
  75862. }
  75863. this._depthOfFieldBlurLevel = value;
  75864. // recreate dof and dispose old as this setting is not dynamic
  75865. var oldDof = this.depthOfField;
  75866. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75867. this.depthOfField.focalLength = oldDof.focalLength;
  75868. this.depthOfField.focusDistance = oldDof.focusDistance;
  75869. this.depthOfField.fStop = oldDof.fStop;
  75870. this.depthOfField.lensSize = oldDof.lensSize;
  75871. for (var i = 0; i < this._cameras.length; i++) {
  75872. oldDof.disposeEffects(this._cameras[i]);
  75873. }
  75874. this._buildPipeline();
  75875. },
  75876. enumerable: true,
  75877. configurable: true
  75878. });
  75879. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75880. get: function () {
  75881. return this._fxaaEnabled;
  75882. },
  75883. /**
  75884. * If the anti aliasing is enabled.
  75885. */
  75886. set: function (enabled) {
  75887. if (this._fxaaEnabled === enabled) {
  75888. return;
  75889. }
  75890. this._fxaaEnabled = enabled;
  75891. this._buildPipeline();
  75892. },
  75893. enumerable: true,
  75894. configurable: true
  75895. });
  75896. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75897. get: function () {
  75898. return this._samples;
  75899. },
  75900. /**
  75901. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75902. */
  75903. set: function (sampleCount) {
  75904. if (this._samples === sampleCount) {
  75905. return;
  75906. }
  75907. this._samples = sampleCount;
  75908. this._buildPipeline();
  75909. },
  75910. enumerable: true,
  75911. configurable: true
  75912. });
  75913. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75914. get: function () {
  75915. return this._imageProcessingEnabled;
  75916. },
  75917. /**
  75918. * If image processing is enabled.
  75919. */
  75920. set: function (enabled) {
  75921. if (this._imageProcessingEnabled === enabled) {
  75922. return;
  75923. }
  75924. this._imageProcessingEnabled = enabled;
  75925. this._buildPipeline();
  75926. },
  75927. enumerable: true,
  75928. configurable: true
  75929. });
  75930. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75931. get: function () {
  75932. return this._glowLayer == null;
  75933. },
  75934. /**
  75935. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75936. */
  75937. set: function (enabled) {
  75938. if (enabled && !this._glowLayer) {
  75939. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75940. }
  75941. else if (!enabled && this._glowLayer) {
  75942. this._glowLayer.dispose();
  75943. this._glowLayer = null;
  75944. }
  75945. },
  75946. enumerable: true,
  75947. configurable: true
  75948. });
  75949. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75950. get: function () {
  75951. return this._chromaticAberrationEnabled;
  75952. },
  75953. /**
  75954. * Enable or disable the chromaticAberration process from the pipeline
  75955. */
  75956. set: function (enabled) {
  75957. if (this._chromaticAberrationEnabled === enabled) {
  75958. return;
  75959. }
  75960. this._chromaticAberrationEnabled = enabled;
  75961. this._buildPipeline();
  75962. },
  75963. enumerable: true,
  75964. configurable: true
  75965. });
  75966. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75967. get: function () {
  75968. return this._grainEnabled;
  75969. },
  75970. /**
  75971. * Enable or disable the grain process from the pipeline
  75972. */
  75973. set: function (enabled) {
  75974. if (this._grainEnabled === enabled) {
  75975. return;
  75976. }
  75977. this._grainEnabled = enabled;
  75978. this._buildPipeline();
  75979. },
  75980. enumerable: true,
  75981. configurable: true
  75982. });
  75983. /**
  75984. * Force the compilation of the entire pipeline.
  75985. */
  75986. DefaultRenderingPipeline.prototype.prepare = function () {
  75987. var previousState = this._buildAllowed;
  75988. this._buildAllowed = true;
  75989. this._buildPipeline();
  75990. this._buildAllowed = previousState;
  75991. };
  75992. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75993. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75994. if (this._hasCleared) {
  75995. postProcess.autoClear = false;
  75996. }
  75997. else {
  75998. postProcess.autoClear = true;
  75999. this._scene.autoClear = false;
  76000. this._hasCleared = true;
  76001. }
  76002. if (!skipTextureSharing) {
  76003. if (this._prevPrevPostProcess) {
  76004. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76005. }
  76006. else {
  76007. postProcess.useOwnOutput();
  76008. }
  76009. if (this._prevPostProcess) {
  76010. this._prevPrevPostProcess = this._prevPostProcess;
  76011. }
  76012. this._prevPostProcess = postProcess;
  76013. }
  76014. };
  76015. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76016. var _this = this;
  76017. if (!this._buildAllowed) {
  76018. return;
  76019. }
  76020. this._scene.autoClear = true;
  76021. var engine = this._scene.getEngine();
  76022. this._disposePostProcesses();
  76023. if (this._cameras !== null) {
  76024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76025. // get back cameras to be used to reattach pipeline
  76026. this._cameras = this._originalCameras.slice();
  76027. }
  76028. this._reset();
  76029. this._prevPostProcess = null;
  76030. this._prevPrevPostProcess = null;
  76031. this._hasCleared = false;
  76032. if (this.depthOfFieldEnabled) {
  76033. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76034. this.depthOfField.depthTexture = depthTexture;
  76035. if (!this.depthOfField._isReady()) {
  76036. this.depthOfField._updateEffects();
  76037. }
  76038. this.addEffect(this.depthOfField);
  76039. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76040. }
  76041. if (this.bloomEnabled) {
  76042. if (!this.bloom._isReady()) {
  76043. this.bloom._updateEffects();
  76044. }
  76045. this.addEffect(this.bloom);
  76046. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76047. }
  76048. if (this._imageProcessingEnabled) {
  76049. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76050. if (this._hdr) {
  76051. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76052. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76053. }
  76054. else {
  76055. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76056. }
  76057. }
  76058. if (this.sharpenEnabled) {
  76059. if (!this.sharpen.isReady()) {
  76060. this.sharpen.updateEffect();
  76061. }
  76062. this.addEffect(this._sharpenEffect);
  76063. this._setAutoClearAndTextureSharing(this.sharpen);
  76064. }
  76065. if (this.grainEnabled) {
  76066. if (!this.grain.isReady()) {
  76067. this.grain.updateEffect();
  76068. }
  76069. this.addEffect(this._grainEffect);
  76070. this._setAutoClearAndTextureSharing(this.grain);
  76071. }
  76072. if (this.chromaticAberrationEnabled) {
  76073. if (!this.chromaticAberration.isReady()) {
  76074. this.chromaticAberration.updateEffect();
  76075. }
  76076. this.addEffect(this._chromaticAberrationEffect);
  76077. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76078. }
  76079. if (this.fxaaEnabled) {
  76080. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76081. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76082. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76083. }
  76084. if (this._cameras !== null) {
  76085. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76086. }
  76087. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76088. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76089. }
  76090. };
  76091. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76092. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76093. for (var i = 0; i < this._cameras.length; i++) {
  76094. var camera = this._cameras[i];
  76095. if (this.imageProcessing) {
  76096. this.imageProcessing.dispose(camera);
  76097. }
  76098. if (this.fxaa) {
  76099. this.fxaa.dispose(camera);
  76100. }
  76101. // These are created in the constructor and should not be disposed on every pipeline change
  76102. if (disposeNonRecreated) {
  76103. if (this.sharpen) {
  76104. this.sharpen.dispose(camera);
  76105. }
  76106. if (this.depthOfField) {
  76107. this.depthOfField.disposeEffects(camera);
  76108. }
  76109. if (this.bloom) {
  76110. this.bloom.disposeEffects(camera);
  76111. }
  76112. if (this.chromaticAberration) {
  76113. this.chromaticAberration.dispose(camera);
  76114. }
  76115. if (this.grain) {
  76116. this.grain.dispose(camera);
  76117. }
  76118. if (this._glowLayer) {
  76119. this._glowLayer.dispose();
  76120. }
  76121. }
  76122. }
  76123. this.imageProcessing = null;
  76124. this.fxaa = null;
  76125. if (disposeNonRecreated) {
  76126. this.sharpen = null;
  76127. this._sharpenEffect = null;
  76128. this.depthOfField = null;
  76129. this.bloom = null;
  76130. this.chromaticAberration = null;
  76131. this._chromaticAberrationEffect = null;
  76132. this.grain = null;
  76133. this._grainEffect = null;
  76134. this._glowLayer = null;
  76135. }
  76136. };
  76137. /**
  76138. * Dispose of the pipeline and stop all post processes
  76139. */
  76140. DefaultRenderingPipeline.prototype.dispose = function () {
  76141. this._disposePostProcesses(true);
  76142. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76143. this._scene.autoClear = true;
  76144. if (this._resizeObserver) {
  76145. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76146. this._resizeObserver = null;
  76147. }
  76148. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76149. _super.prototype.dispose.call(this);
  76150. };
  76151. /**
  76152. * Serialize the rendering pipeline (Used when exporting)
  76153. * @returns the serialized object
  76154. */
  76155. DefaultRenderingPipeline.prototype.serialize = function () {
  76156. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76157. serializationObject.customType = "DefaultRenderingPipeline";
  76158. return serializationObject;
  76159. };
  76160. /**
  76161. * Parse the serialized pipeline
  76162. * @param source Source pipeline.
  76163. * @param scene The scene to load the pipeline to.
  76164. * @param rootUrl The URL of the serialized pipeline.
  76165. * @returns An instantiated pipeline from the serialized object.
  76166. */
  76167. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76168. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76169. };
  76170. __decorate([
  76171. BABYLON.serialize()
  76172. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76173. __decorate([
  76174. BABYLON.serialize()
  76175. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76176. __decorate([
  76177. BABYLON.serialize()
  76178. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76179. __decorate([
  76180. BABYLON.serialize()
  76181. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76182. __decorate([
  76183. BABYLON.serialize()
  76184. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76185. __decorate([
  76186. BABYLON.serialize()
  76187. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76188. __decorate([
  76189. BABYLON.serialize()
  76190. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76191. __decorate([
  76192. BABYLON.serialize()
  76193. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76194. __decorate([
  76195. BABYLON.serialize()
  76196. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76197. __decorate([
  76198. BABYLON.serialize()
  76199. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76200. __decorate([
  76201. BABYLON.serialize()
  76202. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76203. __decorate([
  76204. BABYLON.serialize()
  76205. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76206. __decorate([
  76207. BABYLON.serialize()
  76208. ], DefaultRenderingPipeline.prototype, "samples", null);
  76209. __decorate([
  76210. BABYLON.serialize()
  76211. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76212. __decorate([
  76213. BABYLON.serialize()
  76214. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76215. __decorate([
  76216. BABYLON.serialize()
  76217. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76218. __decorate([
  76219. BABYLON.serialize()
  76220. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76221. return DefaultRenderingPipeline;
  76222. }(BABYLON.PostProcessRenderPipeline));
  76223. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76224. })(BABYLON || (BABYLON = {}));
  76225. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76226. var BABYLON;
  76227. (function (BABYLON) {
  76228. /**
  76229. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76230. */
  76231. var GeometryBufferRenderer = /** @class */ (function () {
  76232. /**
  76233. * Creates a new G Buffer for the scene
  76234. * @param scene The scene the buffer belongs to
  76235. * @param ratio How big is the buffer related to the main canvas.
  76236. */
  76237. function GeometryBufferRenderer(scene, ratio) {
  76238. if (ratio === void 0) { ratio = 1; }
  76239. this._enablePosition = false;
  76240. this._scene = scene;
  76241. this._ratio = ratio;
  76242. // Render target
  76243. this._createRenderTargets();
  76244. }
  76245. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76246. /**
  76247. * Set the render list (meshes to be rendered) used in the G buffer.
  76248. */
  76249. set: function (meshes) {
  76250. this._multiRenderTarget.renderList = meshes;
  76251. },
  76252. enumerable: true,
  76253. configurable: true
  76254. });
  76255. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76256. /**
  76257. * Gets wether or not G buffer are supported by the running hardware.
  76258. * This requires draw buffer supports
  76259. */
  76260. get: function () {
  76261. return this._multiRenderTarget.isSupported;
  76262. },
  76263. enumerable: true,
  76264. configurable: true
  76265. });
  76266. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76267. /**
  76268. * Gets wether or not position are enabled for the G buffer.
  76269. */
  76270. get: function () {
  76271. return this._enablePosition;
  76272. },
  76273. /**
  76274. * Sets wether or not position are enabled for the G buffer.
  76275. */
  76276. set: function (enable) {
  76277. this._enablePosition = enable;
  76278. this.dispose();
  76279. this._createRenderTargets();
  76280. },
  76281. enumerable: true,
  76282. configurable: true
  76283. });
  76284. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76285. /**
  76286. * Gets the scene associated with the buffer.
  76287. */
  76288. get: function () {
  76289. return this._scene;
  76290. },
  76291. enumerable: true,
  76292. configurable: true
  76293. });
  76294. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76295. /**
  76296. * Gets the ratio used by the buffer during its creation.
  76297. * How big is the buffer related to the main canvas.
  76298. */
  76299. get: function () {
  76300. return this._ratio;
  76301. },
  76302. enumerable: true,
  76303. configurable: true
  76304. });
  76305. /**
  76306. * Checks wether everything is ready to render a submesh to the G buffer.
  76307. * @param subMesh the submesh to check readiness for
  76308. * @param useInstances is the mesh drawn using instance or not
  76309. * @returns true if ready otherwise false
  76310. */
  76311. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76312. var material = subMesh.getMaterial();
  76313. if (material && material.disableDepthWrite) {
  76314. return false;
  76315. }
  76316. var defines = [];
  76317. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76318. var mesh = subMesh.getMesh();
  76319. // Alpha test
  76320. if (material && material.needAlphaTesting()) {
  76321. defines.push("#define ALPHATEST");
  76322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76323. attribs.push(BABYLON.VertexBuffer.UVKind);
  76324. defines.push("#define UV1");
  76325. }
  76326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76327. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76328. defines.push("#define UV2");
  76329. }
  76330. }
  76331. // Buffers
  76332. if (this._enablePosition) {
  76333. defines.push("#define POSITION");
  76334. }
  76335. // Bones
  76336. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76339. if (mesh.numBoneInfluencers > 4) {
  76340. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76341. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76342. }
  76343. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76344. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76345. }
  76346. else {
  76347. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76348. }
  76349. // Instances
  76350. if (useInstances) {
  76351. defines.push("#define INSTANCES");
  76352. attribs.push("world0");
  76353. attribs.push("world1");
  76354. attribs.push("world2");
  76355. attribs.push("world3");
  76356. }
  76357. // Get correct effect
  76358. var join = defines.join("\n");
  76359. if (this._cachedDefines !== join) {
  76360. this._cachedDefines = join;
  76361. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76362. }
  76363. return this._effect.isReady();
  76364. };
  76365. /**
  76366. * Gets the current underlying G Buffer.
  76367. * @returns the buffer
  76368. */
  76369. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76370. return this._multiRenderTarget;
  76371. };
  76372. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76373. /**
  76374. * Gets the number of samples used to render the buffer (anti aliasing).
  76375. */
  76376. get: function () {
  76377. return this._multiRenderTarget.samples;
  76378. },
  76379. /**
  76380. * Sets the number of samples used to render the buffer (anti aliasing).
  76381. */
  76382. set: function (value) {
  76383. this._multiRenderTarget.samples = value;
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. /**
  76389. * Disposes the renderer and frees up associated resources.
  76390. */
  76391. GeometryBufferRenderer.prototype.dispose = function () {
  76392. this.getGBuffer().dispose();
  76393. };
  76394. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76395. var _this = this;
  76396. var engine = this._scene.getEngine();
  76397. var count = this._enablePosition ? 3 : 2;
  76398. 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 });
  76399. if (!this.isSupported) {
  76400. return;
  76401. }
  76402. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76403. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76404. this._multiRenderTarget.refreshRate = 1;
  76405. this._multiRenderTarget.renderParticles = false;
  76406. this._multiRenderTarget.renderList = null;
  76407. // set default depth value to 1.0 (far away)
  76408. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76409. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76410. });
  76411. // Custom render function
  76412. var renderSubMesh = function (subMesh) {
  76413. var mesh = subMesh.getRenderingMesh();
  76414. var scene = _this._scene;
  76415. var engine = scene.getEngine();
  76416. var material = subMesh.getMaterial();
  76417. if (!material) {
  76418. return;
  76419. }
  76420. // Culling
  76421. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76422. // Managing instances
  76423. var batch = mesh._getInstancesRenderList(subMesh._id);
  76424. if (batch.mustReturn) {
  76425. return;
  76426. }
  76427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76428. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76429. engine.enableEffect(_this._effect);
  76430. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76431. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76432. _this._effect.setMatrix("view", scene.getViewMatrix());
  76433. // Alpha test
  76434. if (material && material.needAlphaTesting()) {
  76435. var alphaTexture = material.getAlphaTestTexture();
  76436. if (alphaTexture) {
  76437. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76438. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76439. }
  76440. }
  76441. // Bones
  76442. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76443. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76444. }
  76445. // Draw
  76446. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76447. }
  76448. };
  76449. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76450. var index;
  76451. if (depthOnlySubMeshes.length) {
  76452. engine.setColorWrite(false);
  76453. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76454. renderSubMesh(depthOnlySubMeshes.data[index]);
  76455. }
  76456. engine.setColorWrite(true);
  76457. }
  76458. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76459. renderSubMesh(opaqueSubMeshes.data[index]);
  76460. }
  76461. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76462. renderSubMesh(alphaTestSubMeshes.data[index]);
  76463. }
  76464. };
  76465. };
  76466. return GeometryBufferRenderer;
  76467. }());
  76468. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76469. })(BABYLON || (BABYLON = {}));
  76470. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76471. var BABYLON;
  76472. (function (BABYLON) {
  76473. /**
  76474. * This groups together the common properties used for image processing either in direct forward pass
  76475. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76476. * or not.
  76477. */
  76478. var ImageProcessingConfiguration = /** @class */ (function () {
  76479. function ImageProcessingConfiguration() {
  76480. /**
  76481. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76482. */
  76483. this.colorCurves = new BABYLON.ColorCurves();
  76484. this._colorCurvesEnabled = false;
  76485. this._colorGradingEnabled = false;
  76486. this._colorGradingWithGreenDepth = true;
  76487. this._colorGradingBGR = true;
  76488. this._exposure = 1.0;
  76489. this._toneMappingEnabled = false;
  76490. this._contrast = 1.0;
  76491. /**
  76492. * Vignette stretch size.
  76493. */
  76494. this.vignetteStretch = 0;
  76495. /**
  76496. * Vignette centre X Offset.
  76497. */
  76498. this.vignetteCentreX = 0;
  76499. /**
  76500. * Vignette centre Y Offset.
  76501. */
  76502. this.vignetteCentreY = 0;
  76503. /**
  76504. * Vignette weight or intensity of the vignette effect.
  76505. */
  76506. this.vignetteWeight = 1.5;
  76507. /**
  76508. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76509. * if vignetteEnabled is set to true.
  76510. */
  76511. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76512. /**
  76513. * Camera field of view used by the Vignette effect.
  76514. */
  76515. this.vignetteCameraFov = 0.5;
  76516. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76517. this._vignetteEnabled = false;
  76518. this._applyByPostProcess = false;
  76519. this._isEnabled = true;
  76520. /**
  76521. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76522. */
  76523. this.onUpdateParameters = new BABYLON.Observable();
  76524. }
  76525. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76526. /**
  76527. * Gets wether the color curves effect is enabled.
  76528. */
  76529. get: function () {
  76530. return this._colorCurvesEnabled;
  76531. },
  76532. /**
  76533. * Sets wether the color curves effect is enabled.
  76534. */
  76535. set: function (value) {
  76536. if (this._colorCurvesEnabled === value) {
  76537. return;
  76538. }
  76539. this._colorCurvesEnabled = value;
  76540. this._updateParameters();
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76546. /**
  76547. * Gets wether the color grading effect is enabled.
  76548. */
  76549. get: function () {
  76550. return this._colorGradingEnabled;
  76551. },
  76552. /**
  76553. * Sets wether the color grading effect is enabled.
  76554. */
  76555. set: function (value) {
  76556. if (this._colorGradingEnabled === value) {
  76557. return;
  76558. }
  76559. this._colorGradingEnabled = value;
  76560. this._updateParameters();
  76561. },
  76562. enumerable: true,
  76563. configurable: true
  76564. });
  76565. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76566. /**
  76567. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76568. */
  76569. get: function () {
  76570. return this._colorGradingWithGreenDepth;
  76571. },
  76572. /**
  76573. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76574. */
  76575. set: function (value) {
  76576. if (this._colorGradingWithGreenDepth === value) {
  76577. return;
  76578. }
  76579. this._colorGradingWithGreenDepth = value;
  76580. this._updateParameters();
  76581. },
  76582. enumerable: true,
  76583. configurable: true
  76584. });
  76585. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76586. /**
  76587. * Gets wether the color grading texture contains BGR values.
  76588. */
  76589. get: function () {
  76590. return this._colorGradingBGR;
  76591. },
  76592. /**
  76593. * Sets wether the color grading texture contains BGR values.
  76594. */
  76595. set: function (value) {
  76596. if (this._colorGradingBGR === value) {
  76597. return;
  76598. }
  76599. this._colorGradingBGR = value;
  76600. this._updateParameters();
  76601. },
  76602. enumerable: true,
  76603. configurable: true
  76604. });
  76605. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76606. /**
  76607. * Gets the Exposure used in the effect.
  76608. */
  76609. get: function () {
  76610. return this._exposure;
  76611. },
  76612. /**
  76613. * Sets the Exposure used in the effect.
  76614. */
  76615. set: function (value) {
  76616. if (this._exposure === value) {
  76617. return;
  76618. }
  76619. this._exposure = value;
  76620. this._updateParameters();
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76626. /**
  76627. * Gets wether the tone mapping effect is enabled.
  76628. */
  76629. get: function () {
  76630. return this._toneMappingEnabled;
  76631. },
  76632. /**
  76633. * Sets wether the tone mapping effect is enabled.
  76634. */
  76635. set: function (value) {
  76636. if (this._toneMappingEnabled === value) {
  76637. return;
  76638. }
  76639. this._toneMappingEnabled = value;
  76640. this._updateParameters();
  76641. },
  76642. enumerable: true,
  76643. configurable: true
  76644. });
  76645. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76646. /**
  76647. * Gets the contrast used in the effect.
  76648. */
  76649. get: function () {
  76650. return this._contrast;
  76651. },
  76652. /**
  76653. * Sets the contrast used in the effect.
  76654. */
  76655. set: function (value) {
  76656. if (this._contrast === value) {
  76657. return;
  76658. }
  76659. this._contrast = value;
  76660. this._updateParameters();
  76661. },
  76662. enumerable: true,
  76663. configurable: true
  76664. });
  76665. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76666. /**
  76667. * Gets the vignette blend mode allowing different kind of effect.
  76668. */
  76669. get: function () {
  76670. return this._vignetteBlendMode;
  76671. },
  76672. /**
  76673. * Sets the vignette blend mode allowing different kind of effect.
  76674. */
  76675. set: function (value) {
  76676. if (this._vignetteBlendMode === value) {
  76677. return;
  76678. }
  76679. this._vignetteBlendMode = value;
  76680. this._updateParameters();
  76681. },
  76682. enumerable: true,
  76683. configurable: true
  76684. });
  76685. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76686. /**
  76687. * Gets wether the vignette effect is enabled.
  76688. */
  76689. get: function () {
  76690. return this._vignetteEnabled;
  76691. },
  76692. /**
  76693. * Sets wether the vignette effect is enabled.
  76694. */
  76695. set: function (value) {
  76696. if (this._vignetteEnabled === value) {
  76697. return;
  76698. }
  76699. this._vignetteEnabled = value;
  76700. this._updateParameters();
  76701. },
  76702. enumerable: true,
  76703. configurable: true
  76704. });
  76705. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76706. /**
  76707. * Gets wether the image processing is applied through a post process or not.
  76708. */
  76709. get: function () {
  76710. return this._applyByPostProcess;
  76711. },
  76712. /**
  76713. * Sets wether the image processing is applied through a post process or not.
  76714. */
  76715. set: function (value) {
  76716. if (this._applyByPostProcess === value) {
  76717. return;
  76718. }
  76719. this._applyByPostProcess = value;
  76720. this._updateParameters();
  76721. },
  76722. enumerable: true,
  76723. configurable: true
  76724. });
  76725. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76726. /**
  76727. * Gets wether the image processing is enabled or not.
  76728. */
  76729. get: function () {
  76730. return this._isEnabled;
  76731. },
  76732. /**
  76733. * Sets wether the image processing is enabled or not.
  76734. */
  76735. set: function (value) {
  76736. if (this._isEnabled === value) {
  76737. return;
  76738. }
  76739. this._isEnabled = value;
  76740. this._updateParameters();
  76741. },
  76742. enumerable: true,
  76743. configurable: true
  76744. });
  76745. /**
  76746. * Method called each time the image processing information changes requires to recompile the effect.
  76747. */
  76748. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76749. this.onUpdateParameters.notifyObservers(this);
  76750. };
  76751. ImageProcessingConfiguration.prototype.getClassName = function () {
  76752. return "ImageProcessingConfiguration";
  76753. };
  76754. /**
  76755. * Prepare the list of uniforms associated with the Image Processing effects.
  76756. * @param uniformsList The list of uniforms used in the effect
  76757. * @param defines the list of defines currently in use
  76758. */
  76759. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76760. if (defines.EXPOSURE) {
  76761. uniforms.push("exposureLinear");
  76762. }
  76763. if (defines.CONTRAST) {
  76764. uniforms.push("contrast");
  76765. }
  76766. if (defines.COLORGRADING) {
  76767. uniforms.push("colorTransformSettings");
  76768. }
  76769. if (defines.VIGNETTE) {
  76770. uniforms.push("vInverseScreenSize");
  76771. uniforms.push("vignetteSettings1");
  76772. uniforms.push("vignetteSettings2");
  76773. }
  76774. if (defines.COLORCURVES) {
  76775. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76776. }
  76777. };
  76778. /**
  76779. * Prepare the list of samplers associated with the Image Processing effects.
  76780. * @param uniformsList The list of uniforms used in the effect
  76781. * @param defines the list of defines currently in use
  76782. */
  76783. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76784. if (defines.COLORGRADING) {
  76785. samplersList.push("txColorTransform");
  76786. }
  76787. };
  76788. /**
  76789. * Prepare the list of defines associated to the shader.
  76790. * @param defines the list of defines to complete
  76791. */
  76792. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76793. if (forPostProcess === void 0) { forPostProcess = false; }
  76794. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76795. defines.VIGNETTE = false;
  76796. defines.TONEMAPPING = false;
  76797. defines.CONTRAST = false;
  76798. defines.EXPOSURE = false;
  76799. defines.COLORCURVES = false;
  76800. defines.COLORGRADING = false;
  76801. defines.COLORGRADING3D = false;
  76802. defines.IMAGEPROCESSING = false;
  76803. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76804. return;
  76805. }
  76806. defines.VIGNETTE = this.vignetteEnabled;
  76807. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76808. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76809. defines.TONEMAPPING = this.toneMappingEnabled;
  76810. defines.CONTRAST = (this.contrast !== 1.0);
  76811. defines.EXPOSURE = (this.exposure !== 1.0);
  76812. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76813. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76814. if (defines.COLORGRADING) {
  76815. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76816. }
  76817. else {
  76818. defines.COLORGRADING3D = false;
  76819. }
  76820. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76821. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76822. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76823. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76824. };
  76825. /**
  76826. * Returns true if all the image processing information are ready.
  76827. */
  76828. ImageProcessingConfiguration.prototype.isReady = function () {
  76829. // Color Grading texure can not be none blocking.
  76830. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76831. };
  76832. /**
  76833. * Binds the image processing to the shader.
  76834. * @param effect The effect to bind to
  76835. */
  76836. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76837. if (aspectRatio === void 0) { aspectRatio = 1; }
  76838. // Color Curves
  76839. if (this._colorCurvesEnabled && this.colorCurves) {
  76840. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76841. }
  76842. // Vignette
  76843. if (this._vignetteEnabled) {
  76844. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76845. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76846. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76847. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76848. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76849. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76850. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76851. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76852. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76853. var vignettePower = -2.0 * this.vignetteWeight;
  76854. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76855. }
  76856. // Exposure
  76857. effect.setFloat("exposureLinear", this.exposure);
  76858. // Contrast
  76859. effect.setFloat("contrast", this.contrast);
  76860. // Color transform settings
  76861. if (this.colorGradingTexture) {
  76862. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76863. var textureSize = this.colorGradingTexture.getSize().height;
  76864. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76865. 0.5 / textureSize, // textureOffset
  76866. textureSize, // textureSize
  76867. this.colorGradingTexture.level // weight
  76868. );
  76869. }
  76870. };
  76871. /**
  76872. * Clones the current image processing instance.
  76873. * @return The cloned image processing
  76874. */
  76875. ImageProcessingConfiguration.prototype.clone = function () {
  76876. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76877. };
  76878. /**
  76879. * Serializes the current image processing instance to a json representation.
  76880. * @return a JSON representation
  76881. */
  76882. ImageProcessingConfiguration.prototype.serialize = function () {
  76883. return BABYLON.SerializationHelper.Serialize(this);
  76884. };
  76885. /**
  76886. * Parses the image processing from a json representation.
  76887. * @param source the JSON source to parse
  76888. * @return The parsed image processing
  76889. */
  76890. ImageProcessingConfiguration.Parse = function (source) {
  76891. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76892. };
  76893. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76894. /**
  76895. * Used to apply the vignette as a mix with the pixel color.
  76896. */
  76897. get: function () {
  76898. return this._VIGNETTEMODE_MULTIPLY;
  76899. },
  76900. enumerable: true,
  76901. configurable: true
  76902. });
  76903. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76904. /**
  76905. * Used to apply the vignette as a replacement of the pixel color.
  76906. */
  76907. get: function () {
  76908. return this._VIGNETTEMODE_OPAQUE;
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. // Static constants associated to the image processing.
  76914. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76915. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76916. __decorate([
  76917. BABYLON.serializeAsColorCurves()
  76918. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76919. __decorate([
  76920. BABYLON.serialize()
  76921. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76922. __decorate([
  76923. BABYLON.serializeAsTexture()
  76924. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76925. __decorate([
  76926. BABYLON.serialize()
  76927. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76928. __decorate([
  76929. BABYLON.serialize()
  76930. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76931. __decorate([
  76932. BABYLON.serialize()
  76933. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76934. __decorate([
  76935. BABYLON.serialize()
  76936. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76937. __decorate([
  76938. BABYLON.serialize()
  76939. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76940. __decorate([
  76941. BABYLON.serialize()
  76942. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76943. __decorate([
  76944. BABYLON.serialize()
  76945. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76946. __decorate([
  76947. BABYLON.serialize()
  76948. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76949. __decorate([
  76950. BABYLON.serialize()
  76951. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76952. __decorate([
  76953. BABYLON.serialize()
  76954. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76955. __decorate([
  76956. BABYLON.serializeAsColor4()
  76957. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76958. __decorate([
  76959. BABYLON.serialize()
  76960. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76961. __decorate([
  76962. BABYLON.serialize()
  76963. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76964. __decorate([
  76965. BABYLON.serialize()
  76966. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76967. __decorate([
  76968. BABYLON.serialize()
  76969. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76970. __decorate([
  76971. BABYLON.serialize()
  76972. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76973. return ImageProcessingConfiguration;
  76974. }());
  76975. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76976. })(BABYLON || (BABYLON = {}));
  76977. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76978. var BABYLON;
  76979. (function (BABYLON) {
  76980. /**
  76981. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76982. * It can help converting any input color in a desired output one. This can then be used to create effects
  76983. * from sepia, black and white to sixties or futuristic rendering...
  76984. *
  76985. * The only supported format is currently 3dl.
  76986. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76987. */
  76988. var ColorGradingTexture = /** @class */ (function (_super) {
  76989. __extends(ColorGradingTexture, _super);
  76990. /**
  76991. * Instantiates a ColorGradingTexture from the following parameters.
  76992. *
  76993. * @param url The location of the color gradind data (currently only supporting 3dl)
  76994. * @param scene The scene the texture will be used in
  76995. */
  76996. function ColorGradingTexture(url, scene) {
  76997. var _this = _super.call(this, scene) || this;
  76998. if (!url) {
  76999. return _this;
  77000. }
  77001. _this._engine = scene.getEngine();
  77002. _this._textureMatrix = BABYLON.Matrix.Identity();
  77003. _this.name = url;
  77004. _this.url = url;
  77005. _this.hasAlpha = false;
  77006. _this.isCube = false;
  77007. _this.is3D = _this._engine.webGLVersion > 1;
  77008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77010. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77011. _this.anisotropicFilteringLevel = 1;
  77012. _this._texture = _this._getFromCache(url, true);
  77013. if (!_this._texture) {
  77014. if (!scene.useDelayedTextureLoading) {
  77015. _this.loadTexture();
  77016. }
  77017. else {
  77018. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77019. }
  77020. }
  77021. return _this;
  77022. }
  77023. /**
  77024. * Returns the texture matrix used in most of the material.
  77025. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77026. */
  77027. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77028. return this._textureMatrix;
  77029. };
  77030. /**
  77031. * Occurs when the file being loaded is a .3dl LUT file.
  77032. */
  77033. ColorGradingTexture.prototype.load3dlTexture = function () {
  77034. var engine = this._engine;
  77035. var texture;
  77036. if (engine.webGLVersion === 1) {
  77037. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77038. }
  77039. else {
  77040. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77041. }
  77042. this._texture = texture;
  77043. var callback = function (text) {
  77044. if (typeof text !== "string") {
  77045. return;
  77046. }
  77047. var data = null;
  77048. var tempData = null;
  77049. var line;
  77050. var lines = text.split('\n');
  77051. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77052. var maxColor = 0;
  77053. for (var i = 0; i < lines.length; i++) {
  77054. line = lines[i];
  77055. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77056. continue;
  77057. if (line.indexOf('#') === 0)
  77058. continue;
  77059. var words = line.split(" ");
  77060. if (size === 0) {
  77061. // Number of space + one
  77062. size = words.length;
  77063. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77064. tempData = new Float32Array(size * size * size * 4);
  77065. continue;
  77066. }
  77067. if (size != 0) {
  77068. var r = Math.max(parseInt(words[0]), 0);
  77069. var g = Math.max(parseInt(words[1]), 0);
  77070. var b = Math.max(parseInt(words[2]), 0);
  77071. maxColor = Math.max(r, maxColor);
  77072. maxColor = Math.max(g, maxColor);
  77073. maxColor = Math.max(b, maxColor);
  77074. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77075. if (tempData) {
  77076. tempData[pixelStorageIndex + 0] = r;
  77077. tempData[pixelStorageIndex + 1] = g;
  77078. tempData[pixelStorageIndex + 2] = b;
  77079. }
  77080. pixelIndexSlice++;
  77081. if (pixelIndexSlice % size == 0) {
  77082. pixelIndexH++;
  77083. pixelIndexSlice = 0;
  77084. if (pixelIndexH % size == 0) {
  77085. pixelIndexW++;
  77086. pixelIndexH = 0;
  77087. }
  77088. }
  77089. }
  77090. }
  77091. if (tempData && data) {
  77092. for (var i = 0; i < tempData.length; i++) {
  77093. if (i > 0 && (i + 1) % 4 === 0) {
  77094. data[i] = 255;
  77095. }
  77096. else {
  77097. var value = tempData[i];
  77098. data[i] = (value / maxColor * 255);
  77099. }
  77100. }
  77101. }
  77102. if (texture.is3D) {
  77103. texture.updateSize(size, size, size);
  77104. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77105. }
  77106. else {
  77107. texture.updateSize(size * size, size);
  77108. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77109. }
  77110. };
  77111. var scene = this.getScene();
  77112. if (scene) {
  77113. scene._loadFile(this.url, callback);
  77114. }
  77115. else {
  77116. this._engine._loadFile(this.url, callback);
  77117. }
  77118. return this._texture;
  77119. };
  77120. /**
  77121. * Starts the loading process of the texture.
  77122. */
  77123. ColorGradingTexture.prototype.loadTexture = function () {
  77124. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77125. this.load3dlTexture();
  77126. }
  77127. };
  77128. /**
  77129. * Clones the color gradind texture.
  77130. */
  77131. ColorGradingTexture.prototype.clone = function () {
  77132. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77133. // Base texture
  77134. newTexture.level = this.level;
  77135. return newTexture;
  77136. };
  77137. /**
  77138. * Called during delayed load for textures.
  77139. */
  77140. ColorGradingTexture.prototype.delayLoad = function () {
  77141. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77142. return;
  77143. }
  77144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77145. this._texture = this._getFromCache(this.url, true);
  77146. if (!this._texture) {
  77147. this.loadTexture();
  77148. }
  77149. };
  77150. /**
  77151. * Parses a color grading texture serialized by Babylon.
  77152. * @param parsedTexture The texture information being parsedTexture
  77153. * @param scene The scene to load the texture in
  77154. * @param rootUrl The root url of the data assets to load
  77155. * @return A color gradind texture
  77156. */
  77157. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77158. var texture = null;
  77159. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77160. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77161. texture.name = parsedTexture.name;
  77162. texture.level = parsedTexture.level;
  77163. }
  77164. return texture;
  77165. };
  77166. /**
  77167. * Serializes the LUT texture to json format.
  77168. */
  77169. ColorGradingTexture.prototype.serialize = function () {
  77170. if (!this.name) {
  77171. return null;
  77172. }
  77173. var serializationObject = {};
  77174. serializationObject.name = this.name;
  77175. serializationObject.level = this.level;
  77176. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77177. return serializationObject;
  77178. };
  77179. /**
  77180. * Empty line regex stored for GC.
  77181. */
  77182. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77183. return ColorGradingTexture;
  77184. }(BABYLON.BaseTexture));
  77185. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77186. })(BABYLON || (BABYLON = {}));
  77187. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77188. var BABYLON;
  77189. (function (BABYLON) {
  77190. /**
  77191. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77192. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77193. * 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;
  77194. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77195. */
  77196. var ColorCurves = /** @class */ (function () {
  77197. function ColorCurves() {
  77198. this._dirty = true;
  77199. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77200. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77201. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77202. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77203. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77204. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77205. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77206. this._globalHue = 30;
  77207. this._globalDensity = 0;
  77208. this._globalSaturation = 0;
  77209. this._globalExposure = 0;
  77210. this._highlightsHue = 30;
  77211. this._highlightsDensity = 0;
  77212. this._highlightsSaturation = 0;
  77213. this._highlightsExposure = 0;
  77214. this._midtonesHue = 30;
  77215. this._midtonesDensity = 0;
  77216. this._midtonesSaturation = 0;
  77217. this._midtonesExposure = 0;
  77218. this._shadowsHue = 30;
  77219. this._shadowsDensity = 0;
  77220. this._shadowsSaturation = 0;
  77221. this._shadowsExposure = 0;
  77222. }
  77223. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77224. /**
  77225. * Gets the global Hue value.
  77226. * 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).
  77227. */
  77228. get: function () {
  77229. return this._globalHue;
  77230. },
  77231. /**
  77232. * Sets the global Hue value.
  77233. * 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).
  77234. */
  77235. set: function (value) {
  77236. this._globalHue = value;
  77237. this._dirty = true;
  77238. },
  77239. enumerable: true,
  77240. configurable: true
  77241. });
  77242. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77243. /**
  77244. * Gets the global Density value.
  77245. * 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.
  77246. * Values less than zero provide a filter of opposite hue.
  77247. */
  77248. get: function () {
  77249. return this._globalDensity;
  77250. },
  77251. /**
  77252. * Sets the global Density value.
  77253. * 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.
  77254. * Values less than zero provide a filter of opposite hue.
  77255. */
  77256. set: function (value) {
  77257. this._globalDensity = value;
  77258. this._dirty = true;
  77259. },
  77260. enumerable: true,
  77261. configurable: true
  77262. });
  77263. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77264. /**
  77265. * Gets the global Saturation value.
  77266. * 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.
  77267. */
  77268. get: function () {
  77269. return this._globalSaturation;
  77270. },
  77271. /**
  77272. * Sets the global Saturation value.
  77273. * 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.
  77274. */
  77275. set: function (value) {
  77276. this._globalSaturation = value;
  77277. this._dirty = true;
  77278. },
  77279. enumerable: true,
  77280. configurable: true
  77281. });
  77282. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77283. /**
  77284. * Gets the global Exposure value.
  77285. * 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.
  77286. */
  77287. get: function () {
  77288. return this._globalExposure;
  77289. },
  77290. /**
  77291. * Sets the global Exposure value.
  77292. * 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.
  77293. */
  77294. set: function (value) {
  77295. this._globalExposure = value;
  77296. this._dirty = true;
  77297. },
  77298. enumerable: true,
  77299. configurable: true
  77300. });
  77301. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77302. /**
  77303. * Gets the highlights Hue value.
  77304. * 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).
  77305. */
  77306. get: function () {
  77307. return this._highlightsHue;
  77308. },
  77309. /**
  77310. * Sets the highlights Hue value.
  77311. * 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).
  77312. */
  77313. set: function (value) {
  77314. this._highlightsHue = value;
  77315. this._dirty = true;
  77316. },
  77317. enumerable: true,
  77318. configurable: true
  77319. });
  77320. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77321. /**
  77322. * Gets the highlights Density value.
  77323. * 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.
  77324. * Values less than zero provide a filter of opposite hue.
  77325. */
  77326. get: function () {
  77327. return this._highlightsDensity;
  77328. },
  77329. /**
  77330. * Sets the highlights Density value.
  77331. * 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.
  77332. * Values less than zero provide a filter of opposite hue.
  77333. */
  77334. set: function (value) {
  77335. this._highlightsDensity = value;
  77336. this._dirty = true;
  77337. },
  77338. enumerable: true,
  77339. configurable: true
  77340. });
  77341. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77342. /**
  77343. * Gets the highlights Saturation value.
  77344. * 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.
  77345. */
  77346. get: function () {
  77347. return this._highlightsSaturation;
  77348. },
  77349. /**
  77350. * Sets the highlights Saturation value.
  77351. * 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.
  77352. */
  77353. set: function (value) {
  77354. this._highlightsSaturation = value;
  77355. this._dirty = true;
  77356. },
  77357. enumerable: true,
  77358. configurable: true
  77359. });
  77360. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77361. /**
  77362. * Gets the highlights Exposure value.
  77363. * 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.
  77364. */
  77365. get: function () {
  77366. return this._highlightsExposure;
  77367. },
  77368. /**
  77369. * Sets the highlights Exposure value.
  77370. * 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.
  77371. */
  77372. set: function (value) {
  77373. this._highlightsExposure = value;
  77374. this._dirty = true;
  77375. },
  77376. enumerable: true,
  77377. configurable: true
  77378. });
  77379. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77380. /**
  77381. * Gets the midtones Hue value.
  77382. * 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).
  77383. */
  77384. get: function () {
  77385. return this._midtonesHue;
  77386. },
  77387. /**
  77388. * Sets the midtones Hue value.
  77389. * 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).
  77390. */
  77391. set: function (value) {
  77392. this._midtonesHue = value;
  77393. this._dirty = true;
  77394. },
  77395. enumerable: true,
  77396. configurable: true
  77397. });
  77398. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77399. /**
  77400. * Gets the midtones Density value.
  77401. * 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.
  77402. * Values less than zero provide a filter of opposite hue.
  77403. */
  77404. get: function () {
  77405. return this._midtonesDensity;
  77406. },
  77407. /**
  77408. * Sets the midtones Density value.
  77409. * 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.
  77410. * Values less than zero provide a filter of opposite hue.
  77411. */
  77412. set: function (value) {
  77413. this._midtonesDensity = value;
  77414. this._dirty = true;
  77415. },
  77416. enumerable: true,
  77417. configurable: true
  77418. });
  77419. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77420. /**
  77421. * Gets the midtones Saturation value.
  77422. * 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.
  77423. */
  77424. get: function () {
  77425. return this._midtonesSaturation;
  77426. },
  77427. /**
  77428. * Sets the midtones Saturation value.
  77429. * 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.
  77430. */
  77431. set: function (value) {
  77432. this._midtonesSaturation = value;
  77433. this._dirty = true;
  77434. },
  77435. enumerable: true,
  77436. configurable: true
  77437. });
  77438. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77439. /**
  77440. * Gets the midtones Exposure value.
  77441. * 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.
  77442. */
  77443. get: function () {
  77444. return this._midtonesExposure;
  77445. },
  77446. /**
  77447. * Sets the midtones Exposure value.
  77448. * 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.
  77449. */
  77450. set: function (value) {
  77451. this._midtonesExposure = value;
  77452. this._dirty = true;
  77453. },
  77454. enumerable: true,
  77455. configurable: true
  77456. });
  77457. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77458. /**
  77459. * Gets the shadows Hue value.
  77460. * 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).
  77461. */
  77462. get: function () {
  77463. return this._shadowsHue;
  77464. },
  77465. /**
  77466. * Sets the shadows Hue value.
  77467. * 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).
  77468. */
  77469. set: function (value) {
  77470. this._shadowsHue = value;
  77471. this._dirty = true;
  77472. },
  77473. enumerable: true,
  77474. configurable: true
  77475. });
  77476. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77477. /**
  77478. * Gets the shadows Density value.
  77479. * 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.
  77480. * Values less than zero provide a filter of opposite hue.
  77481. */
  77482. get: function () {
  77483. return this._shadowsDensity;
  77484. },
  77485. /**
  77486. * Sets the shadows Density value.
  77487. * 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.
  77488. * Values less than zero provide a filter of opposite hue.
  77489. */
  77490. set: function (value) {
  77491. this._shadowsDensity = value;
  77492. this._dirty = true;
  77493. },
  77494. enumerable: true,
  77495. configurable: true
  77496. });
  77497. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77498. /**
  77499. * Gets the shadows Saturation value.
  77500. * 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.
  77501. */
  77502. get: function () {
  77503. return this._shadowsSaturation;
  77504. },
  77505. /**
  77506. * Sets the shadows Saturation value.
  77507. * 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.
  77508. */
  77509. set: function (value) {
  77510. this._shadowsSaturation = value;
  77511. this._dirty = true;
  77512. },
  77513. enumerable: true,
  77514. configurable: true
  77515. });
  77516. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77517. /**
  77518. * Gets the shadows Exposure value.
  77519. * 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.
  77520. */
  77521. get: function () {
  77522. return this._shadowsExposure;
  77523. },
  77524. /**
  77525. * Sets the shadows Exposure value.
  77526. * 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.
  77527. */
  77528. set: function (value) {
  77529. this._shadowsExposure = value;
  77530. this._dirty = true;
  77531. },
  77532. enumerable: true,
  77533. configurable: true
  77534. });
  77535. ColorCurves.prototype.getClassName = function () {
  77536. return "ColorCurves";
  77537. };
  77538. /**
  77539. * Binds the color curves to the shader.
  77540. * @param colorCurves The color curve to bind
  77541. * @param effect The effect to bind to
  77542. */
  77543. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77544. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77545. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77546. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77547. if (colorCurves._dirty) {
  77548. colorCurves._dirty = false;
  77549. // Fill in global info.
  77550. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77551. // Compute highlights info.
  77552. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77553. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77554. // Compute midtones info.
  77555. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77556. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77557. // Compute shadows info.
  77558. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77559. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77560. // Compute deltas (neutral is midtones).
  77561. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77562. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77563. }
  77564. if (effect) {
  77565. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77566. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77567. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77568. }
  77569. };
  77570. /**
  77571. * Prepare the list of uniforms associated with the ColorCurves effects.
  77572. * @param uniformsList The list of uniforms used in the effect
  77573. */
  77574. ColorCurves.PrepareUniforms = function (uniformsList) {
  77575. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77576. };
  77577. /**
  77578. * Returns color grading data based on a hue, density, saturation and exposure value.
  77579. * @param filterHue The hue of the color filter.
  77580. * @param filterDensity The density of the color filter.
  77581. * @param saturation The saturation.
  77582. * @param exposure The exposure.
  77583. * @param result The result data container.
  77584. */
  77585. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77586. if (hue == null) {
  77587. return;
  77588. }
  77589. hue = ColorCurves.clamp(hue, 0, 360);
  77590. density = ColorCurves.clamp(density, -100, 100);
  77591. saturation = ColorCurves.clamp(saturation, -100, 100);
  77592. exposure = ColorCurves.clamp(exposure, -100, 100);
  77593. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77594. // so that the maximum filter density is only 50% control. This provides fine control
  77595. // for small values and reasonable range.
  77596. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77597. density *= 0.5;
  77598. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77599. if (density < 0) {
  77600. density *= -1;
  77601. hue = (hue + 180) % 360;
  77602. }
  77603. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77604. result.scaleToRef(2, result);
  77605. result.a = 1 + 0.01 * saturation;
  77606. };
  77607. /**
  77608. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77609. * @param value The input slider value in range [-100,100].
  77610. * @returns Adjusted value.
  77611. */
  77612. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77613. value /= 100;
  77614. var x = Math.abs(value);
  77615. x = Math.pow(x, 2);
  77616. if (value < 0) {
  77617. x *= -1;
  77618. }
  77619. x *= 100;
  77620. return x;
  77621. };
  77622. /**
  77623. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77624. * @param hue The hue (H) input.
  77625. * @param saturation The saturation (S) input.
  77626. * @param brightness The brightness (B) input.
  77627. * @result An RGBA color represented as Vector4.
  77628. */
  77629. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77630. var h = ColorCurves.clamp(hue, 0, 360);
  77631. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77632. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77633. if (s === 0) {
  77634. result.r = v;
  77635. result.g = v;
  77636. result.b = v;
  77637. }
  77638. else {
  77639. // sector 0 to 5
  77640. h /= 60;
  77641. var i = Math.floor(h);
  77642. // fractional part of h
  77643. var f = h - i;
  77644. var p = v * (1 - s);
  77645. var q = v * (1 - s * f);
  77646. var t = v * (1 - s * (1 - f));
  77647. switch (i) {
  77648. case 0:
  77649. result.r = v;
  77650. result.g = t;
  77651. result.b = p;
  77652. break;
  77653. case 1:
  77654. result.r = q;
  77655. result.g = v;
  77656. result.b = p;
  77657. break;
  77658. case 2:
  77659. result.r = p;
  77660. result.g = v;
  77661. result.b = t;
  77662. break;
  77663. case 3:
  77664. result.r = p;
  77665. result.g = q;
  77666. result.b = v;
  77667. break;
  77668. case 4:
  77669. result.r = t;
  77670. result.g = p;
  77671. result.b = v;
  77672. break;
  77673. default: // case 5:
  77674. result.r = v;
  77675. result.g = p;
  77676. result.b = q;
  77677. break;
  77678. }
  77679. }
  77680. result.a = 1;
  77681. };
  77682. /**
  77683. * Returns a value clamped between min and max
  77684. * @param value The value to clamp
  77685. * @param min The minimum of value
  77686. * @param max The maximum of value
  77687. * @returns The clamped value.
  77688. */
  77689. ColorCurves.clamp = function (value, min, max) {
  77690. return Math.min(Math.max(value, min), max);
  77691. };
  77692. /**
  77693. * Clones the current color curve instance.
  77694. * @return The cloned curves
  77695. */
  77696. ColorCurves.prototype.clone = function () {
  77697. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77698. };
  77699. /**
  77700. * Serializes the current color curve instance to a json representation.
  77701. * @return a JSON representation
  77702. */
  77703. ColorCurves.prototype.serialize = function () {
  77704. return BABYLON.SerializationHelper.Serialize(this);
  77705. };
  77706. /**
  77707. * Parses the color curve from a json representation.
  77708. * @param source the JSON source to parse
  77709. * @return The parsed curves
  77710. */
  77711. ColorCurves.Parse = function (source) {
  77712. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77713. };
  77714. __decorate([
  77715. BABYLON.serialize()
  77716. ], ColorCurves.prototype, "_globalHue", void 0);
  77717. __decorate([
  77718. BABYLON.serialize()
  77719. ], ColorCurves.prototype, "_globalDensity", void 0);
  77720. __decorate([
  77721. BABYLON.serialize()
  77722. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77723. __decorate([
  77724. BABYLON.serialize()
  77725. ], ColorCurves.prototype, "_globalExposure", void 0);
  77726. __decorate([
  77727. BABYLON.serialize()
  77728. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77729. __decorate([
  77730. BABYLON.serialize()
  77731. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77732. __decorate([
  77733. BABYLON.serialize()
  77734. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77735. __decorate([
  77736. BABYLON.serialize()
  77737. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77738. __decorate([
  77739. BABYLON.serialize()
  77740. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77741. __decorate([
  77742. BABYLON.serialize()
  77743. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77744. __decorate([
  77745. BABYLON.serialize()
  77746. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77747. __decorate([
  77748. BABYLON.serialize()
  77749. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77750. return ColorCurves;
  77751. }());
  77752. BABYLON.ColorCurves = ColorCurves;
  77753. })(BABYLON || (BABYLON = {}));
  77754. //# sourceMappingURL=babylon.colorCurves.js.map
  77755. var BABYLON;
  77756. (function (BABYLON) {
  77757. var RefractionPostProcess = /** @class */ (function (_super) {
  77758. __extends(RefractionPostProcess, _super);
  77759. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77760. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77761. _this.color = color;
  77762. _this.depth = depth;
  77763. _this.colorLevel = colorLevel;
  77764. _this._ownRefractionTexture = true;
  77765. _this.onActivateObservable.add(function (cam) {
  77766. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77767. });
  77768. _this.onApplyObservable.add(function (effect) {
  77769. effect.setColor3("baseColor", _this.color);
  77770. effect.setFloat("depth", _this.depth);
  77771. effect.setFloat("colorLevel", _this.colorLevel);
  77772. effect.setTexture("refractionSampler", _this._refTexture);
  77773. });
  77774. return _this;
  77775. }
  77776. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77777. /**
  77778. * Gets or sets the refraction texture
  77779. * Please note that you are responsible for disposing the texture if you set it manually
  77780. */
  77781. get: function () {
  77782. return this._refTexture;
  77783. },
  77784. set: function (value) {
  77785. if (this._refTexture && this._ownRefractionTexture) {
  77786. this._refTexture.dispose();
  77787. }
  77788. this._refTexture = value;
  77789. this._ownRefractionTexture = false;
  77790. },
  77791. enumerable: true,
  77792. configurable: true
  77793. });
  77794. // Methods
  77795. RefractionPostProcess.prototype.dispose = function (camera) {
  77796. if (this._refTexture && this._ownRefractionTexture) {
  77797. this._refTexture.dispose();
  77798. this._refTexture = null;
  77799. }
  77800. _super.prototype.dispose.call(this, camera);
  77801. };
  77802. return RefractionPostProcess;
  77803. }(BABYLON.PostProcess));
  77804. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77805. })(BABYLON || (BABYLON = {}));
  77806. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77807. var BABYLON;
  77808. (function (BABYLON) {
  77809. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77810. __extends(BlackAndWhitePostProcess, _super);
  77811. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77812. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77813. _this.degree = 1;
  77814. _this.onApplyObservable.add(function (effect) {
  77815. effect.setFloat("degree", _this.degree);
  77816. });
  77817. return _this;
  77818. }
  77819. return BlackAndWhitePostProcess;
  77820. }(BABYLON.PostProcess));
  77821. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77822. })(BABYLON || (BABYLON = {}));
  77823. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77824. var BABYLON;
  77825. (function (BABYLON) {
  77826. /**
  77827. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77828. * input texture to perform effects such as edge detection or sharpening
  77829. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77830. */
  77831. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77832. __extends(ConvolutionPostProcess, _super);
  77833. /**
  77834. * Creates a new instance ConvolutionPostProcess
  77835. * @param name The name of the effect.
  77836. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77837. * @param options The required width/height ratio to downsize to before computing the render pass.
  77838. * @param camera The camera to apply the render pass to.
  77839. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77840. * @param engine The engine which the post process will be applied. (default: current engine)
  77841. * @param reusable If the post process can be reused on the same frame. (default: false)
  77842. * @param textureType Type of textures used when performing the post process. (default: 0)
  77843. */
  77844. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77845. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77846. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77847. _this.kernel = kernel;
  77848. _this.onApply = function (effect) {
  77849. effect.setFloat2("screenSize", _this.width, _this.height);
  77850. effect.setArray("kernel", _this.kernel);
  77851. };
  77852. return _this;
  77853. }
  77854. // Statics
  77855. /**
  77856. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77857. */
  77858. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77859. /**
  77860. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77861. */
  77862. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77863. /**
  77864. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77865. */
  77866. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77867. /**
  77868. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77869. */
  77870. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77871. /**
  77872. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77873. */
  77874. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77875. /**
  77876. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77877. */
  77878. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77879. return ConvolutionPostProcess;
  77880. }(BABYLON.PostProcess));
  77881. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77882. })(BABYLON || (BABYLON = {}));
  77883. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77884. var BABYLON;
  77885. (function (BABYLON) {
  77886. var FilterPostProcess = /** @class */ (function (_super) {
  77887. __extends(FilterPostProcess, _super);
  77888. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77889. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77890. _this.kernelMatrix = kernelMatrix;
  77891. _this.onApply = function (effect) {
  77892. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77893. };
  77894. return _this;
  77895. }
  77896. return FilterPostProcess;
  77897. }(BABYLON.PostProcess));
  77898. BABYLON.FilterPostProcess = FilterPostProcess;
  77899. })(BABYLON || (BABYLON = {}));
  77900. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77901. var BABYLON;
  77902. (function (BABYLON) {
  77903. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77904. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77905. __extends(VolumetricLightScatteringPostProcess, _super);
  77906. /**
  77907. * @constructor
  77908. * @param {string} name - The post-process name
  77909. * @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)
  77910. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77911. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77912. * @param {number} samples - The post-process quality, default 100
  77913. * @param {number} samplingMode - The post-process filtering mode
  77914. * @param {BABYLON.Engine} engine - The babylon engine
  77915. * @param {boolean} reusable - If the post-process is reusable
  77916. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77917. */
  77918. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77919. if (samples === void 0) { samples = 100; }
  77920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77921. 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;
  77922. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77923. /**
  77924. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77925. */
  77926. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77927. /**
  77928. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77929. */
  77930. _this.useCustomMeshPosition = false;
  77931. /**
  77932. * If the post-process should inverse the light scattering direction
  77933. */
  77934. _this.invert = true;
  77935. /**
  77936. * Array containing the excluded meshes not rendered in the internal pass
  77937. */
  77938. _this.excludedMeshes = new Array();
  77939. /**
  77940. * Controls the overall intensity of the post-process
  77941. */
  77942. _this.exposure = 0.3;
  77943. /**
  77944. * Dissipates each sample's contribution in range [0, 1]
  77945. */
  77946. _this.decay = 0.96815;
  77947. /**
  77948. * Controls the overall intensity of each sample
  77949. */
  77950. _this.weight = 0.58767;
  77951. /**
  77952. * Controls the density of each sample
  77953. */
  77954. _this.density = 0.926;
  77955. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77956. engine = scene.getEngine();
  77957. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77958. // Configure mesh
  77959. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77960. // Configure
  77961. _this._createPass(scene, ratio.passRatio || ratio);
  77962. _this.onActivate = function (camera) {
  77963. if (!_this.isSupported) {
  77964. _this.dispose(camera);
  77965. }
  77966. _this.onActivate = null;
  77967. };
  77968. _this.onApplyObservable.add(function (effect) {
  77969. _this._updateMeshScreenCoordinates(scene);
  77970. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77971. effect.setFloat("exposure", _this.exposure);
  77972. effect.setFloat("decay", _this.decay);
  77973. effect.setFloat("weight", _this.weight);
  77974. effect.setFloat("density", _this.density);
  77975. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77976. });
  77977. return _this;
  77978. }
  77979. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77980. get: function () {
  77981. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77982. return false;
  77983. },
  77984. set: function (useDiffuseColor) {
  77985. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77986. },
  77987. enumerable: true,
  77988. configurable: true
  77989. });
  77990. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77991. return "VolumetricLightScatteringPostProcess";
  77992. };
  77993. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77994. var mesh = subMesh.getMesh();
  77995. // Render this.mesh as default
  77996. if (mesh === this.mesh && mesh.material) {
  77997. return mesh.material.isReady(mesh);
  77998. }
  77999. var defines = [];
  78000. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78001. var material = subMesh.getMaterial();
  78002. // Alpha test
  78003. if (material) {
  78004. if (material.needAlphaTesting()) {
  78005. defines.push("#define ALPHATEST");
  78006. }
  78007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78008. attribs.push(BABYLON.VertexBuffer.UVKind);
  78009. defines.push("#define UV1");
  78010. }
  78011. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78012. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78013. defines.push("#define UV2");
  78014. }
  78015. }
  78016. // Bones
  78017. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78018. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78019. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78020. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78021. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78022. }
  78023. else {
  78024. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78025. }
  78026. // Instances
  78027. if (useInstances) {
  78028. defines.push("#define INSTANCES");
  78029. attribs.push("world0");
  78030. attribs.push("world1");
  78031. attribs.push("world2");
  78032. attribs.push("world3");
  78033. }
  78034. // Get correct effect
  78035. var join = defines.join("\n");
  78036. if (this._cachedDefines !== join) {
  78037. this._cachedDefines = join;
  78038. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78039. }
  78040. return this._volumetricLightScatteringPass.isReady();
  78041. };
  78042. /**
  78043. * Sets the new light position for light scattering effect
  78044. * @param {BABYLON.Vector3} The new custom light position
  78045. */
  78046. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78047. this.customMeshPosition = position;
  78048. };
  78049. /**
  78050. * Returns the light position for light scattering effect
  78051. * @return {BABYLON.Vector3} The custom light position
  78052. */
  78053. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78054. return this.customMeshPosition;
  78055. };
  78056. /**
  78057. * Disposes the internal assets and detaches the post-process from the camera
  78058. */
  78059. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78060. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78061. if (rttIndex !== -1) {
  78062. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78063. }
  78064. this._volumetricLightScatteringRTT.dispose();
  78065. _super.prototype.dispose.call(this, camera);
  78066. };
  78067. /**
  78068. * Returns the render target texture used by the post-process
  78069. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78070. */
  78071. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78072. return this._volumetricLightScatteringRTT;
  78073. };
  78074. // Private methods
  78075. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78076. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78077. return true;
  78078. }
  78079. return false;
  78080. };
  78081. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78082. var _this = this;
  78083. var engine = scene.getEngine();
  78084. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78085. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78086. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78087. this._volumetricLightScatteringRTT.renderList = null;
  78088. this._volumetricLightScatteringRTT.renderParticles = false;
  78089. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78090. var camera = this.getCamera();
  78091. if (camera) {
  78092. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78093. }
  78094. else {
  78095. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78096. }
  78097. // Custom render function for submeshes
  78098. var renderSubMesh = function (subMesh) {
  78099. var mesh = subMesh.getRenderingMesh();
  78100. if (_this._meshExcluded(mesh)) {
  78101. return;
  78102. }
  78103. var material = subMesh.getMaterial();
  78104. if (!material) {
  78105. return;
  78106. }
  78107. var scene = mesh.getScene();
  78108. var engine = scene.getEngine();
  78109. // Culling
  78110. engine.setState(material.backFaceCulling);
  78111. // Managing instances
  78112. var batch = mesh._getInstancesRenderList(subMesh._id);
  78113. if (batch.mustReturn) {
  78114. return;
  78115. }
  78116. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78117. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78118. var effect = _this._volumetricLightScatteringPass;
  78119. if (mesh === _this.mesh) {
  78120. if (subMesh.effect) {
  78121. effect = subMesh.effect;
  78122. }
  78123. else {
  78124. effect = material.getEffect();
  78125. }
  78126. }
  78127. engine.enableEffect(effect);
  78128. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78129. if (mesh === _this.mesh) {
  78130. material.bind(mesh.getWorldMatrix(), mesh);
  78131. }
  78132. else {
  78133. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78134. // Alpha test
  78135. if (material && material.needAlphaTesting()) {
  78136. var alphaTexture = material.getAlphaTestTexture();
  78137. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78138. if (alphaTexture) {
  78139. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78140. }
  78141. }
  78142. // Bones
  78143. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78144. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78145. }
  78146. }
  78147. // Draw
  78148. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78149. }
  78150. };
  78151. // Render target texture callbacks
  78152. var savedSceneClearColor;
  78153. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78154. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78155. savedSceneClearColor = scene.clearColor;
  78156. scene.clearColor = sceneClearColor;
  78157. });
  78158. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78159. scene.clearColor = savedSceneClearColor;
  78160. });
  78161. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78162. var engine = scene.getEngine();
  78163. var index;
  78164. if (depthOnlySubMeshes.length) {
  78165. engine.setColorWrite(false);
  78166. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78167. renderSubMesh(depthOnlySubMeshes.data[index]);
  78168. }
  78169. engine.setColorWrite(true);
  78170. }
  78171. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78172. renderSubMesh(opaqueSubMeshes.data[index]);
  78173. }
  78174. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78175. renderSubMesh(alphaTestSubMeshes.data[index]);
  78176. }
  78177. if (transparentSubMeshes.length) {
  78178. // Sort sub meshes
  78179. for (index = 0; index < transparentSubMeshes.length; index++) {
  78180. var submesh = transparentSubMeshes.data[index];
  78181. var boundingInfo = submesh.getBoundingInfo();
  78182. if (boundingInfo && scene.activeCamera) {
  78183. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78184. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78185. }
  78186. }
  78187. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78188. sortedArray.sort(function (a, b) {
  78189. // Alpha index first
  78190. if (a._alphaIndex > b._alphaIndex) {
  78191. return 1;
  78192. }
  78193. if (a._alphaIndex < b._alphaIndex) {
  78194. return -1;
  78195. }
  78196. // Then distance to camera
  78197. if (a._distanceToCamera < b._distanceToCamera) {
  78198. return 1;
  78199. }
  78200. if (a._distanceToCamera > b._distanceToCamera) {
  78201. return -1;
  78202. }
  78203. return 0;
  78204. });
  78205. // Render sub meshes
  78206. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78207. for (index = 0; index < sortedArray.length; index++) {
  78208. renderSubMesh(sortedArray[index]);
  78209. }
  78210. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78211. }
  78212. };
  78213. };
  78214. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78215. var transform = scene.getTransformMatrix();
  78216. var meshPosition;
  78217. if (this.useCustomMeshPosition) {
  78218. meshPosition = this.customMeshPosition;
  78219. }
  78220. else if (this.attachedNode) {
  78221. meshPosition = this.attachedNode.position;
  78222. }
  78223. else {
  78224. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78225. }
  78226. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78227. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78228. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78229. if (this.invert)
  78230. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78231. };
  78232. // Static methods
  78233. /**
  78234. * Creates a default mesh for the Volumeric Light Scattering post-process
  78235. * @param {string} The mesh name
  78236. * @param {BABYLON.Scene} The scene where to create the mesh
  78237. * @return {BABYLON.Mesh} the default mesh
  78238. */
  78239. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78240. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78241. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78242. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78243. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78244. mesh.material = material;
  78245. return mesh;
  78246. };
  78247. __decorate([
  78248. BABYLON.serializeAsVector3()
  78249. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78250. __decorate([
  78251. BABYLON.serialize()
  78252. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78253. __decorate([
  78254. BABYLON.serialize()
  78255. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78256. __decorate([
  78257. BABYLON.serializeAsMeshReference()
  78258. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78259. __decorate([
  78260. BABYLON.serialize()
  78261. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78262. __decorate([
  78263. BABYLON.serialize()
  78264. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78265. __decorate([
  78266. BABYLON.serialize()
  78267. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78268. __decorate([
  78269. BABYLON.serialize()
  78270. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78271. __decorate([
  78272. BABYLON.serialize()
  78273. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78274. return VolumetricLightScatteringPostProcess;
  78275. }(BABYLON.PostProcess));
  78276. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78277. })(BABYLON || (BABYLON = {}));
  78278. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78279. //
  78280. // This post-process allows the modification of rendered colors by using
  78281. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78282. //
  78283. // The object needs to be provided an url to a texture containing the color
  78284. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78285. // Use an image editing software to tweak the LUT to match your needs.
  78286. //
  78287. // For an example of a color LUT, see here:
  78288. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78289. // For explanations on color grading, see here:
  78290. // http://udn.epicgames.com/Three/ColorGrading.html
  78291. //
  78292. var BABYLON;
  78293. (function (BABYLON) {
  78294. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78295. __extends(ColorCorrectionPostProcess, _super);
  78296. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78297. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78298. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78299. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78300. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78301. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78302. _this.onApply = function (effect) {
  78303. effect.setTexture("colorTable", _this._colorTableTexture);
  78304. };
  78305. return _this;
  78306. }
  78307. return ColorCorrectionPostProcess;
  78308. }(BABYLON.PostProcess));
  78309. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78310. })(BABYLON || (BABYLON = {}));
  78311. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78312. var BABYLON;
  78313. (function (BABYLON) {
  78314. /** Defines operator used for tonemapping */
  78315. var TonemappingOperator;
  78316. (function (TonemappingOperator) {
  78317. /** Hable */
  78318. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78319. /** Reinhard */
  78320. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78321. /** HejiDawson */
  78322. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78323. /** Photographic */
  78324. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78325. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78326. ;
  78327. /**
  78328. * Defines a post process to apply tone mapping
  78329. */
  78330. var TonemapPostProcess = /** @class */ (function (_super) {
  78331. __extends(TonemapPostProcess, _super);
  78332. /**
  78333. * Creates a new TonemapPostProcess
  78334. * @param name defines the name of the postprocess
  78335. * @param _operator defines the operator to use
  78336. * @param exposureAdjustment defines the required exposure adjustement
  78337. * @param camera defines the camera to use (can be null)
  78338. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78339. * @param engine defines the hosting engine (can be ignore if camera is set)
  78340. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78341. */
  78342. function TonemapPostProcess(name, _operator,
  78343. /** Defines the required exposure adjustement */
  78344. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78346. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78347. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78348. _this._operator = _operator;
  78349. _this.exposureAdjustment = exposureAdjustment;
  78350. var defines = "#define ";
  78351. if (_this._operator === TonemappingOperator.Hable)
  78352. defines += "HABLE_TONEMAPPING";
  78353. else if (_this._operator === TonemappingOperator.Reinhard)
  78354. defines += "REINHARD_TONEMAPPING";
  78355. else if (_this._operator === TonemappingOperator.HejiDawson)
  78356. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78357. else if (_this._operator === TonemappingOperator.Photographic)
  78358. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78359. //sadly a second call to create the effect.
  78360. _this.updateEffect(defines);
  78361. _this.onApply = function (effect) {
  78362. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78363. };
  78364. return _this;
  78365. }
  78366. return TonemapPostProcess;
  78367. }(BABYLON.PostProcess));
  78368. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78369. })(BABYLON || (BABYLON = {}));
  78370. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78371. var BABYLON;
  78372. (function (BABYLON) {
  78373. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78374. __extends(DisplayPassPostProcess, _super);
  78375. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78376. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78377. }
  78378. return DisplayPassPostProcess;
  78379. }(BABYLON.PostProcess));
  78380. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78381. })(BABYLON || (BABYLON = {}));
  78382. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78383. var BABYLON;
  78384. (function (BABYLON) {
  78385. var HighlightsPostProcess = /** @class */ (function (_super) {
  78386. __extends(HighlightsPostProcess, _super);
  78387. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78388. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78389. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78390. }
  78391. return HighlightsPostProcess;
  78392. }(BABYLON.PostProcess));
  78393. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78394. })(BABYLON || (BABYLON = {}));
  78395. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78396. var BABYLON;
  78397. (function (BABYLON) {
  78398. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78399. __extends(ImageProcessingPostProcess, _super);
  78400. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78401. if (camera === void 0) { camera = null; }
  78402. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78403. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78404. _this._fromLinearSpace = true;
  78405. /**
  78406. * Defines cache preventing GC.
  78407. */
  78408. _this._defines = {
  78409. IMAGEPROCESSING: false,
  78410. VIGNETTE: false,
  78411. VIGNETTEBLENDMODEMULTIPLY: false,
  78412. VIGNETTEBLENDMODEOPAQUE: false,
  78413. TONEMAPPING: false,
  78414. CONTRAST: false,
  78415. COLORCURVES: false,
  78416. COLORGRADING: false,
  78417. COLORGRADING3D: false,
  78418. FROMLINEARSPACE: false,
  78419. SAMPLER3DGREENDEPTH: false,
  78420. SAMPLER3DBGRMAP: false,
  78421. IMAGEPROCESSINGPOSTPROCESS: false,
  78422. EXPOSURE: false,
  78423. };
  78424. // Setup the configuration as forced by the constructor. This would then not force the
  78425. // scene materials output in linear space and let untouched the default forward pass.
  78426. if (imageProcessingConfiguration) {
  78427. imageProcessingConfiguration.applyByPostProcess = true;
  78428. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78429. // This will cause the shader to be compiled
  78430. _this.fromLinearSpace = false;
  78431. }
  78432. // Setup the default processing configuration to the scene.
  78433. else {
  78434. _this._attachImageProcessingConfiguration(null, true);
  78435. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78436. }
  78437. _this.onApply = function (effect) {
  78438. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78439. };
  78440. return _this;
  78441. }
  78442. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78443. /**
  78444. * Gets the image processing configuration used either in this material.
  78445. */
  78446. get: function () {
  78447. return this._imageProcessingConfiguration;
  78448. },
  78449. /**
  78450. * Sets the Default image processing configuration used either in the this material.
  78451. *
  78452. * If sets to null, the scene one is in use.
  78453. */
  78454. set: function (value) {
  78455. this._attachImageProcessingConfiguration(value);
  78456. },
  78457. enumerable: true,
  78458. configurable: true
  78459. });
  78460. /**
  78461. * Attaches a new image processing configuration to the PBR Material.
  78462. * @param configuration
  78463. */
  78464. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78465. var _this = this;
  78466. if (doNotBuild === void 0) { doNotBuild = false; }
  78467. if (configuration === this._imageProcessingConfiguration) {
  78468. return;
  78469. }
  78470. // Detaches observer.
  78471. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78472. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78473. }
  78474. // Pick the scene configuration if needed.
  78475. if (!configuration) {
  78476. var scene = null;
  78477. var engine = this.getEngine();
  78478. var camera = this.getCamera();
  78479. if (camera) {
  78480. scene = camera.getScene();
  78481. }
  78482. else if (engine && engine.scenes) {
  78483. var scenes = engine.scenes;
  78484. scene = scenes[scenes.length - 1];
  78485. }
  78486. else {
  78487. scene = BABYLON.Engine.LastCreatedScene;
  78488. }
  78489. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78490. }
  78491. else {
  78492. this._imageProcessingConfiguration = configuration;
  78493. }
  78494. // Attaches observer.
  78495. if (this._imageProcessingConfiguration) {
  78496. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78497. _this._updateParameters();
  78498. });
  78499. }
  78500. // Ensure the effect will be rebuilt.
  78501. if (!doNotBuild) {
  78502. this._updateParameters();
  78503. }
  78504. };
  78505. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78506. /**
  78507. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78508. */
  78509. get: function () {
  78510. return this.imageProcessingConfiguration.colorCurves;
  78511. },
  78512. /**
  78513. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78514. */
  78515. set: function (value) {
  78516. this.imageProcessingConfiguration.colorCurves = value;
  78517. },
  78518. enumerable: true,
  78519. configurable: true
  78520. });
  78521. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78522. /**
  78523. * Gets wether the color curves effect is enabled.
  78524. */
  78525. get: function () {
  78526. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78527. },
  78528. /**
  78529. * Sets wether the color curves effect is enabled.
  78530. */
  78531. set: function (value) {
  78532. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78533. },
  78534. enumerable: true,
  78535. configurable: true
  78536. });
  78537. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78538. /**
  78539. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78540. */
  78541. get: function () {
  78542. return this.imageProcessingConfiguration.colorGradingTexture;
  78543. },
  78544. /**
  78545. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78546. */
  78547. set: function (value) {
  78548. this.imageProcessingConfiguration.colorGradingTexture = value;
  78549. },
  78550. enumerable: true,
  78551. configurable: true
  78552. });
  78553. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78554. /**
  78555. * Gets wether the color grading effect is enabled.
  78556. */
  78557. get: function () {
  78558. return this.imageProcessingConfiguration.colorGradingEnabled;
  78559. },
  78560. /**
  78561. * Gets wether the color grading effect is enabled.
  78562. */
  78563. set: function (value) {
  78564. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78565. },
  78566. enumerable: true,
  78567. configurable: true
  78568. });
  78569. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78570. /**
  78571. * Gets exposure used in the effect.
  78572. */
  78573. get: function () {
  78574. return this.imageProcessingConfiguration.exposure;
  78575. },
  78576. /**
  78577. * Sets exposure used in the effect.
  78578. */
  78579. set: function (value) {
  78580. this.imageProcessingConfiguration.exposure = value;
  78581. },
  78582. enumerable: true,
  78583. configurable: true
  78584. });
  78585. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78586. /**
  78587. * Gets wether tonemapping is enabled or not.
  78588. */
  78589. get: function () {
  78590. return this._imageProcessingConfiguration.toneMappingEnabled;
  78591. },
  78592. /**
  78593. * Sets wether tonemapping is enabled or not
  78594. */
  78595. set: function (value) {
  78596. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78597. },
  78598. enumerable: true,
  78599. configurable: true
  78600. });
  78601. ;
  78602. ;
  78603. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78604. /**
  78605. * Gets contrast used in the effect.
  78606. */
  78607. get: function () {
  78608. return this.imageProcessingConfiguration.contrast;
  78609. },
  78610. /**
  78611. * Sets contrast used in the effect.
  78612. */
  78613. set: function (value) {
  78614. this.imageProcessingConfiguration.contrast = value;
  78615. },
  78616. enumerable: true,
  78617. configurable: true
  78618. });
  78619. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78620. /**
  78621. * Gets Vignette stretch size.
  78622. */
  78623. get: function () {
  78624. return this.imageProcessingConfiguration.vignetteStretch;
  78625. },
  78626. /**
  78627. * Sets Vignette stretch size.
  78628. */
  78629. set: function (value) {
  78630. this.imageProcessingConfiguration.vignetteStretch = value;
  78631. },
  78632. enumerable: true,
  78633. configurable: true
  78634. });
  78635. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78636. /**
  78637. * Gets Vignette centre X Offset.
  78638. */
  78639. get: function () {
  78640. return this.imageProcessingConfiguration.vignetteCentreX;
  78641. },
  78642. /**
  78643. * Sets Vignette centre X Offset.
  78644. */
  78645. set: function (value) {
  78646. this.imageProcessingConfiguration.vignetteCentreX = value;
  78647. },
  78648. enumerable: true,
  78649. configurable: true
  78650. });
  78651. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78652. /**
  78653. * Gets Vignette centre Y Offset.
  78654. */
  78655. get: function () {
  78656. return this.imageProcessingConfiguration.vignetteCentreY;
  78657. },
  78658. /**
  78659. * Sets Vignette centre Y Offset.
  78660. */
  78661. set: function (value) {
  78662. this.imageProcessingConfiguration.vignetteCentreY = value;
  78663. },
  78664. enumerable: true,
  78665. configurable: true
  78666. });
  78667. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78668. /**
  78669. * Gets Vignette weight or intensity of the vignette effect.
  78670. */
  78671. get: function () {
  78672. return this.imageProcessingConfiguration.vignetteWeight;
  78673. },
  78674. /**
  78675. * Sets Vignette weight or intensity of the vignette effect.
  78676. */
  78677. set: function (value) {
  78678. this.imageProcessingConfiguration.vignetteWeight = value;
  78679. },
  78680. enumerable: true,
  78681. configurable: true
  78682. });
  78683. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78684. /**
  78685. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78686. * if vignetteEnabled is set to true.
  78687. */
  78688. get: function () {
  78689. return this.imageProcessingConfiguration.vignetteColor;
  78690. },
  78691. /**
  78692. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78693. * if vignetteEnabled is set to true.
  78694. */
  78695. set: function (value) {
  78696. this.imageProcessingConfiguration.vignetteColor = value;
  78697. },
  78698. enumerable: true,
  78699. configurable: true
  78700. });
  78701. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78702. /**
  78703. * Gets Camera field of view used by the Vignette effect.
  78704. */
  78705. get: function () {
  78706. return this.imageProcessingConfiguration.vignetteCameraFov;
  78707. },
  78708. /**
  78709. * Sets Camera field of view used by the Vignette effect.
  78710. */
  78711. set: function (value) {
  78712. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78713. },
  78714. enumerable: true,
  78715. configurable: true
  78716. });
  78717. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78718. /**
  78719. * Gets the vignette blend mode allowing different kind of effect.
  78720. */
  78721. get: function () {
  78722. return this.imageProcessingConfiguration.vignetteBlendMode;
  78723. },
  78724. /**
  78725. * Sets the vignette blend mode allowing different kind of effect.
  78726. */
  78727. set: function (value) {
  78728. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78729. },
  78730. enumerable: true,
  78731. configurable: true
  78732. });
  78733. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78734. /**
  78735. * Gets wether the vignette effect is enabled.
  78736. */
  78737. get: function () {
  78738. return this.imageProcessingConfiguration.vignetteEnabled;
  78739. },
  78740. /**
  78741. * Sets wether the vignette effect is enabled.
  78742. */
  78743. set: function (value) {
  78744. this.imageProcessingConfiguration.vignetteEnabled = value;
  78745. },
  78746. enumerable: true,
  78747. configurable: true
  78748. });
  78749. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78750. /**
  78751. * Gets wether the input of the processing is in Gamma or Linear Space.
  78752. */
  78753. get: function () {
  78754. return this._fromLinearSpace;
  78755. },
  78756. /**
  78757. * Sets wether the input of the processing is in Gamma or Linear Space.
  78758. */
  78759. set: function (value) {
  78760. if (this._fromLinearSpace === value) {
  78761. return;
  78762. }
  78763. this._fromLinearSpace = value;
  78764. this._updateParameters();
  78765. },
  78766. enumerable: true,
  78767. configurable: true
  78768. });
  78769. ImageProcessingPostProcess.prototype.getClassName = function () {
  78770. return "ImageProcessingPostProcess";
  78771. };
  78772. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78773. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78774. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78775. var defines = "";
  78776. for (var define in this._defines) {
  78777. if (this._defines[define]) {
  78778. defines += "#define " + define + ";\r\n";
  78779. }
  78780. }
  78781. var samplers = ["textureSampler"];
  78782. var uniforms = ["scale"];
  78783. if (BABYLON.ImageProcessingConfiguration) {
  78784. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78785. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78786. }
  78787. this.updateEffect(defines, uniforms, samplers);
  78788. };
  78789. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78790. _super.prototype.dispose.call(this, camera);
  78791. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78792. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78793. }
  78794. if (this._imageProcessingConfiguration) {
  78795. this.imageProcessingConfiguration.applyByPostProcess = false;
  78796. }
  78797. };
  78798. __decorate([
  78799. BABYLON.serialize()
  78800. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78801. return ImageProcessingPostProcess;
  78802. }(BABYLON.PostProcess));
  78803. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78804. })(BABYLON || (BABYLON = {}));
  78805. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78806. var BABYLON;
  78807. (function (BABYLON) {
  78808. /**
  78809. * Class used to store bone information
  78810. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78811. */
  78812. var Bone = /** @class */ (function (_super) {
  78813. __extends(Bone, _super);
  78814. /**
  78815. * Create a new bone
  78816. * @param name defines the bone name
  78817. * @param skeleton defines the parent skeleton
  78818. * @param parentBone defines the parent (can be null if the bone is the root)
  78819. * @param localMatrix defines the local matrix
  78820. * @param restPose defines the rest pose matrix
  78821. * @param baseMatrix defines the base matrix
  78822. * @param index defines index of the bone in the hiearchy
  78823. */
  78824. function Bone(
  78825. /**
  78826. * defines the bone name
  78827. */
  78828. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78829. if (parentBone === void 0) { parentBone = null; }
  78830. if (localMatrix === void 0) { localMatrix = null; }
  78831. if (restPose === void 0) { restPose = null; }
  78832. if (baseMatrix === void 0) { baseMatrix = null; }
  78833. if (index === void 0) { index = null; }
  78834. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78835. _this.name = name;
  78836. /**
  78837. * Gets the list of child bones
  78838. */
  78839. _this.children = new Array();
  78840. /** Gets the animations associated with this bone */
  78841. _this.animations = new Array();
  78842. /**
  78843. * @hidden Internal only
  78844. * Set this value to map this bone to a different index in the transform matrices
  78845. * Set this value to -1 to exclude the bone from the transform matrices
  78846. */
  78847. _this._index = null;
  78848. _this._absoluteTransform = new BABYLON.Matrix();
  78849. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78850. _this._scalingDeterminant = 1;
  78851. _this._worldTransform = new BABYLON.Matrix();
  78852. _this._needToDecompose = true;
  78853. _this._needToCompose = false;
  78854. _this._skeleton = skeleton;
  78855. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78856. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78857. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78858. _this._index = index;
  78859. skeleton.bones.push(_this);
  78860. _this.setParent(parentBone, false);
  78861. if (baseMatrix || localMatrix) {
  78862. _this._updateDifferenceMatrix();
  78863. }
  78864. return _this;
  78865. }
  78866. Object.defineProperty(Bone.prototype, "_matrix", {
  78867. /** @hidden */
  78868. get: function () {
  78869. this._compose();
  78870. return this._localMatrix;
  78871. },
  78872. /** @hidden */
  78873. set: function (value) {
  78874. this._localMatrix.copyFrom(value);
  78875. this._needToDecompose = true;
  78876. },
  78877. enumerable: true,
  78878. configurable: true
  78879. });
  78880. // Members
  78881. /**
  78882. * Gets the parent skeleton
  78883. * @returns a skeleton
  78884. */
  78885. Bone.prototype.getSkeleton = function () {
  78886. return this._skeleton;
  78887. };
  78888. /**
  78889. * Gets parent bone
  78890. * @returns a bone or null if the bone is the root of the bone hierarchy
  78891. */
  78892. Bone.prototype.getParent = function () {
  78893. return this._parent;
  78894. };
  78895. /**
  78896. * Sets the parent bone
  78897. * @param parent defines the parent (can be null if the bone is the root)
  78898. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78899. */
  78900. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78901. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78902. if (this._parent === parent) {
  78903. return;
  78904. }
  78905. if (this._parent) {
  78906. var index = this._parent.children.indexOf(this);
  78907. if (index !== -1) {
  78908. this._parent.children.splice(index, 1);
  78909. }
  78910. }
  78911. this._parent = parent;
  78912. if (this._parent) {
  78913. this._parent.children.push(this);
  78914. }
  78915. if (updateDifferenceMatrix) {
  78916. this._updateDifferenceMatrix();
  78917. }
  78918. this.markAsDirty();
  78919. };
  78920. /**
  78921. * Gets the local matrix
  78922. * @returns a matrix
  78923. */
  78924. Bone.prototype.getLocalMatrix = function () {
  78925. this._compose();
  78926. return this._localMatrix;
  78927. };
  78928. /**
  78929. * Gets the base matrix (initial matrix which remains unchanged)
  78930. * @returns a matrix
  78931. */
  78932. Bone.prototype.getBaseMatrix = function () {
  78933. return this._baseMatrix;
  78934. };
  78935. /**
  78936. * Gets the rest pose matrix
  78937. * @returns a matrix
  78938. */
  78939. Bone.prototype.getRestPose = function () {
  78940. return this._restPose;
  78941. };
  78942. /**
  78943. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78944. */
  78945. Bone.prototype.getWorldMatrix = function () {
  78946. return this._worldTransform;
  78947. };
  78948. /**
  78949. * Sets the local matrix to rest pose matrix
  78950. */
  78951. Bone.prototype.returnToRest = function () {
  78952. this.updateMatrix(this._restPose.clone());
  78953. };
  78954. /**
  78955. * Gets the inverse of the absolute transform matrix.
  78956. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78957. * @returns a matrix
  78958. */
  78959. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78960. return this._invertedAbsoluteTransform;
  78961. };
  78962. /**
  78963. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78964. * @returns a matrix
  78965. */
  78966. Bone.prototype.getAbsoluteTransform = function () {
  78967. return this._absoluteTransform;
  78968. };
  78969. Object.defineProperty(Bone.prototype, "position", {
  78970. // Properties (matches AbstractMesh properties)
  78971. /** Gets or sets current position (in local space) */
  78972. get: function () {
  78973. this._decompose();
  78974. return this._localPosition;
  78975. },
  78976. set: function (newPosition) {
  78977. this._decompose();
  78978. this._localPosition.copyFrom(newPosition);
  78979. this._markAsDirtyAndCompose();
  78980. },
  78981. enumerable: true,
  78982. configurable: true
  78983. });
  78984. Object.defineProperty(Bone.prototype, "rotation", {
  78985. /** Gets or sets current rotation (in local space) */
  78986. get: function () {
  78987. return this.getRotation();
  78988. },
  78989. set: function (newRotation) {
  78990. this.setRotation(newRotation);
  78991. },
  78992. enumerable: true,
  78993. configurable: true
  78994. });
  78995. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78996. /** Gets or sets current rotation quaternion (in local space) */
  78997. get: function () {
  78998. this._decompose();
  78999. return this._localRotation;
  79000. },
  79001. set: function (newRotation) {
  79002. this.setRotationQuaternion(newRotation);
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. Object.defineProperty(Bone.prototype, "scaling", {
  79008. /** Gets or sets current scaling (in local space) */
  79009. get: function () {
  79010. return this.getScale();
  79011. },
  79012. set: function (newScaling) {
  79013. this.setScale(newScaling);
  79014. },
  79015. enumerable: true,
  79016. configurable: true
  79017. });
  79018. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79019. /**
  79020. * Gets the animation properties override
  79021. */
  79022. get: function () {
  79023. return this._skeleton.animationPropertiesOverride;
  79024. },
  79025. enumerable: true,
  79026. configurable: true
  79027. });
  79028. // Methods
  79029. Bone.prototype._decompose = function () {
  79030. if (!this._needToDecompose) {
  79031. return;
  79032. }
  79033. this._needToDecompose = false;
  79034. if (!this._localScaling) {
  79035. this._localScaling = BABYLON.Vector3.Zero();
  79036. this._localRotation = BABYLON.Quaternion.Zero();
  79037. this._localPosition = BABYLON.Vector3.Zero();
  79038. }
  79039. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79040. };
  79041. Bone.prototype._compose = function () {
  79042. if (!this._needToCompose) {
  79043. return;
  79044. }
  79045. this._needToCompose = false;
  79046. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79047. };
  79048. /**
  79049. * Update the base and local matrices
  79050. * @param matrix defines the new base or local matrix
  79051. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79052. * @param updateLocalMatrix defines if the local matrix should be updated
  79053. */
  79054. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79055. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79056. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79057. this._baseMatrix.copyFrom(matrix);
  79058. if (updateDifferenceMatrix) {
  79059. this._updateDifferenceMatrix();
  79060. }
  79061. if (updateLocalMatrix) {
  79062. this._localMatrix.copyFrom(matrix);
  79063. this._markAsDirtyAndDecompose();
  79064. }
  79065. else {
  79066. this.markAsDirty();
  79067. }
  79068. };
  79069. /** @hidden */
  79070. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79071. if (updateChildren === void 0) { updateChildren = true; }
  79072. if (!rootMatrix) {
  79073. rootMatrix = this._baseMatrix;
  79074. }
  79075. if (this._parent) {
  79076. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79077. }
  79078. else {
  79079. this._absoluteTransform.copyFrom(rootMatrix);
  79080. }
  79081. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79082. if (updateChildren) {
  79083. for (var index = 0; index < this.children.length; index++) {
  79084. this.children[index]._updateDifferenceMatrix();
  79085. }
  79086. }
  79087. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79088. };
  79089. /**
  79090. * Flag the bone as dirty (Forcing it to update everything)
  79091. */
  79092. Bone.prototype.markAsDirty = function () {
  79093. this._currentRenderId++;
  79094. this._childRenderId++;
  79095. this._skeleton._markAsDirty();
  79096. };
  79097. Bone.prototype._markAsDirtyAndCompose = function () {
  79098. this.markAsDirty();
  79099. this._needToCompose = true;
  79100. };
  79101. Bone.prototype._markAsDirtyAndDecompose = function () {
  79102. this.markAsDirty();
  79103. this._needToDecompose = true;
  79104. };
  79105. /**
  79106. * Copy an animation range from another bone
  79107. * @param source defines the source bone
  79108. * @param rangeName defines the range name to copy
  79109. * @param frameOffset defines the frame offset
  79110. * @param rescaleAsRequired defines if rescaling must be applied if required
  79111. * @param skelDimensionsRatio defines the scaling ratio
  79112. * @returns true if operation was successful
  79113. */
  79114. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79115. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79116. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79117. // all animation may be coming from a library skeleton, so may need to create animation
  79118. if (this.animations.length === 0) {
  79119. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79120. this.animations[0].setKeys([]);
  79121. }
  79122. // get animation info / verify there is such a range from the source bone
  79123. var sourceRange = source.animations[0].getRange(rangeName);
  79124. if (!sourceRange) {
  79125. return false;
  79126. }
  79127. var from = sourceRange.from;
  79128. var to = sourceRange.to;
  79129. var sourceKeys = source.animations[0].getKeys();
  79130. // rescaling prep
  79131. var sourceBoneLength = source.length;
  79132. var sourceParent = source.getParent();
  79133. var parent = this.getParent();
  79134. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79135. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79136. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79137. var destKeys = this.animations[0].getKeys();
  79138. // loop vars declaration
  79139. var orig;
  79140. var origTranslation;
  79141. var mat;
  79142. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79143. orig = sourceKeys[key];
  79144. if (orig.frame >= from && orig.frame <= to) {
  79145. if (rescaleAsRequired) {
  79146. mat = orig.value.clone();
  79147. // scale based on parent ratio, when bone has parent
  79148. if (parentScalingReqd) {
  79149. origTranslation = mat.getTranslation();
  79150. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79151. // scale based on skeleton dimension ratio when root bone, and value is passed
  79152. }
  79153. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79154. origTranslation = mat.getTranslation();
  79155. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79156. // use original when root bone, and no data for skelDimensionsRatio
  79157. }
  79158. else {
  79159. mat = orig.value;
  79160. }
  79161. }
  79162. else {
  79163. mat = orig.value;
  79164. }
  79165. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79166. }
  79167. }
  79168. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79169. return true;
  79170. };
  79171. /**
  79172. * Translate the bone in local or world space
  79173. * @param vec The amount to translate the bone
  79174. * @param space The space that the translation is in
  79175. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79176. */
  79177. Bone.prototype.translate = function (vec, space, mesh) {
  79178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79179. var lm = this.getLocalMatrix();
  79180. if (space == BABYLON.Space.LOCAL) {
  79181. lm.m[12] += vec.x;
  79182. lm.m[13] += vec.y;
  79183. lm.m[14] += vec.z;
  79184. }
  79185. else {
  79186. var wm = null;
  79187. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79188. if (mesh) {
  79189. wm = mesh.getWorldMatrix();
  79190. }
  79191. this._skeleton.computeAbsoluteTransforms();
  79192. var tmat = Bone._tmpMats[0];
  79193. var tvec = Bone._tmpVecs[0];
  79194. if (this._parent) {
  79195. if (mesh && wm) {
  79196. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79197. tmat.multiplyToRef(wm, tmat);
  79198. }
  79199. else {
  79200. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79201. }
  79202. }
  79203. tmat.m[12] = 0;
  79204. tmat.m[13] = 0;
  79205. tmat.m[14] = 0;
  79206. tmat.invert();
  79207. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79208. lm.m[12] += tvec.x;
  79209. lm.m[13] += tvec.y;
  79210. lm.m[14] += tvec.z;
  79211. }
  79212. this._markAsDirtyAndDecompose();
  79213. };
  79214. /**
  79215. * Set the postion of the bone in local or world space
  79216. * @param position The position to set the bone
  79217. * @param space The space that the position is in
  79218. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79219. */
  79220. Bone.prototype.setPosition = function (position, space, mesh) {
  79221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79222. var lm = this.getLocalMatrix();
  79223. if (space == BABYLON.Space.LOCAL) {
  79224. lm.m[12] = position.x;
  79225. lm.m[13] = position.y;
  79226. lm.m[14] = position.z;
  79227. }
  79228. else {
  79229. var wm = null;
  79230. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79231. if (mesh) {
  79232. wm = mesh.getWorldMatrix();
  79233. }
  79234. this._skeleton.computeAbsoluteTransforms();
  79235. var tmat = Bone._tmpMats[0];
  79236. var vec = Bone._tmpVecs[0];
  79237. if (this._parent) {
  79238. if (mesh && wm) {
  79239. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79240. tmat.multiplyToRef(wm, tmat);
  79241. }
  79242. else {
  79243. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79244. }
  79245. }
  79246. tmat.invert();
  79247. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79248. lm.m[12] = vec.x;
  79249. lm.m[13] = vec.y;
  79250. lm.m[14] = vec.z;
  79251. }
  79252. this._markAsDirtyAndDecompose();
  79253. };
  79254. /**
  79255. * Set the absolute position of the bone (world space)
  79256. * @param position The position to set the bone
  79257. * @param mesh The mesh that this bone is attached to
  79258. */
  79259. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79260. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79261. };
  79262. /**
  79263. * Scale the bone on the x, y and z axes (in local space)
  79264. * @param x The amount to scale the bone on the x axis
  79265. * @param y The amount to scale the bone on the y axis
  79266. * @param z The amount to scale the bone on the z axis
  79267. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79268. */
  79269. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79270. if (scaleChildren === void 0) { scaleChildren = false; }
  79271. var locMat = this.getLocalMatrix();
  79272. // Apply new scaling on top of current local matrix
  79273. var scaleMat = Bone._tmpMats[0];
  79274. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79275. scaleMat.multiplyToRef(locMat, locMat);
  79276. // Invert scaling matrix and apply the inverse to all children
  79277. scaleMat.invert();
  79278. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79279. var child = _a[_i];
  79280. var cm = child.getLocalMatrix();
  79281. cm.multiplyToRef(scaleMat, cm);
  79282. cm.m[12] *= x;
  79283. cm.m[13] *= y;
  79284. cm.m[14] *= z;
  79285. child._markAsDirtyAndDecompose();
  79286. }
  79287. this._markAsDirtyAndDecompose();
  79288. if (scaleChildren) {
  79289. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79290. var child = _c[_b];
  79291. child.scale(x, y, z, scaleChildren);
  79292. }
  79293. }
  79294. };
  79295. /**
  79296. * Set the bone scaling in local space
  79297. * @param scale defines the scaling vector
  79298. */
  79299. Bone.prototype.setScale = function (scale) {
  79300. this._decompose();
  79301. this._localScaling.copyFrom(scale);
  79302. this._markAsDirtyAndCompose();
  79303. };
  79304. /**
  79305. * Gets the current scaling in local space
  79306. * @returns the current scaling vector
  79307. */
  79308. Bone.prototype.getScale = function () {
  79309. this._decompose();
  79310. return this._localScaling;
  79311. };
  79312. /**
  79313. * Gets the current scaling in local space and stores it in a target vector
  79314. * @param result defines the target vector
  79315. */
  79316. Bone.prototype.getScaleToRef = function (result) {
  79317. this._decompose();
  79318. result.copyFrom(this._localScaling);
  79319. };
  79320. /**
  79321. * Set the yaw, pitch, and roll of the bone in local or world space
  79322. * @param yaw The rotation of the bone on the y axis
  79323. * @param pitch The rotation of the bone on the x axis
  79324. * @param roll The rotation of the bone on the z axis
  79325. * @param space The space that the axes of rotation are in
  79326. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79327. */
  79328. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79330. if (space === BABYLON.Space.LOCAL) {
  79331. var quat = Bone._tmpQuat;
  79332. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79333. this.setRotationQuaternion(quat, space, mesh);
  79334. return;
  79335. }
  79336. var rotMatInv = Bone._tmpMats[0];
  79337. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79338. return;
  79339. }
  79340. var rotMat = Bone._tmpMats[1];
  79341. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79342. rotMatInv.multiplyToRef(rotMat, rotMat);
  79343. this._rotateWithMatrix(rotMat, space, mesh);
  79344. };
  79345. /**
  79346. * Add a rotation to the bone on an axis in local or world space
  79347. * @param axis The axis to rotate the bone on
  79348. * @param amount The amount to rotate the bone
  79349. * @param space The space that the axis is in
  79350. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79351. */
  79352. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79354. var rmat = Bone._tmpMats[0];
  79355. rmat.m[12] = 0;
  79356. rmat.m[13] = 0;
  79357. rmat.m[14] = 0;
  79358. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79359. this._rotateWithMatrix(rmat, space, mesh);
  79360. };
  79361. /**
  79362. * Set the rotation of the bone to a particular axis angle in local or world space
  79363. * @param axis The axis to rotate the bone on
  79364. * @param angle The angle that the bone should be rotated to
  79365. * @param space The space that the axis is in
  79366. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79367. */
  79368. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79369. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79370. if (space === BABYLON.Space.LOCAL) {
  79371. var quat = Bone._tmpQuat;
  79372. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79373. this.setRotationQuaternion(quat, space, mesh);
  79374. return;
  79375. }
  79376. var rotMatInv = Bone._tmpMats[0];
  79377. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79378. return;
  79379. }
  79380. var rotMat = Bone._tmpMats[1];
  79381. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79382. rotMatInv.multiplyToRef(rotMat, rotMat);
  79383. this._rotateWithMatrix(rotMat, space, mesh);
  79384. };
  79385. /**
  79386. * Set the euler rotation of the bone in local of world space
  79387. * @param rotation The euler rotation that the bone should be set to
  79388. * @param space The space that the rotation is in
  79389. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79390. */
  79391. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79393. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79394. };
  79395. /**
  79396. * Set the quaternion rotation of the bone in local of world space
  79397. * @param quat The quaternion rotation that the bone should be set to
  79398. * @param space The space that the rotation is in
  79399. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79400. */
  79401. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79403. if (space === BABYLON.Space.LOCAL) {
  79404. this._decompose();
  79405. this._localRotation.copyFrom(quat);
  79406. this._markAsDirtyAndCompose();
  79407. return;
  79408. }
  79409. var rotMatInv = Bone._tmpMats[0];
  79410. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79411. return;
  79412. }
  79413. var rotMat = Bone._tmpMats[1];
  79414. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79415. rotMatInv.multiplyToRef(rotMat, rotMat);
  79416. this._rotateWithMatrix(rotMat, space, mesh);
  79417. };
  79418. /**
  79419. * Set the rotation matrix of the bone in local of world space
  79420. * @param rotMat The rotation matrix that the bone should be set to
  79421. * @param space The space that the rotation is in
  79422. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79423. */
  79424. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79425. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79426. if (space === BABYLON.Space.LOCAL) {
  79427. var quat = Bone._tmpQuat;
  79428. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79429. this.setRotationQuaternion(quat, space, mesh);
  79430. return;
  79431. }
  79432. var rotMatInv = Bone._tmpMats[0];
  79433. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79434. return;
  79435. }
  79436. var rotMat2 = Bone._tmpMats[1];
  79437. rotMat2.copyFrom(rotMat);
  79438. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79439. this._rotateWithMatrix(rotMat2, space, mesh);
  79440. };
  79441. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79443. var lmat = this.getLocalMatrix();
  79444. var lx = lmat.m[12];
  79445. var ly = lmat.m[13];
  79446. var lz = lmat.m[14];
  79447. var parent = this.getParent();
  79448. var parentScale = Bone._tmpMats[3];
  79449. var parentScaleInv = Bone._tmpMats[4];
  79450. if (parent && space == BABYLON.Space.WORLD) {
  79451. if (mesh) {
  79452. parentScale.copyFrom(mesh.getWorldMatrix());
  79453. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79454. }
  79455. else {
  79456. parentScale.copyFrom(parent.getAbsoluteTransform());
  79457. }
  79458. parentScaleInv.copyFrom(parentScale);
  79459. parentScaleInv.invert();
  79460. lmat.multiplyToRef(parentScale, lmat);
  79461. lmat.multiplyToRef(rmat, lmat);
  79462. lmat.multiplyToRef(parentScaleInv, lmat);
  79463. }
  79464. else {
  79465. if (space == BABYLON.Space.WORLD && mesh) {
  79466. parentScale.copyFrom(mesh.getWorldMatrix());
  79467. parentScaleInv.copyFrom(parentScale);
  79468. parentScaleInv.invert();
  79469. lmat.multiplyToRef(parentScale, lmat);
  79470. lmat.multiplyToRef(rmat, lmat);
  79471. lmat.multiplyToRef(parentScaleInv, lmat);
  79472. }
  79473. else {
  79474. lmat.multiplyToRef(rmat, lmat);
  79475. }
  79476. }
  79477. lmat.m[12] = lx;
  79478. lmat.m[13] = ly;
  79479. lmat.m[14] = lz;
  79480. this.computeAbsoluteTransforms();
  79481. this._markAsDirtyAndDecompose();
  79482. };
  79483. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79484. var scaleMatrix = Bone._tmpMats[2];
  79485. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79486. if (mesh) {
  79487. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79488. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79489. }
  79490. rotMatInv.invert();
  79491. if (isNaN(rotMatInv.m[0])) {
  79492. // Matrix failed to invert.
  79493. // This can happen if scale is zero for example.
  79494. return false;
  79495. }
  79496. scaleMatrix.m[0] *= this._scalingDeterminant;
  79497. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79498. return true;
  79499. };
  79500. /**
  79501. * Get the position of the bone in local or world space
  79502. * @param space The space that the returned position is in
  79503. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79504. * @returns The position of the bone
  79505. */
  79506. Bone.prototype.getPosition = function (space, mesh) {
  79507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79508. if (mesh === void 0) { mesh = null; }
  79509. var pos = BABYLON.Vector3.Zero();
  79510. this.getPositionToRef(space, mesh, pos);
  79511. return pos;
  79512. };
  79513. /**
  79514. * Copy the position of the bone to a vector3 in local or world space
  79515. * @param space The space that the returned position is in
  79516. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79517. * @param result The vector3 to copy the position to
  79518. */
  79519. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79520. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79521. if (space == BABYLON.Space.LOCAL) {
  79522. var lm = this.getLocalMatrix();
  79523. result.x = lm.m[12];
  79524. result.y = lm.m[13];
  79525. result.z = lm.m[14];
  79526. }
  79527. else {
  79528. var wm = null;
  79529. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79530. if (mesh) {
  79531. wm = mesh.getWorldMatrix();
  79532. }
  79533. this._skeleton.computeAbsoluteTransforms();
  79534. var tmat = Bone._tmpMats[0];
  79535. if (mesh && wm) {
  79536. tmat.copyFrom(this.getAbsoluteTransform());
  79537. tmat.multiplyToRef(wm, tmat);
  79538. }
  79539. else {
  79540. tmat = this.getAbsoluteTransform();
  79541. }
  79542. result.x = tmat.m[12];
  79543. result.y = tmat.m[13];
  79544. result.z = tmat.m[14];
  79545. }
  79546. };
  79547. /**
  79548. * Get the absolute position of the bone (world space)
  79549. * @param mesh The mesh that this bone is attached to
  79550. * @returns The absolute position of the bone
  79551. */
  79552. Bone.prototype.getAbsolutePosition = function (mesh) {
  79553. if (mesh === void 0) { mesh = null; }
  79554. var pos = BABYLON.Vector3.Zero();
  79555. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79556. return pos;
  79557. };
  79558. /**
  79559. * Copy the absolute position of the bone (world space) to the result param
  79560. * @param mesh The mesh that this bone is attached to
  79561. * @param result The vector3 to copy the absolute position to
  79562. */
  79563. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79564. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79565. };
  79566. /**
  79567. * Compute the absolute transforms of this bone and its children
  79568. */
  79569. Bone.prototype.computeAbsoluteTransforms = function () {
  79570. this._compose();
  79571. if (this._parent) {
  79572. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79573. }
  79574. else {
  79575. this._absoluteTransform.copyFrom(this._localMatrix);
  79576. var poseMatrix = this._skeleton.getPoseMatrix();
  79577. if (poseMatrix) {
  79578. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79579. }
  79580. }
  79581. var children = this.children;
  79582. var len = children.length;
  79583. for (var i = 0; i < len; i++) {
  79584. children[i].computeAbsoluteTransforms();
  79585. }
  79586. };
  79587. /**
  79588. * Get the world direction from an axis that is in the local space of the bone
  79589. * @param localAxis The local direction that is used to compute the world direction
  79590. * @param mesh The mesh that this bone is attached to
  79591. * @returns The world direction
  79592. */
  79593. Bone.prototype.getDirection = function (localAxis, mesh) {
  79594. if (mesh === void 0) { mesh = null; }
  79595. var result = BABYLON.Vector3.Zero();
  79596. this.getDirectionToRef(localAxis, mesh, result);
  79597. return result;
  79598. };
  79599. /**
  79600. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79601. * @param localAxis The local direction that is used to compute the world direction
  79602. * @param mesh The mesh that this bone is attached to
  79603. * @param result The vector3 that the world direction will be copied to
  79604. */
  79605. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79606. if (mesh === void 0) { mesh = null; }
  79607. var wm = null;
  79608. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79609. if (mesh) {
  79610. wm = mesh.getWorldMatrix();
  79611. }
  79612. this._skeleton.computeAbsoluteTransforms();
  79613. var mat = Bone._tmpMats[0];
  79614. mat.copyFrom(this.getAbsoluteTransform());
  79615. if (mesh && wm) {
  79616. mat.multiplyToRef(wm, mat);
  79617. }
  79618. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79619. result.normalize();
  79620. };
  79621. /**
  79622. * Get the euler rotation of the bone in local or world space
  79623. * @param space The space that the rotation should be in
  79624. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79625. * @returns The euler rotation
  79626. */
  79627. Bone.prototype.getRotation = function (space, mesh) {
  79628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79629. if (mesh === void 0) { mesh = null; }
  79630. var result = BABYLON.Vector3.Zero();
  79631. this.getRotationToRef(space, mesh, result);
  79632. return result;
  79633. };
  79634. /**
  79635. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79636. * @param space The space that the rotation should be in
  79637. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79638. * @param result The vector3 that the rotation should be copied to
  79639. */
  79640. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79642. if (mesh === void 0) { mesh = null; }
  79643. var quat = Bone._tmpQuat;
  79644. this.getRotationQuaternionToRef(space, mesh, quat);
  79645. quat.toEulerAnglesToRef(result);
  79646. };
  79647. /**
  79648. * Get the quaternion rotation of the bone in either local or world space
  79649. * @param space The space that the rotation should be in
  79650. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79651. * @returns The quaternion rotation
  79652. */
  79653. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79655. if (mesh === void 0) { mesh = null; }
  79656. var result = BABYLON.Quaternion.Identity();
  79657. this.getRotationQuaternionToRef(space, mesh, result);
  79658. return result;
  79659. };
  79660. /**
  79661. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79662. * @param space The space that the rotation should be in
  79663. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79664. * @param result The quaternion that the rotation should be copied to
  79665. */
  79666. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79668. if (mesh === void 0) { mesh = null; }
  79669. if (space == BABYLON.Space.LOCAL) {
  79670. this._decompose();
  79671. result.copyFrom(this._localRotation);
  79672. }
  79673. else {
  79674. var mat = Bone._tmpMats[0];
  79675. var amat = this.getAbsoluteTransform();
  79676. if (mesh) {
  79677. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79678. }
  79679. else {
  79680. mat.copyFrom(amat);
  79681. }
  79682. mat.m[0] *= this._scalingDeterminant;
  79683. mat.m[1] *= this._scalingDeterminant;
  79684. mat.m[2] *= this._scalingDeterminant;
  79685. mat.decompose(undefined, result, undefined);
  79686. }
  79687. };
  79688. /**
  79689. * Get the rotation matrix of the bone in local or world space
  79690. * @param space The space that the rotation should be in
  79691. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79692. * @returns The rotation matrix
  79693. */
  79694. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79696. var result = BABYLON.Matrix.Identity();
  79697. this.getRotationMatrixToRef(space, mesh, result);
  79698. return result;
  79699. };
  79700. /**
  79701. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79702. * @param space The space that the rotation should be in
  79703. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79704. * @param result The quaternion that the rotation should be copied to
  79705. */
  79706. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79708. if (space == BABYLON.Space.LOCAL) {
  79709. this.getLocalMatrix().getRotationMatrixToRef(result);
  79710. }
  79711. else {
  79712. var mat = Bone._tmpMats[0];
  79713. var amat = this.getAbsoluteTransform();
  79714. if (mesh) {
  79715. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79716. }
  79717. else {
  79718. mat.copyFrom(amat);
  79719. }
  79720. mat.m[0] *= this._scalingDeterminant;
  79721. mat.m[1] *= this._scalingDeterminant;
  79722. mat.m[2] *= this._scalingDeterminant;
  79723. mat.getRotationMatrixToRef(result);
  79724. }
  79725. };
  79726. /**
  79727. * Get the world position of a point that is in the local space of the bone
  79728. * @param position The local position
  79729. * @param mesh The mesh that this bone is attached to
  79730. * @returns The world position
  79731. */
  79732. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79733. if (mesh === void 0) { mesh = null; }
  79734. var result = BABYLON.Vector3.Zero();
  79735. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79736. return result;
  79737. };
  79738. /**
  79739. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79740. * @param position The local position
  79741. * @param mesh The mesh that this bone is attached to
  79742. * @param result The vector3 that the world position should be copied to
  79743. */
  79744. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79745. if (mesh === void 0) { mesh = null; }
  79746. var wm = null;
  79747. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79748. if (mesh) {
  79749. wm = mesh.getWorldMatrix();
  79750. }
  79751. this._skeleton.computeAbsoluteTransforms();
  79752. var tmat = Bone._tmpMats[0];
  79753. if (mesh && wm) {
  79754. tmat.copyFrom(this.getAbsoluteTransform());
  79755. tmat.multiplyToRef(wm, tmat);
  79756. }
  79757. else {
  79758. tmat = this.getAbsoluteTransform();
  79759. }
  79760. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79761. };
  79762. /**
  79763. * Get the local position of a point that is in world space
  79764. * @param position The world position
  79765. * @param mesh The mesh that this bone is attached to
  79766. * @returns The local position
  79767. */
  79768. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79769. if (mesh === void 0) { mesh = null; }
  79770. var result = BABYLON.Vector3.Zero();
  79771. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79772. return result;
  79773. };
  79774. /**
  79775. * Get the local position of a point that is in world space and copy it to the result param
  79776. * @param position The world position
  79777. * @param mesh The mesh that this bone is attached to
  79778. * @param result The vector3 that the local position should be copied to
  79779. */
  79780. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79781. if (mesh === void 0) { mesh = null; }
  79782. var wm = null;
  79783. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79784. if (mesh) {
  79785. wm = mesh.getWorldMatrix();
  79786. }
  79787. this._skeleton.computeAbsoluteTransforms();
  79788. var tmat = Bone._tmpMats[0];
  79789. tmat.copyFrom(this.getAbsoluteTransform());
  79790. if (mesh && wm) {
  79791. tmat.multiplyToRef(wm, tmat);
  79792. }
  79793. tmat.invert();
  79794. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79795. };
  79796. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79797. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79798. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79799. return Bone;
  79800. }(BABYLON.Node));
  79801. BABYLON.Bone = Bone;
  79802. })(BABYLON || (BABYLON = {}));
  79803. //# sourceMappingURL=babylon.bone.js.map
  79804. var BABYLON;
  79805. (function (BABYLON) {
  79806. /**
  79807. * Class used to apply inverse kinematics to bones
  79808. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79809. */
  79810. var BoneIKController = /** @class */ (function () {
  79811. /**
  79812. * Creates a new BoneIKController
  79813. * @param mesh defines the mesh to control
  79814. * @param bone defines the bone to control
  79815. * @param options defines options to set up the controller
  79816. */
  79817. function BoneIKController(mesh, bone, options) {
  79818. /**
  79819. * Gets or sets the target position
  79820. */
  79821. this.targetPosition = BABYLON.Vector3.Zero();
  79822. /**
  79823. * Gets or sets the pole target position
  79824. */
  79825. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79826. /**
  79827. * Gets or sets the pole target local offset
  79828. */
  79829. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79830. /**
  79831. * Gets or sets the pole angle
  79832. */
  79833. this.poleAngle = 0;
  79834. /**
  79835. * 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)
  79836. */
  79837. this.slerpAmount = 1;
  79838. this._bone1Quat = BABYLON.Quaternion.Identity();
  79839. this._bone1Mat = BABYLON.Matrix.Identity();
  79840. this._bone2Ang = Math.PI;
  79841. this._maxAngle = Math.PI;
  79842. this._rightHandedSystem = false;
  79843. this._bendAxis = BABYLON.Vector3.Right();
  79844. this._slerping = false;
  79845. this._adjustRoll = 0;
  79846. this._bone2 = bone;
  79847. this._bone1 = bone.getParent();
  79848. if (!this._bone1) {
  79849. return;
  79850. }
  79851. this.mesh = mesh;
  79852. var bonePos = bone.getPosition();
  79853. if (bone.getAbsoluteTransform().determinant() > 0) {
  79854. this._rightHandedSystem = true;
  79855. this._bendAxis.x = 0;
  79856. this._bendAxis.y = 0;
  79857. this._bendAxis.z = -1;
  79858. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79859. this._adjustRoll = Math.PI * .5;
  79860. this._bendAxis.z = 1;
  79861. }
  79862. }
  79863. if (this._bone1.length) {
  79864. var boneScale1 = this._bone1.getScale();
  79865. var boneScale2 = this._bone2.getScale();
  79866. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79867. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79868. }
  79869. else if (this._bone1.children[0]) {
  79870. mesh.computeWorldMatrix(true);
  79871. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79872. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79873. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79874. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79875. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79876. }
  79877. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79878. this.maxAngle = Math.PI;
  79879. if (options) {
  79880. if (options.targetMesh) {
  79881. this.targetMesh = options.targetMesh;
  79882. this.targetMesh.computeWorldMatrix(true);
  79883. }
  79884. if (options.poleTargetMesh) {
  79885. this.poleTargetMesh = options.poleTargetMesh;
  79886. this.poleTargetMesh.computeWorldMatrix(true);
  79887. }
  79888. else if (options.poleTargetBone) {
  79889. this.poleTargetBone = options.poleTargetBone;
  79890. }
  79891. else if (this._bone1.getParent()) {
  79892. this.poleTargetBone = this._bone1.getParent();
  79893. }
  79894. if (options.poleTargetLocalOffset) {
  79895. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79896. }
  79897. if (options.poleAngle) {
  79898. this.poleAngle = options.poleAngle;
  79899. }
  79900. if (options.bendAxis) {
  79901. this._bendAxis.copyFrom(options.bendAxis);
  79902. }
  79903. if (options.maxAngle) {
  79904. this.maxAngle = options.maxAngle;
  79905. }
  79906. if (options.slerpAmount) {
  79907. this.slerpAmount = options.slerpAmount;
  79908. }
  79909. }
  79910. }
  79911. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79912. /**
  79913. * Gets or sets maximum allowed angle
  79914. */
  79915. get: function () {
  79916. return this._maxAngle;
  79917. },
  79918. set: function (value) {
  79919. this._setMaxAngle(value);
  79920. },
  79921. enumerable: true,
  79922. configurable: true
  79923. });
  79924. BoneIKController.prototype._setMaxAngle = function (ang) {
  79925. if (ang < 0) {
  79926. ang = 0;
  79927. }
  79928. if (ang > Math.PI || ang == undefined) {
  79929. ang = Math.PI;
  79930. }
  79931. this._maxAngle = ang;
  79932. var a = this._bone1Length;
  79933. var b = this._bone2Length;
  79934. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79935. };
  79936. /**
  79937. * Force the controller to update the bones
  79938. */
  79939. BoneIKController.prototype.update = function () {
  79940. var bone1 = this._bone1;
  79941. if (!bone1) {
  79942. return;
  79943. }
  79944. var target = this.targetPosition;
  79945. var poleTarget = this.poleTargetPosition;
  79946. var mat1 = BoneIKController._tmpMats[0];
  79947. var mat2 = BoneIKController._tmpMats[1];
  79948. if (this.targetMesh) {
  79949. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79950. }
  79951. if (this.poleTargetBone) {
  79952. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79953. }
  79954. else if (this.poleTargetMesh) {
  79955. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79956. }
  79957. var bonePos = BoneIKController._tmpVecs[0];
  79958. var zaxis = BoneIKController._tmpVecs[1];
  79959. var xaxis = BoneIKController._tmpVecs[2];
  79960. var yaxis = BoneIKController._tmpVecs[3];
  79961. var upAxis = BoneIKController._tmpVecs[4];
  79962. var _tmpQuat = BoneIKController._tmpQuat;
  79963. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79964. poleTarget.subtractToRef(bonePos, upAxis);
  79965. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79966. upAxis.y = 1;
  79967. }
  79968. else {
  79969. upAxis.normalize();
  79970. }
  79971. target.subtractToRef(bonePos, yaxis);
  79972. yaxis.normalize();
  79973. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79974. zaxis.normalize();
  79975. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79976. xaxis.normalize();
  79977. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79978. var a = this._bone1Length;
  79979. var b = this._bone2Length;
  79980. var c = BABYLON.Vector3.Distance(bonePos, target);
  79981. if (this._maxReach > 0) {
  79982. c = Math.min(this._maxReach, c);
  79983. }
  79984. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79985. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79986. if (acosa > 1) {
  79987. acosa = 1;
  79988. }
  79989. if (acosb > 1) {
  79990. acosb = 1;
  79991. }
  79992. if (acosa < -1) {
  79993. acosa = -1;
  79994. }
  79995. if (acosb < -1) {
  79996. acosb = -1;
  79997. }
  79998. var angA = Math.acos(acosa);
  79999. var angB = Math.acos(acosb);
  80000. var angC = -angA - angB;
  80001. if (this._rightHandedSystem) {
  80002. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80003. mat2.multiplyToRef(mat1, mat1);
  80004. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80005. mat2.multiplyToRef(mat1, mat1);
  80006. }
  80007. else {
  80008. var _tmpVec = BoneIKController._tmpVecs[5];
  80009. _tmpVec.copyFrom(this._bendAxis);
  80010. _tmpVec.x *= -1;
  80011. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80012. mat2.multiplyToRef(mat1, mat1);
  80013. }
  80014. if (this.poleAngle) {
  80015. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80016. mat1.multiplyToRef(mat2, mat1);
  80017. }
  80018. if (this._bone1) {
  80019. if (this.slerpAmount < 1) {
  80020. if (!this._slerping) {
  80021. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80022. }
  80023. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80024. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80025. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80026. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80027. this._slerping = true;
  80028. }
  80029. else {
  80030. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80031. this._bone1Mat.copyFrom(mat1);
  80032. this._slerping = false;
  80033. }
  80034. }
  80035. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80036. this._bone2Ang = angC;
  80037. };
  80038. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80039. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80040. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80041. return BoneIKController;
  80042. }());
  80043. BABYLON.BoneIKController = BoneIKController;
  80044. })(BABYLON || (BABYLON = {}));
  80045. //# sourceMappingURL=babylon.boneIKController.js.map
  80046. var BABYLON;
  80047. (function (BABYLON) {
  80048. /**
  80049. * Class used to make a bone look toward a point in space
  80050. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80051. */
  80052. var BoneLookController = /** @class */ (function () {
  80053. /**
  80054. * Create a BoneLookController
  80055. * @param mesh the mesh that the bone belongs to
  80056. * @param bone the bone that will be looking to the target
  80057. * @param target the target Vector3 to look at
  80058. * @param settings optional settings:
  80059. * * maxYaw: the maximum angle the bone will yaw to
  80060. * * minYaw: the minimum angle the bone will yaw to
  80061. * * maxPitch: the maximum angle the bone will pitch to
  80062. * * minPitch: the minimum angle the bone will yaw to
  80063. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80064. * * upAxis: the up axis of the coordinate system
  80065. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80066. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80067. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80068. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80069. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80070. * * adjustRoll: used to make an adjustment to the roll of the bone
  80071. **/
  80072. function BoneLookController(mesh, bone, target, options) {
  80073. /**
  80074. * The up axis of the coordinate system that is used when the bone is rotated
  80075. */
  80076. this.upAxis = BABYLON.Vector3.Up();
  80077. /**
  80078. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80079. */
  80080. this.upAxisSpace = BABYLON.Space.LOCAL;
  80081. /**
  80082. * Used to make an adjustment to the yaw of the bone
  80083. */
  80084. this.adjustYaw = 0;
  80085. /**
  80086. * Used to make an adjustment to the pitch of the bone
  80087. */
  80088. this.adjustPitch = 0;
  80089. /**
  80090. * Used to make an adjustment to the roll of the bone
  80091. */
  80092. this.adjustRoll = 0;
  80093. /**
  80094. * 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)
  80095. */
  80096. this.slerpAmount = 1;
  80097. this._boneQuat = BABYLON.Quaternion.Identity();
  80098. this._slerping = false;
  80099. this._firstFrameSkipped = false;
  80100. this._fowardAxis = BABYLON.Vector3.Forward();
  80101. this.mesh = mesh;
  80102. this.bone = bone;
  80103. this.target = target;
  80104. if (options) {
  80105. if (options.adjustYaw) {
  80106. this.adjustYaw = options.adjustYaw;
  80107. }
  80108. if (options.adjustPitch) {
  80109. this.adjustPitch = options.adjustPitch;
  80110. }
  80111. if (options.adjustRoll) {
  80112. this.adjustRoll = options.adjustRoll;
  80113. }
  80114. if (options.maxYaw != null) {
  80115. this.maxYaw = options.maxYaw;
  80116. }
  80117. else {
  80118. this.maxYaw = Math.PI;
  80119. }
  80120. if (options.minYaw != null) {
  80121. this.minYaw = options.minYaw;
  80122. }
  80123. else {
  80124. this.minYaw = -Math.PI;
  80125. }
  80126. if (options.maxPitch != null) {
  80127. this.maxPitch = options.maxPitch;
  80128. }
  80129. else {
  80130. this.maxPitch = Math.PI;
  80131. }
  80132. if (options.minPitch != null) {
  80133. this.minPitch = options.minPitch;
  80134. }
  80135. else {
  80136. this.minPitch = -Math.PI;
  80137. }
  80138. if (options.slerpAmount != null) {
  80139. this.slerpAmount = options.slerpAmount;
  80140. }
  80141. if (options.upAxis != null) {
  80142. this.upAxis = options.upAxis;
  80143. }
  80144. if (options.upAxisSpace != null) {
  80145. this.upAxisSpace = options.upAxisSpace;
  80146. }
  80147. if (options.yawAxis != null || options.pitchAxis != null) {
  80148. var newYawAxis = BABYLON.Axis.Y;
  80149. var newPitchAxis = BABYLON.Axis.X;
  80150. if (options.yawAxis != null) {
  80151. newYawAxis = options.yawAxis.clone();
  80152. newYawAxis.normalize();
  80153. }
  80154. if (options.pitchAxis != null) {
  80155. newPitchAxis = options.pitchAxis.clone();
  80156. newPitchAxis.normalize();
  80157. }
  80158. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80159. this._transformYawPitch = BABYLON.Matrix.Identity();
  80160. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80161. this._transformYawPitchInv = this._transformYawPitch.clone();
  80162. this._transformYawPitch.invert();
  80163. }
  80164. }
  80165. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80166. this.upAxisSpace = BABYLON.Space.LOCAL;
  80167. }
  80168. }
  80169. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80170. /**
  80171. * Gets or sets the minimum yaw angle that the bone can look to
  80172. */
  80173. get: function () {
  80174. return this._minYaw;
  80175. },
  80176. set: function (value) {
  80177. this._minYaw = value;
  80178. this._minYawSin = Math.sin(value);
  80179. this._minYawCos = Math.cos(value);
  80180. if (this._maxYaw != null) {
  80181. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80182. this._yawRange = this._maxYaw - this._minYaw;
  80183. }
  80184. },
  80185. enumerable: true,
  80186. configurable: true
  80187. });
  80188. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80189. /**
  80190. * Gets or sets the maximum yaw angle that the bone can look to
  80191. */
  80192. get: function () {
  80193. return this._maxYaw;
  80194. },
  80195. set: function (value) {
  80196. this._maxYaw = value;
  80197. this._maxYawSin = Math.sin(value);
  80198. this._maxYawCos = Math.cos(value);
  80199. if (this._minYaw != null) {
  80200. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80201. this._yawRange = this._maxYaw - this._minYaw;
  80202. }
  80203. },
  80204. enumerable: true,
  80205. configurable: true
  80206. });
  80207. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80208. /**
  80209. * Gets or sets the minimum pitch angle that the bone can look to
  80210. */
  80211. get: function () {
  80212. return this._minPitch;
  80213. },
  80214. set: function (value) {
  80215. this._minPitch = value;
  80216. this._minPitchTan = Math.tan(value);
  80217. },
  80218. enumerable: true,
  80219. configurable: true
  80220. });
  80221. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80222. /**
  80223. * Gets or sets the maximum pitch angle that the bone can look to
  80224. */
  80225. get: function () {
  80226. return this._maxPitch;
  80227. },
  80228. set: function (value) {
  80229. this._maxPitch = value;
  80230. this._maxPitchTan = Math.tan(value);
  80231. },
  80232. enumerable: true,
  80233. configurable: true
  80234. });
  80235. /**
  80236. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80237. */
  80238. BoneLookController.prototype.update = function () {
  80239. //skip the first frame when slerping so that the mesh rotation is correct
  80240. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80241. this._firstFrameSkipped = true;
  80242. return;
  80243. }
  80244. var bone = this.bone;
  80245. var bonePos = BoneLookController._tmpVecs[0];
  80246. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80247. var target = this.target;
  80248. var _tmpMat1 = BoneLookController._tmpMats[0];
  80249. var _tmpMat2 = BoneLookController._tmpMats[1];
  80250. var mesh = this.mesh;
  80251. var parentBone = bone.getParent();
  80252. var upAxis = BoneLookController._tmpVecs[1];
  80253. upAxis.copyFrom(this.upAxis);
  80254. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80255. if (this._transformYawPitch) {
  80256. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80257. }
  80258. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80259. }
  80260. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80261. mesh.getDirectionToRef(upAxis, upAxis);
  80262. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80263. upAxis.normalize();
  80264. }
  80265. }
  80266. var checkYaw = false;
  80267. var checkPitch = false;
  80268. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80269. checkYaw = true;
  80270. }
  80271. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80272. checkPitch = true;
  80273. }
  80274. if (checkYaw || checkPitch) {
  80275. var spaceMat = BoneLookController._tmpMats[2];
  80276. var spaceMatInv = BoneLookController._tmpMats[3];
  80277. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80278. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80279. }
  80280. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80281. spaceMat.copyFrom(mesh.getWorldMatrix());
  80282. }
  80283. else {
  80284. var forwardAxis = BoneLookController._tmpVecs[2];
  80285. forwardAxis.copyFrom(this._fowardAxis);
  80286. if (this._transformYawPitch) {
  80287. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80288. }
  80289. if (parentBone) {
  80290. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80291. }
  80292. else {
  80293. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80294. }
  80295. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80296. rightAxis.normalize();
  80297. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80298. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80299. }
  80300. spaceMat.invertToRef(spaceMatInv);
  80301. var xzlen = null;
  80302. if (checkPitch) {
  80303. var localTarget = BoneLookController._tmpVecs[3];
  80304. target.subtractToRef(bonePos, localTarget);
  80305. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80306. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80307. var pitch = Math.atan2(localTarget.y, xzlen);
  80308. var newPitch = pitch;
  80309. if (pitch > this._maxPitch) {
  80310. localTarget.y = this._maxPitchTan * xzlen;
  80311. newPitch = this._maxPitch;
  80312. }
  80313. else if (pitch < this._minPitch) {
  80314. localTarget.y = this._minPitchTan * xzlen;
  80315. newPitch = this._minPitch;
  80316. }
  80317. if (pitch != newPitch) {
  80318. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80319. localTarget.addInPlace(bonePos);
  80320. target = localTarget;
  80321. }
  80322. }
  80323. if (checkYaw) {
  80324. var localTarget = BoneLookController._tmpVecs[4];
  80325. target.subtractToRef(bonePos, localTarget);
  80326. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80327. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80328. var newYaw = yaw;
  80329. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80330. if (xzlen == null) {
  80331. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80332. }
  80333. if (this._yawRange > Math.PI) {
  80334. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80335. localTarget.z = this._maxYawCos * xzlen;
  80336. localTarget.x = this._maxYawSin * xzlen;
  80337. newYaw = this._maxYaw;
  80338. }
  80339. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80340. localTarget.z = this._minYawCos * xzlen;
  80341. localTarget.x = this._minYawSin * xzlen;
  80342. newYaw = this._minYaw;
  80343. }
  80344. }
  80345. else {
  80346. if (yaw > this._maxYaw) {
  80347. localTarget.z = this._maxYawCos * xzlen;
  80348. localTarget.x = this._maxYawSin * xzlen;
  80349. newYaw = this._maxYaw;
  80350. }
  80351. else if (yaw < this._minYaw) {
  80352. localTarget.z = this._minYawCos * xzlen;
  80353. localTarget.x = this._minYawSin * xzlen;
  80354. newYaw = this._minYaw;
  80355. }
  80356. }
  80357. }
  80358. if (this._slerping && this._yawRange > Math.PI) {
  80359. //are we going to be crossing into the min/max region?
  80360. var boneFwd = BoneLookController._tmpVecs[8];
  80361. boneFwd.copyFrom(BABYLON.Axis.Z);
  80362. if (this._transformYawPitch) {
  80363. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80364. }
  80365. var boneRotMat = BoneLookController._tmpMats[4];
  80366. this._boneQuat.toRotationMatrix(boneRotMat);
  80367. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80368. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80369. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80370. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80371. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80372. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80373. if (angBtwTar > angBtwMidYaw) {
  80374. if (xzlen == null) {
  80375. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80376. }
  80377. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80378. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80379. if (angBtwMin < angBtwMax) {
  80380. newYaw = boneYaw + Math.PI * .75;
  80381. localTarget.z = Math.cos(newYaw) * xzlen;
  80382. localTarget.x = Math.sin(newYaw) * xzlen;
  80383. }
  80384. else {
  80385. newYaw = boneYaw - Math.PI * .75;
  80386. localTarget.z = Math.cos(newYaw) * xzlen;
  80387. localTarget.x = Math.sin(newYaw) * xzlen;
  80388. }
  80389. }
  80390. }
  80391. if (yaw != newYaw) {
  80392. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80393. localTarget.addInPlace(bonePos);
  80394. target = localTarget;
  80395. }
  80396. }
  80397. }
  80398. var zaxis = BoneLookController._tmpVecs[5];
  80399. var xaxis = BoneLookController._tmpVecs[6];
  80400. var yaxis = BoneLookController._tmpVecs[7];
  80401. var _tmpQuat = BoneLookController._tmpQuat;
  80402. target.subtractToRef(bonePos, zaxis);
  80403. zaxis.normalize();
  80404. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80405. xaxis.normalize();
  80406. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80407. yaxis.normalize();
  80408. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80409. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80410. return;
  80411. }
  80412. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80413. return;
  80414. }
  80415. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80416. return;
  80417. }
  80418. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80419. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80420. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80421. }
  80422. if (this.slerpAmount < 1) {
  80423. if (!this._slerping) {
  80424. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80425. }
  80426. if (this._transformYawPitch) {
  80427. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80428. }
  80429. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80430. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80431. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80432. this._slerping = true;
  80433. }
  80434. else {
  80435. if (this._transformYawPitch) {
  80436. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80437. }
  80438. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80439. this._slerping = false;
  80440. }
  80441. };
  80442. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80443. var angDiff = ang2 - ang1;
  80444. angDiff %= Math.PI * 2;
  80445. if (angDiff > Math.PI) {
  80446. angDiff -= Math.PI * 2;
  80447. }
  80448. else if (angDiff < -Math.PI) {
  80449. angDiff += Math.PI * 2;
  80450. }
  80451. return angDiff;
  80452. };
  80453. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80454. ang1 %= (2 * Math.PI);
  80455. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80456. ang2 %= (2 * Math.PI);
  80457. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80458. var ab = 0;
  80459. if (ang1 < ang2) {
  80460. ab = ang2 - ang1;
  80461. }
  80462. else {
  80463. ab = ang1 - ang2;
  80464. }
  80465. if (ab > Math.PI) {
  80466. ab = Math.PI * 2 - ab;
  80467. }
  80468. return ab;
  80469. };
  80470. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80471. ang %= (2 * Math.PI);
  80472. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80473. ang1 %= (2 * Math.PI);
  80474. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80475. ang2 %= (2 * Math.PI);
  80476. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80477. if (ang1 < ang2) {
  80478. if (ang > ang1 && ang < ang2) {
  80479. return true;
  80480. }
  80481. }
  80482. else {
  80483. if (ang > ang2 && ang < ang1) {
  80484. return true;
  80485. }
  80486. }
  80487. return false;
  80488. };
  80489. 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()];
  80490. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80491. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80492. return BoneLookController;
  80493. }());
  80494. BABYLON.BoneLookController = BoneLookController;
  80495. })(BABYLON || (BABYLON = {}));
  80496. //# sourceMappingURL=babylon.boneLookController.js.map
  80497. var BABYLON;
  80498. (function (BABYLON) {
  80499. /**
  80500. * Class used to handle skinning animations
  80501. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80502. */
  80503. var Skeleton = /** @class */ (function () {
  80504. /**
  80505. * Creates a new skeleton
  80506. * @param name defines the skeleton name
  80507. * @param id defines the skeleton Id
  80508. * @param scene defines the hosting scene
  80509. */
  80510. function Skeleton(
  80511. /** defines the skeleton name */
  80512. name,
  80513. /** defines the skeleton Id */
  80514. id, scene) {
  80515. this.name = name;
  80516. this.id = id;
  80517. /**
  80518. * Gets the list of child bones
  80519. */
  80520. this.bones = new Array();
  80521. /**
  80522. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80523. */
  80524. this.needInitialSkinMatrix = false;
  80525. this._isDirty = true;
  80526. this._meshesWithPoseMatrix = new Array();
  80527. this._identity = BABYLON.Matrix.Identity();
  80528. this._ranges = {};
  80529. this._lastAbsoluteTransformsUpdateId = -1;
  80530. /**
  80531. * Specifies if the skeleton should be serialized
  80532. */
  80533. this.doNotSerialize = false;
  80534. this._animationPropertiesOverride = null;
  80535. // Events
  80536. /**
  80537. * An observable triggered before computing the skeleton's matrices
  80538. */
  80539. this.onBeforeComputeObservable = new BABYLON.Observable();
  80540. this.bones = [];
  80541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80542. scene.skeletons.push(this);
  80543. //make sure it will recalculate the matrix next time prepare is called.
  80544. this._isDirty = true;
  80545. }
  80546. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80547. /**
  80548. * Gets or sets the animation properties override
  80549. */
  80550. get: function () {
  80551. if (!this._animationPropertiesOverride) {
  80552. return this._scene.animationPropertiesOverride;
  80553. }
  80554. return this._animationPropertiesOverride;
  80555. },
  80556. set: function (value) {
  80557. this._animationPropertiesOverride = value;
  80558. },
  80559. enumerable: true,
  80560. configurable: true
  80561. });
  80562. // Members
  80563. /**
  80564. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80565. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80566. * @returns a Float32Array containing matrices data
  80567. */
  80568. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80569. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80570. return mesh._bonesTransformMatrices;
  80571. }
  80572. if (!this._transformMatrices) {
  80573. this.prepare();
  80574. }
  80575. return this._transformMatrices;
  80576. };
  80577. /**
  80578. * Gets the current hosting scene
  80579. * @returns a scene object
  80580. */
  80581. Skeleton.prototype.getScene = function () {
  80582. return this._scene;
  80583. };
  80584. // Methods
  80585. /**
  80586. * Gets a string representing the current skeleton data
  80587. * @param fullDetails defines a boolean indicating if we want a verbose version
  80588. * @returns a string representing the current skeleton data
  80589. */
  80590. Skeleton.prototype.toString = function (fullDetails) {
  80591. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80592. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80593. if (fullDetails) {
  80594. ret += ", Ranges: {";
  80595. var first = true;
  80596. for (var name_1 in this._ranges) {
  80597. if (first) {
  80598. ret += ", ";
  80599. first = false;
  80600. }
  80601. ret += name_1;
  80602. }
  80603. ret += "}";
  80604. }
  80605. return ret;
  80606. };
  80607. /**
  80608. * Get bone's index searching by name
  80609. * @param name defines bone's name to search for
  80610. * @return the indice of the bone. Returns -1 if not found
  80611. */
  80612. Skeleton.prototype.getBoneIndexByName = function (name) {
  80613. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80614. if (this.bones[boneIndex].name === name) {
  80615. return boneIndex;
  80616. }
  80617. }
  80618. return -1;
  80619. };
  80620. /**
  80621. * Creater a new animation range
  80622. * @param name defines the name of the range
  80623. * @param from defines the start key
  80624. * @param to defines the end key
  80625. */
  80626. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80627. // check name not already in use
  80628. if (!this._ranges[name]) {
  80629. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80630. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80631. if (this.bones[i].animations[0]) {
  80632. this.bones[i].animations[0].createRange(name, from, to);
  80633. }
  80634. }
  80635. }
  80636. };
  80637. /**
  80638. * Delete a specific animation range
  80639. * @param name defines the name of the range
  80640. * @param deleteFrames defines if frames must be removed as well
  80641. */
  80642. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80643. if (deleteFrames === void 0) { deleteFrames = true; }
  80644. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80645. if (this.bones[i].animations[0]) {
  80646. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80647. }
  80648. }
  80649. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80650. };
  80651. /**
  80652. * Gets a specific animation range
  80653. * @param name defines the name of the range to look for
  80654. * @returns the requested animation range or null if not found
  80655. */
  80656. Skeleton.prototype.getAnimationRange = function (name) {
  80657. return this._ranges[name];
  80658. };
  80659. /**
  80660. * Gets the list of all animation ranges defined on this skeleton
  80661. * @returns an array
  80662. */
  80663. Skeleton.prototype.getAnimationRanges = function () {
  80664. var animationRanges = [];
  80665. var name;
  80666. var i = 0;
  80667. for (name in this._ranges) {
  80668. animationRanges[i] = this._ranges[name];
  80669. i++;
  80670. }
  80671. return animationRanges;
  80672. };
  80673. /**
  80674. * Copy animation range from a source skeleton.
  80675. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80676. * @param source defines the source skeleton
  80677. * @param name defines the name of the range to copy
  80678. * @param rescaleAsRequired defines if rescaling must be applied if required
  80679. * @returns true if operation was successful
  80680. */
  80681. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80682. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80683. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80684. return false;
  80685. }
  80686. var ret = true;
  80687. var frameOffset = this._getHighestAnimationFrame() + 1;
  80688. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80689. var boneDict = {};
  80690. var sourceBones = source.bones;
  80691. var nBones;
  80692. var i;
  80693. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80694. boneDict[sourceBones[i].name] = sourceBones[i];
  80695. }
  80696. if (this.bones.length !== sourceBones.length) {
  80697. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80698. ret = false;
  80699. }
  80700. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80701. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80702. var boneName = this.bones[i].name;
  80703. var sourceBone = boneDict[boneName];
  80704. if (sourceBone) {
  80705. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80706. }
  80707. else {
  80708. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80709. ret = false;
  80710. }
  80711. }
  80712. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80713. var range = source.getAnimationRange(name);
  80714. if (range) {
  80715. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80716. }
  80717. return ret;
  80718. };
  80719. /**
  80720. * Forces the skeleton to go to rest pose
  80721. */
  80722. Skeleton.prototype.returnToRest = function () {
  80723. for (var index = 0; index < this.bones.length; index++) {
  80724. this.bones[index].returnToRest();
  80725. }
  80726. };
  80727. Skeleton.prototype._getHighestAnimationFrame = function () {
  80728. var ret = 0;
  80729. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80730. if (this.bones[i].animations[0]) {
  80731. var highest = this.bones[i].animations[0].getHighestFrame();
  80732. if (ret < highest) {
  80733. ret = highest;
  80734. }
  80735. }
  80736. }
  80737. return ret;
  80738. };
  80739. /**
  80740. * Begin a specific animation range
  80741. * @param name defines the name of the range to start
  80742. * @param loop defines if looping must be turned on (false by default)
  80743. * @param speedRatio defines the speed ratio to apply (1 by default)
  80744. * @param onAnimationEnd defines a callback which will be called when animation will end
  80745. * @returns a new animatable
  80746. */
  80747. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80748. var range = this.getAnimationRange(name);
  80749. if (!range) {
  80750. return null;
  80751. }
  80752. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80753. };
  80754. /** @hidden */
  80755. Skeleton.prototype._markAsDirty = function () {
  80756. this._isDirty = true;
  80757. };
  80758. /** @hidden */
  80759. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80760. this._meshesWithPoseMatrix.push(mesh);
  80761. };
  80762. /** @hidden */
  80763. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80764. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80765. if (index > -1) {
  80766. this._meshesWithPoseMatrix.splice(index, 1);
  80767. }
  80768. };
  80769. /** @hidden */
  80770. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80771. this.onBeforeComputeObservable.notifyObservers(this);
  80772. for (var index = 0; index < this.bones.length; index++) {
  80773. var bone = this.bones[index];
  80774. var parentBone = bone.getParent();
  80775. if (parentBone) {
  80776. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80777. }
  80778. else {
  80779. if (initialSkinMatrix) {
  80780. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80781. }
  80782. else {
  80783. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80784. }
  80785. }
  80786. if (bone._index !== -1) {
  80787. var mappedIndex = bone._index === null ? index : bone._index;
  80788. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80789. }
  80790. }
  80791. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80792. };
  80793. /**
  80794. * Build all resources required to render a skeleton
  80795. */
  80796. Skeleton.prototype.prepare = function () {
  80797. if (!this._isDirty) {
  80798. return;
  80799. }
  80800. if (this.needInitialSkinMatrix) {
  80801. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80802. var mesh = this._meshesWithPoseMatrix[index];
  80803. var poseMatrix = mesh.getPoseMatrix();
  80804. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80805. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80806. }
  80807. if (this._synchronizedWithMesh !== mesh) {
  80808. this._synchronizedWithMesh = mesh;
  80809. // Prepare bones
  80810. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80811. var bone = this.bones[boneIndex];
  80812. if (!bone.getParent()) {
  80813. var matrix = bone.getBaseMatrix();
  80814. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80815. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80816. }
  80817. }
  80818. }
  80819. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80820. }
  80821. }
  80822. else {
  80823. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80824. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80825. }
  80826. this._computeTransformMatrices(this._transformMatrices, null);
  80827. }
  80828. this._isDirty = false;
  80829. this._scene._activeBones.addCount(this.bones.length, false);
  80830. };
  80831. /**
  80832. * Gets the list of animatables currently running for this skeleton
  80833. * @returns an array of animatables
  80834. */
  80835. Skeleton.prototype.getAnimatables = function () {
  80836. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80837. this._animatables = [];
  80838. for (var index = 0; index < this.bones.length; index++) {
  80839. this._animatables.push(this.bones[index]);
  80840. }
  80841. }
  80842. return this._animatables;
  80843. };
  80844. /**
  80845. * Clone the current skeleton
  80846. * @param name defines the name of the new skeleton
  80847. * @param id defines the id of the enw skeleton
  80848. * @returns the new skeleton
  80849. */
  80850. Skeleton.prototype.clone = function (name, id) {
  80851. var result = new Skeleton(name, id || name, this._scene);
  80852. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80853. for (var index = 0; index < this.bones.length; index++) {
  80854. var source = this.bones[index];
  80855. var parentBone = null;
  80856. var parent_1 = source.getParent();
  80857. if (parent_1) {
  80858. var parentIndex = this.bones.indexOf(parent_1);
  80859. parentBone = result.bones[parentIndex];
  80860. }
  80861. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80862. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80863. }
  80864. if (this._ranges) {
  80865. result._ranges = {};
  80866. for (var rangeName in this._ranges) {
  80867. var range = this._ranges[rangeName];
  80868. if (range) {
  80869. result._ranges[rangeName] = range.clone();
  80870. }
  80871. }
  80872. }
  80873. this._isDirty = true;
  80874. return result;
  80875. };
  80876. /**
  80877. * Enable animation blending for this skeleton
  80878. * @param blendingSpeed defines the blending speed to apply
  80879. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80880. */
  80881. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80882. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80883. this.bones.forEach(function (bone) {
  80884. bone.animations.forEach(function (animation) {
  80885. animation.enableBlending = true;
  80886. animation.blendingSpeed = blendingSpeed;
  80887. });
  80888. });
  80889. };
  80890. /**
  80891. * Releases all resources associated with the current skeleton
  80892. */
  80893. Skeleton.prototype.dispose = function () {
  80894. this._meshesWithPoseMatrix = [];
  80895. // Animations
  80896. this.getScene().stopAnimation(this);
  80897. // Remove from scene
  80898. this.getScene().removeSkeleton(this);
  80899. };
  80900. /**
  80901. * Serialize the skeleton in a JSON object
  80902. * @returns a JSON object
  80903. */
  80904. Skeleton.prototype.serialize = function () {
  80905. var serializationObject = {};
  80906. serializationObject.name = this.name;
  80907. serializationObject.id = this.id;
  80908. if (this.dimensionsAtRest) {
  80909. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80910. }
  80911. serializationObject.bones = [];
  80912. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80913. for (var index = 0; index < this.bones.length; index++) {
  80914. var bone = this.bones[index];
  80915. var parent_2 = bone.getParent();
  80916. var serializedBone = {
  80917. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80918. name: bone.name,
  80919. matrix: bone.getBaseMatrix().toArray(),
  80920. rest: bone.getRestPose().toArray()
  80921. };
  80922. serializationObject.bones.push(serializedBone);
  80923. if (bone.length) {
  80924. serializedBone.length = bone.length;
  80925. }
  80926. if (bone.metadata) {
  80927. serializedBone.metadata = bone.metadata;
  80928. }
  80929. if (bone.animations && bone.animations.length > 0) {
  80930. serializedBone.animation = bone.animations[0].serialize();
  80931. }
  80932. serializationObject.ranges = [];
  80933. for (var name in this._ranges) {
  80934. var source = this._ranges[name];
  80935. if (!source) {
  80936. continue;
  80937. }
  80938. var range = {};
  80939. range.name = name;
  80940. range.from = source.from;
  80941. range.to = source.to;
  80942. serializationObject.ranges.push(range);
  80943. }
  80944. }
  80945. return serializationObject;
  80946. };
  80947. /**
  80948. * Creates a new skeleton from serialized data
  80949. * @param parsedSkeleton defines the serialized data
  80950. * @param scene defines the hosting scene
  80951. * @returns a new skeleton
  80952. */
  80953. Skeleton.Parse = function (parsedSkeleton, scene) {
  80954. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80955. if (parsedSkeleton.dimensionsAtRest) {
  80956. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80957. }
  80958. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80959. var index;
  80960. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80961. var parsedBone = parsedSkeleton.bones[index];
  80962. var parentBone = null;
  80963. if (parsedBone.parentBoneIndex > -1) {
  80964. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80965. }
  80966. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80967. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80968. if (parsedBone.length) {
  80969. bone.length = parsedBone.length;
  80970. }
  80971. if (parsedBone.metadata) {
  80972. bone.metadata = parsedBone.metadata;
  80973. }
  80974. if (parsedBone.animation) {
  80975. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80976. }
  80977. }
  80978. // placed after bones, so createAnimationRange can cascade down
  80979. if (parsedSkeleton.ranges) {
  80980. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80981. var data = parsedSkeleton.ranges[index];
  80982. skeleton.createAnimationRange(data.name, data.from, data.to);
  80983. }
  80984. }
  80985. return skeleton;
  80986. };
  80987. /**
  80988. * Compute all node absolute transforms
  80989. * @param forceUpdate defines if computation must be done even if cache is up to date
  80990. */
  80991. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80992. if (forceUpdate === void 0) { forceUpdate = false; }
  80993. var renderId = this._scene.getRenderId();
  80994. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80995. this.bones[0].computeAbsoluteTransforms();
  80996. this._lastAbsoluteTransformsUpdateId = renderId;
  80997. }
  80998. };
  80999. /**
  81000. * Gets the root pose matrix
  81001. * @returns a matrix
  81002. */
  81003. Skeleton.prototype.getPoseMatrix = function () {
  81004. var poseMatrix = null;
  81005. if (this._meshesWithPoseMatrix.length > 0) {
  81006. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81007. }
  81008. return poseMatrix;
  81009. };
  81010. /**
  81011. * Sorts bones per internal index
  81012. */
  81013. Skeleton.prototype.sortBones = function () {
  81014. var bones = new Array();
  81015. var visited = new Array(this.bones.length);
  81016. for (var index = 0; index < this.bones.length; index++) {
  81017. this._sortBones(index, bones, visited);
  81018. }
  81019. this.bones = bones;
  81020. };
  81021. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81022. if (visited[index]) {
  81023. return;
  81024. }
  81025. visited[index] = true;
  81026. var bone = this.bones[index];
  81027. if (bone._index === undefined) {
  81028. bone._index = index;
  81029. }
  81030. var parentBone = bone.getParent();
  81031. if (parentBone) {
  81032. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81033. }
  81034. bones.push(bone);
  81035. };
  81036. return Skeleton;
  81037. }());
  81038. BABYLON.Skeleton = Skeleton;
  81039. })(BABYLON || (BABYLON = {}));
  81040. //# sourceMappingURL=babylon.skeleton.js.map
  81041. var BABYLON;
  81042. (function (BABYLON) {
  81043. var SphericalPolynomial = /** @class */ (function () {
  81044. function SphericalPolynomial() {
  81045. this.x = BABYLON.Vector3.Zero();
  81046. this.y = BABYLON.Vector3.Zero();
  81047. this.z = BABYLON.Vector3.Zero();
  81048. this.xx = BABYLON.Vector3.Zero();
  81049. this.yy = BABYLON.Vector3.Zero();
  81050. this.zz = BABYLON.Vector3.Zero();
  81051. this.xy = BABYLON.Vector3.Zero();
  81052. this.yz = BABYLON.Vector3.Zero();
  81053. this.zx = BABYLON.Vector3.Zero();
  81054. }
  81055. SphericalPolynomial.prototype.addAmbient = function (color) {
  81056. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81057. this.xx = this.xx.add(colorVector);
  81058. this.yy = this.yy.add(colorVector);
  81059. this.zz = this.zz.add(colorVector);
  81060. };
  81061. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81062. var result = new SphericalPolynomial();
  81063. result.x = harmonics.L11.scale(1.02333);
  81064. result.y = harmonics.L1_1.scale(1.02333);
  81065. result.z = harmonics.L10.scale(1.02333);
  81066. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81067. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81068. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81069. result.yz = harmonics.L2_1.scale(0.858086);
  81070. result.zx = harmonics.L21.scale(0.858086);
  81071. result.xy = harmonics.L2_2.scale(0.858086);
  81072. result.scale(1.0 / Math.PI);
  81073. return result;
  81074. };
  81075. SphericalPolynomial.prototype.scale = function (scale) {
  81076. this.x = this.x.scale(scale);
  81077. this.y = this.y.scale(scale);
  81078. this.z = this.z.scale(scale);
  81079. this.xx = this.xx.scale(scale);
  81080. this.yy = this.yy.scale(scale);
  81081. this.zz = this.zz.scale(scale);
  81082. this.yz = this.yz.scale(scale);
  81083. this.zx = this.zx.scale(scale);
  81084. this.xy = this.xy.scale(scale);
  81085. };
  81086. return SphericalPolynomial;
  81087. }());
  81088. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81089. var SphericalHarmonics = /** @class */ (function () {
  81090. function SphericalHarmonics() {
  81091. this.L00 = BABYLON.Vector3.Zero();
  81092. this.L1_1 = BABYLON.Vector3.Zero();
  81093. this.L10 = BABYLON.Vector3.Zero();
  81094. this.L11 = BABYLON.Vector3.Zero();
  81095. this.L2_2 = BABYLON.Vector3.Zero();
  81096. this.L2_1 = BABYLON.Vector3.Zero();
  81097. this.L20 = BABYLON.Vector3.Zero();
  81098. this.L21 = BABYLON.Vector3.Zero();
  81099. this.L22 = BABYLON.Vector3.Zero();
  81100. }
  81101. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81102. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81103. var c = colorVector.scale(deltaSolidAngle);
  81104. this.L00 = this.L00.add(c.scale(0.282095));
  81105. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81106. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81107. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81108. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81109. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81110. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81111. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81112. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81113. };
  81114. SphericalHarmonics.prototype.scale = function (scale) {
  81115. this.L00 = this.L00.scale(scale);
  81116. this.L1_1 = this.L1_1.scale(scale);
  81117. this.L10 = this.L10.scale(scale);
  81118. this.L11 = this.L11.scale(scale);
  81119. this.L2_2 = this.L2_2.scale(scale);
  81120. this.L2_1 = this.L2_1.scale(scale);
  81121. this.L20 = this.L20.scale(scale);
  81122. this.L21 = this.L21.scale(scale);
  81123. this.L22 = this.L22.scale(scale);
  81124. };
  81125. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81126. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81127. //
  81128. // E_lm = A_l * L_lm
  81129. //
  81130. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81131. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81132. // the scaling factors are given in equation 9.
  81133. // Constant (Band 0)
  81134. this.L00 = this.L00.scale(3.141593);
  81135. // Linear (Band 1)
  81136. this.L1_1 = this.L1_1.scale(2.094395);
  81137. this.L10 = this.L10.scale(2.094395);
  81138. this.L11 = this.L11.scale(2.094395);
  81139. // Quadratic (Band 2)
  81140. this.L2_2 = this.L2_2.scale(0.785398);
  81141. this.L2_1 = this.L2_1.scale(0.785398);
  81142. this.L20 = this.L20.scale(0.785398);
  81143. this.L21 = this.L21.scale(0.785398);
  81144. this.L22 = this.L22.scale(0.785398);
  81145. };
  81146. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81147. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81148. // L = (1/pi) * E * rho
  81149. //
  81150. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81151. this.scale(1.0 / Math.PI);
  81152. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81153. // (The pixel shader must apply albedo after texture fetches, etc).
  81154. };
  81155. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81156. var result = new SphericalHarmonics();
  81157. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81158. result.L1_1 = polynomial.y.scale(0.977204);
  81159. result.L10 = polynomial.z.scale(0.977204);
  81160. result.L11 = polynomial.x.scale(0.977204);
  81161. result.L2_2 = polynomial.xy.scale(1.16538);
  81162. result.L2_1 = polynomial.yz.scale(1.16538);
  81163. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81164. result.L21 = polynomial.zx.scale(1.16538);
  81165. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81166. result.scale(Math.PI);
  81167. return result;
  81168. };
  81169. return SphericalHarmonics;
  81170. }());
  81171. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81172. })(BABYLON || (BABYLON = {}));
  81173. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81174. var BABYLON;
  81175. (function (BABYLON) {
  81176. var FileFaceOrientation = /** @class */ (function () {
  81177. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81178. this.name = name;
  81179. this.worldAxisForNormal = worldAxisForNormal;
  81180. this.worldAxisForFileX = worldAxisForFileX;
  81181. this.worldAxisForFileY = worldAxisForFileY;
  81182. }
  81183. return FileFaceOrientation;
  81184. }());
  81185. ;
  81186. /**
  81187. * Helper class dealing with the extraction of spherical polynomial dataArray
  81188. * from a cube map.
  81189. */
  81190. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81191. function CubeMapToSphericalPolynomialTools() {
  81192. }
  81193. /**
  81194. * Converts a texture to the according Spherical Polynomial data.
  81195. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81196. *
  81197. * @param texture The texture to extract the information from.
  81198. * @return The Spherical Polynomial data.
  81199. */
  81200. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81201. if (!texture.isCube) {
  81202. // Only supports cube Textures currently.
  81203. return null;
  81204. }
  81205. var size = texture.getSize().width;
  81206. var right = texture.readPixels(0);
  81207. var left = texture.readPixels(1);
  81208. var up;
  81209. var down;
  81210. if (texture.isRenderTarget) {
  81211. up = texture.readPixels(3);
  81212. down = texture.readPixels(2);
  81213. }
  81214. else {
  81215. up = texture.readPixels(2);
  81216. down = texture.readPixels(3);
  81217. }
  81218. var front = texture.readPixels(4);
  81219. var back = texture.readPixels(5);
  81220. var gammaSpace = texture.gammaSpace;
  81221. // Always read as RGBA.
  81222. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81223. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81224. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81225. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81226. }
  81227. var cubeInfo = {
  81228. size: size,
  81229. right: right,
  81230. left: left,
  81231. up: up,
  81232. down: down,
  81233. front: front,
  81234. back: back,
  81235. format: format,
  81236. type: type,
  81237. gammaSpace: gammaSpace,
  81238. };
  81239. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81240. };
  81241. /**
  81242. * Converts a cubemap to the according Spherical Polynomial data.
  81243. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81244. *
  81245. * @param cubeInfo The Cube map to extract the information from.
  81246. * @return The Spherical Polynomial data.
  81247. */
  81248. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81249. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81250. var totalSolidAngle = 0.0;
  81251. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81252. var du = 2.0 / cubeInfo.size;
  81253. var dv = du;
  81254. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81255. var minUV = du * 0.5 - 1.0;
  81256. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81257. var fileFace = this.FileFaces[faceIndex];
  81258. var dataArray = cubeInfo[fileFace.name];
  81259. var v = minUV;
  81260. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81261. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81262. // Because SP is still linear, so summation is fine in that basis.
  81263. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81264. for (var y = 0; y < cubeInfo.size; y++) {
  81265. var u = minUV;
  81266. for (var x = 0; x < cubeInfo.size; x++) {
  81267. // World direction (not normalised)
  81268. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81269. worldDirection.normalize();
  81270. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81271. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81272. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81273. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81274. // Handle Integer types.
  81275. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81276. r /= 255;
  81277. g /= 255;
  81278. b /= 255;
  81279. }
  81280. // Handle Gamma space textures.
  81281. if (cubeInfo.gammaSpace) {
  81282. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81283. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81284. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81285. }
  81286. var color = new BABYLON.Color3(r, g, b);
  81287. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81288. totalSolidAngle += deltaSolidAngle;
  81289. u += du;
  81290. }
  81291. v += dv;
  81292. }
  81293. }
  81294. // Solid angle for entire sphere is 4*pi
  81295. var sphereSolidAngle = 4.0 * Math.PI;
  81296. // Adjust the solid angle to allow for how many faces we processed.
  81297. var facesProcessed = 6.0;
  81298. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81299. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81300. // This is needed because the numerical integration over the cube uses a
  81301. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81302. // and also to compensate for accumulative error due to float precision in the summation.
  81303. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81304. sphericalHarmonics.scale(correctionFactor);
  81305. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81306. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81307. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81308. };
  81309. CubeMapToSphericalPolynomialTools.FileFaces = [
  81310. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81311. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81312. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81313. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81314. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81315. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81316. ];
  81317. return CubeMapToSphericalPolynomialTools;
  81318. }());
  81319. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81320. })(BABYLON || (BABYLON = {}));
  81321. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81322. var BABYLON;
  81323. (function (BABYLON) {
  81324. /**
  81325. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81326. */
  81327. var PanoramaToCubeMapTools = /** @class */ (function () {
  81328. function PanoramaToCubeMapTools() {
  81329. }
  81330. /**
  81331. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81332. *
  81333. * @param float32Array The source data.
  81334. * @param inputWidth The width of the input panorama.
  81335. * @param inputhHeight The height of the input panorama.
  81336. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81337. * @return The cubemap data
  81338. */
  81339. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81340. if (!float32Array) {
  81341. throw "ConvertPanoramaToCubemap: input cannot be null";
  81342. }
  81343. if (float32Array.length != inputWidth * inputHeight * 3) {
  81344. throw "ConvertPanoramaToCubemap: input size is wrong";
  81345. }
  81346. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81347. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81348. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81349. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81350. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81351. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81352. return {
  81353. front: textureFront,
  81354. back: textureBack,
  81355. left: textureLeft,
  81356. right: textureRight,
  81357. up: textureUp,
  81358. down: textureDown,
  81359. size: size,
  81360. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81361. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81362. gammaSpace: false,
  81363. };
  81364. };
  81365. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81366. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81367. var textureArray = new Float32Array(buffer);
  81368. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81369. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81370. var dy = 1 / texSize;
  81371. var fy = 0;
  81372. for (var y = 0; y < texSize; y++) {
  81373. var xv1 = faceData[0];
  81374. var xv2 = faceData[2];
  81375. for (var x = 0; x < texSize; x++) {
  81376. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81377. v.normalize();
  81378. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81379. // 3 channels per pixels
  81380. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81381. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81382. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81383. xv1 = xv1.add(rotDX1);
  81384. xv2 = xv2.add(rotDX2);
  81385. }
  81386. fy += dy;
  81387. }
  81388. return textureArray;
  81389. };
  81390. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81391. var theta = Math.atan2(vDir.z, vDir.x);
  81392. var phi = Math.acos(vDir.y);
  81393. while (theta < -Math.PI)
  81394. theta += 2 * Math.PI;
  81395. while (theta > Math.PI)
  81396. theta -= 2 * Math.PI;
  81397. var dx = theta / Math.PI;
  81398. var dy = phi / Math.PI;
  81399. // recenter.
  81400. dx = dx * 0.5 + 0.5;
  81401. var px = Math.round(dx * inputWidth);
  81402. if (px < 0)
  81403. px = 0;
  81404. else if (px >= inputWidth)
  81405. px = inputWidth - 1;
  81406. var py = Math.round(dy * inputHeight);
  81407. if (py < 0)
  81408. py = 0;
  81409. else if (py >= inputHeight)
  81410. py = inputHeight - 1;
  81411. var inputY = (inputHeight - py - 1);
  81412. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81413. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81414. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81415. return {
  81416. r: r,
  81417. g: g,
  81418. b: b
  81419. };
  81420. };
  81421. PanoramaToCubeMapTools.FACE_FRONT = [
  81422. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81423. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81424. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81425. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81426. ];
  81427. PanoramaToCubeMapTools.FACE_BACK = [
  81428. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81429. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81430. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81431. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81432. ];
  81433. PanoramaToCubeMapTools.FACE_RIGHT = [
  81434. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81435. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81436. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81437. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81438. ];
  81439. PanoramaToCubeMapTools.FACE_LEFT = [
  81440. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81441. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81442. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81443. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81444. ];
  81445. PanoramaToCubeMapTools.FACE_DOWN = [
  81446. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81447. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81448. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81449. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81450. ];
  81451. PanoramaToCubeMapTools.FACE_UP = [
  81452. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81453. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81454. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81455. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81456. ];
  81457. return PanoramaToCubeMapTools;
  81458. }());
  81459. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81460. })(BABYLON || (BABYLON = {}));
  81461. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81462. var BABYLON;
  81463. (function (BABYLON) {
  81464. ;
  81465. /**
  81466. * This groups tools to convert HDR texture to native colors array.
  81467. */
  81468. var HDRTools = /** @class */ (function () {
  81469. function HDRTools() {
  81470. }
  81471. HDRTools.Ldexp = function (mantissa, exponent) {
  81472. if (exponent > 1023) {
  81473. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81474. }
  81475. if (exponent < -1074) {
  81476. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81477. }
  81478. return mantissa * Math.pow(2, exponent);
  81479. };
  81480. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81481. if (exponent > 0) { /*nonzero pixel*/
  81482. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81483. float32array[index + 0] = red * exponent;
  81484. float32array[index + 1] = green * exponent;
  81485. float32array[index + 2] = blue * exponent;
  81486. }
  81487. else {
  81488. float32array[index + 0] = 0;
  81489. float32array[index + 1] = 0;
  81490. float32array[index + 2] = 0;
  81491. }
  81492. };
  81493. HDRTools.readStringLine = function (uint8array, startIndex) {
  81494. var line = "";
  81495. var character = "";
  81496. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81497. character = String.fromCharCode(uint8array[i]);
  81498. if (character == "\n") {
  81499. break;
  81500. }
  81501. line += character;
  81502. }
  81503. return line;
  81504. };
  81505. /**
  81506. * Reads header information from an RGBE texture stored in a native array.
  81507. * More information on this format are available here:
  81508. * https://en.wikipedia.org/wiki/RGBE_image_format
  81509. *
  81510. * @param uint8array The binary file stored in native array.
  81511. * @return The header information.
  81512. */
  81513. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81514. var height = 0;
  81515. var width = 0;
  81516. var line = this.readStringLine(uint8array, 0);
  81517. if (line[0] != '#' || line[1] != '?') {
  81518. throw "Bad HDR Format.";
  81519. }
  81520. var endOfHeader = false;
  81521. var findFormat = false;
  81522. var lineIndex = 0;
  81523. do {
  81524. lineIndex += (line.length + 1);
  81525. line = this.readStringLine(uint8array, lineIndex);
  81526. if (line == "FORMAT=32-bit_rle_rgbe") {
  81527. findFormat = true;
  81528. }
  81529. else if (line.length == 0) {
  81530. endOfHeader = true;
  81531. }
  81532. } while (!endOfHeader);
  81533. if (!findFormat) {
  81534. throw "HDR Bad header format, unsupported FORMAT";
  81535. }
  81536. lineIndex += (line.length + 1);
  81537. line = this.readStringLine(uint8array, lineIndex);
  81538. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81539. var match = sizeRegexp.exec(line);
  81540. // TODO. Support +Y and -X if needed.
  81541. if (!match || match.length < 3) {
  81542. throw "HDR Bad header format, no size";
  81543. }
  81544. width = parseInt(match[2]);
  81545. height = parseInt(match[1]);
  81546. if (width < 8 || width > 0x7fff) {
  81547. throw "HDR Bad header format, unsupported size";
  81548. }
  81549. lineIndex += (line.length + 1);
  81550. return {
  81551. height: height,
  81552. width: width,
  81553. dataPosition: lineIndex
  81554. };
  81555. };
  81556. /**
  81557. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81558. * This RGBE texture needs to store the information as a panorama.
  81559. *
  81560. * More information on this format are available here:
  81561. * https://en.wikipedia.org/wiki/RGBE_image_format
  81562. *
  81563. * @param buffer The binary file stored in an array buffer.
  81564. * @param size The expected size of the extracted cubemap.
  81565. * @return The Cube Map information.
  81566. */
  81567. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81568. var uint8array = new Uint8Array(buffer);
  81569. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81570. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81571. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81572. return cubeMapData;
  81573. };
  81574. /**
  81575. * Returns the pixels data extracted from an RGBE texture.
  81576. * This pixels will be stored left to right up to down in the R G B order in one array.
  81577. *
  81578. * More information on this format are available here:
  81579. * https://en.wikipedia.org/wiki/RGBE_image_format
  81580. *
  81581. * @param uint8array The binary file stored in an array buffer.
  81582. * @param hdrInfo The header information of the file.
  81583. * @return The pixels data in RGB right to left up to down order.
  81584. */
  81585. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81586. // Keep for multi format supports.
  81587. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81588. };
  81589. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81590. var num_scanlines = hdrInfo.height;
  81591. var scanline_width = hdrInfo.width;
  81592. var a, b, c, d, count;
  81593. var dataIndex = hdrInfo.dataPosition;
  81594. var index = 0, endIndex = 0, i = 0;
  81595. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81596. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81597. // 3 channels of 4 bytes per pixel in float.
  81598. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81599. var resultArray = new Float32Array(resultBuffer);
  81600. // read in each successive scanline
  81601. while (num_scanlines > 0) {
  81602. a = uint8array[dataIndex++];
  81603. b = uint8array[dataIndex++];
  81604. c = uint8array[dataIndex++];
  81605. d = uint8array[dataIndex++];
  81606. if (a != 2 || b != 2 || (c & 0x80)) {
  81607. // this file is not run length encoded
  81608. throw "HDR Bad header format, not RLE";
  81609. }
  81610. if (((c << 8) | d) != scanline_width) {
  81611. throw "HDR Bad header format, wrong scan line width";
  81612. }
  81613. index = 0;
  81614. // read each of the four channels for the scanline into the buffer
  81615. for (i = 0; i < 4; i++) {
  81616. endIndex = (i + 1) * scanline_width;
  81617. while (index < endIndex) {
  81618. a = uint8array[dataIndex++];
  81619. b = uint8array[dataIndex++];
  81620. if (a > 128) {
  81621. // a run of the same value
  81622. count = a - 128;
  81623. if ((count == 0) || (count > endIndex - index)) {
  81624. throw "HDR Bad Format, bad scanline data (run)";
  81625. }
  81626. while (count-- > 0) {
  81627. scanLineArray[index++] = b;
  81628. }
  81629. }
  81630. else {
  81631. // a non-run
  81632. count = a;
  81633. if ((count == 0) || (count > endIndex - index)) {
  81634. throw "HDR Bad Format, bad scanline data (non-run)";
  81635. }
  81636. scanLineArray[index++] = b;
  81637. if (--count > 0) {
  81638. for (var j = 0; j < count; j++) {
  81639. scanLineArray[index++] = uint8array[dataIndex++];
  81640. }
  81641. }
  81642. }
  81643. }
  81644. }
  81645. // now convert data from buffer into floats
  81646. for (i = 0; i < scanline_width; i++) {
  81647. a = scanLineArray[i];
  81648. b = scanLineArray[i + scanline_width];
  81649. c = scanLineArray[i + 2 * scanline_width];
  81650. d = scanLineArray[i + 3 * scanline_width];
  81651. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81652. }
  81653. num_scanlines--;
  81654. }
  81655. return resultArray;
  81656. };
  81657. return HDRTools;
  81658. }());
  81659. BABYLON.HDRTools = HDRTools;
  81660. })(BABYLON || (BABYLON = {}));
  81661. //# sourceMappingURL=babylon.hdr.js.map
  81662. var BABYLON;
  81663. (function (BABYLON) {
  81664. /**
  81665. * Sets of helpers addressing the serialization and deserialization of environment texture
  81666. * stored in a BabylonJS env file.
  81667. * Those files are usually stored as .env files.
  81668. */
  81669. var EnvironmentTextureTools = /** @class */ (function () {
  81670. function EnvironmentTextureTools() {
  81671. }
  81672. /**
  81673. * Gets the environment info from an env file.
  81674. * @param data The array buffer containing the .env bytes.
  81675. * @returns the environment file info (the json header) if successfully parsed.
  81676. */
  81677. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81678. var dataView = new DataView(data);
  81679. var pos = 0;
  81680. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81681. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81682. BABYLON.Tools.Error('Not a babylon environment map');
  81683. return null;
  81684. }
  81685. }
  81686. // Read json manifest - collect characters up to null terminator
  81687. var manifestString = '';
  81688. var charCode = 0x00;
  81689. while ((charCode = dataView.getUint8(pos++))) {
  81690. manifestString += String.fromCharCode(charCode);
  81691. }
  81692. var manifest = JSON.parse(manifestString);
  81693. if (manifest.specular) {
  81694. // Extend the header with the position of the payload.
  81695. manifest.specular.specularDataPosition = pos;
  81696. }
  81697. return manifest;
  81698. };
  81699. /**
  81700. * Creates an environment texture from a loaded cube texture.
  81701. * @param texture defines the cube texture to convert in env file
  81702. * @return a promise containing the environment data if succesfull.
  81703. */
  81704. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81705. var _this = this;
  81706. var internalTexture = texture.getInternalTexture();
  81707. if (!internalTexture) {
  81708. return Promise.reject("The cube texture is invalid.");
  81709. }
  81710. if (!texture._prefiltered) {
  81711. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81712. }
  81713. var engine = internalTexture.getEngine();
  81714. if (engine && engine.premultipliedAlpha) {
  81715. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81716. }
  81717. var canvas = engine.getRenderingCanvas();
  81718. if (!canvas) {
  81719. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81720. }
  81721. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81722. if (!engine.getCaps().textureFloatRender) {
  81723. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81724. if (!engine.getCaps().textureHalfFloatRender) {
  81725. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81726. }
  81727. }
  81728. var cubeWidth = internalTexture.width;
  81729. var hostingScene = new BABYLON.Scene(engine);
  81730. var specularTextures = {};
  81731. var promises = [];
  81732. // Read and collect all mipmaps data from the cube.
  81733. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81734. mipmapsCount = Math.round(mipmapsCount);
  81735. var _loop_1 = function (i) {
  81736. var faceWidth = Math.pow(2, mipmapsCount - i);
  81737. var _loop_2 = function (face) {
  81738. var data = texture.readPixels(face, i);
  81739. // Creates a temp texture with the face data.
  81740. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81741. // And rgbdEncode them.
  81742. var promise = new Promise(function (resolve, reject) {
  81743. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81744. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81745. rgbdPostProcess.onApply = function (effect) {
  81746. effect._bindTexture("textureSampler", tempTexture);
  81747. };
  81748. // As the process needs to happen on the main canvas, keep track of the current size
  81749. var currentW = engine.getRenderWidth();
  81750. var currentH = engine.getRenderHeight();
  81751. // Set the desired size for the texture
  81752. engine.setSize(faceWidth, faceWidth);
  81753. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81754. // Reading datas from WebGL
  81755. canvas.toBlob(function (blob) {
  81756. var fileReader = new FileReader();
  81757. fileReader.onload = function (event) {
  81758. var arrayBuffer = event.target.result;
  81759. specularTextures[i * 6 + face] = arrayBuffer;
  81760. resolve();
  81761. };
  81762. fileReader.readAsArrayBuffer(blob);
  81763. });
  81764. // Reapply the previous canvas size
  81765. engine.setSize(currentW, currentH);
  81766. });
  81767. });
  81768. promises.push(promise);
  81769. };
  81770. // All faces of the cube.
  81771. for (var face = 0; face < 6; face++) {
  81772. _loop_2(face);
  81773. }
  81774. };
  81775. for (var i = 0; i <= mipmapsCount; i++) {
  81776. _loop_1(i);
  81777. }
  81778. // Once all the textures haves been collected as RGBD stored in PNGs
  81779. return Promise.all(promises).then(function () {
  81780. // We can delete the hosting scene keeping track of all the creation objects
  81781. hostingScene.dispose();
  81782. // Creates the json header for the env texture
  81783. var info = {
  81784. version: 1,
  81785. width: cubeWidth,
  81786. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81787. specular: {
  81788. mipmaps: []
  81789. }
  81790. };
  81791. // Sets the specular image data information
  81792. var position = 0;
  81793. for (var i = 0; i <= mipmapsCount; i++) {
  81794. for (var face = 0; face < 6; face++) {
  81795. var byteLength = specularTextures[i * 6 + face].byteLength;
  81796. info.specular.mipmaps.push({
  81797. length: byteLength,
  81798. position: position
  81799. });
  81800. position += byteLength;
  81801. }
  81802. }
  81803. // Encode the JSON as an array buffer
  81804. var infoString = JSON.stringify(info);
  81805. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81806. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81807. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81808. infoView[i] = infoString.charCodeAt(i);
  81809. }
  81810. // Ends up with a null terminator for easier parsing
  81811. infoView[infoString.length] = 0x00;
  81812. // Computes the final required size and creates the storage
  81813. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81814. var finalBuffer = new ArrayBuffer(totalSize);
  81815. var finalBufferView = new Uint8Array(finalBuffer);
  81816. var dataView = new DataView(finalBuffer);
  81817. // Copy the magic bytes identifying the file in
  81818. var pos = 0;
  81819. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81820. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81821. }
  81822. // Add the json info
  81823. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81824. pos += infoBuffer.byteLength;
  81825. // Finally inserts the texture data
  81826. for (var i = 0; i <= mipmapsCount; i++) {
  81827. for (var face = 0; face < 6; face++) {
  81828. var dataBuffer = specularTextures[i * 6 + face];
  81829. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81830. pos += dataBuffer.byteLength;
  81831. }
  81832. }
  81833. // Voila
  81834. return finalBuffer;
  81835. });
  81836. };
  81837. /**
  81838. * Creates a JSON representation of the spherical data.
  81839. * @param texture defines the texture containing the polynomials
  81840. * @return the JSON representation of the spherical info
  81841. */
  81842. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81843. var polynmials = texture.sphericalPolynomial;
  81844. if (polynmials == null) {
  81845. return null;
  81846. }
  81847. return {
  81848. polynomials: true,
  81849. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81850. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81851. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81852. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81853. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81854. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81855. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81856. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81857. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81858. };
  81859. };
  81860. /**
  81861. * Uploads the texture info contained in the env file to te GPU.
  81862. * @param texture defines the internal texture to upload to
  81863. * @param arrayBuffer defines the buffer cotaining the data to load
  81864. * @param info defines the texture info retrieved through the GetEnvInfo method
  81865. * @returns a promise
  81866. */
  81867. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81868. if (info.version !== 1) {
  81869. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81870. }
  81871. var specularInfo = info.specular;
  81872. if (!specularInfo) {
  81873. // Nothing else parsed so far
  81874. return Promise.resolve();
  81875. }
  81876. // Double checks the enclosed info
  81877. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81878. mipmapsCount = Math.round(mipmapsCount) + 1;
  81879. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81880. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81881. }
  81882. // Gets everything ready.
  81883. var engine = texture.getEngine();
  81884. var expandTexture = false;
  81885. var generateNonLODTextures = false;
  81886. var rgbdPostProcess = null;
  81887. var cubeRtt = null;
  81888. var lodTextures = null;
  81889. var caps = engine.getCaps();
  81890. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81891. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81892. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81893. // Add extra process if texture lod is not supported
  81894. if (!caps.textureLOD) {
  81895. expandTexture = false;
  81896. generateNonLODTextures = true;
  81897. lodTextures = {};
  81898. }
  81899. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81900. else if (engine.webGLVersion < 2) {
  81901. expandTexture = false;
  81902. }
  81903. // If half float available we can uncompress the texture
  81904. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81905. expandTexture = true;
  81906. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81907. }
  81908. // If full float available we can uncompress the texture
  81909. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81910. expandTexture = true;
  81911. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81912. }
  81913. // Expand the texture if possible
  81914. if (expandTexture) {
  81915. // Simply run through the decode PP
  81916. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81917. texture._isRGBD = false;
  81918. texture.invertY = false;
  81919. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81920. generateDepthBuffer: false,
  81921. generateMipMaps: true,
  81922. generateStencilBuffer: false,
  81923. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81924. type: texture.type,
  81925. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81926. });
  81927. }
  81928. else {
  81929. texture._isRGBD = true;
  81930. texture.invertY = true;
  81931. // In case of missing support, applies the same patch than DDS files.
  81932. if (generateNonLODTextures) {
  81933. var mipSlices = 3;
  81934. var scale = texture._lodGenerationScale;
  81935. var offset = texture._lodGenerationOffset;
  81936. for (var i = 0; i < mipSlices; i++) {
  81937. //compute LOD from even spacing in smoothness (matching shader calculation)
  81938. var smoothness = i / (mipSlices - 1);
  81939. var roughness = 1 - smoothness;
  81940. var minLODIndex = offset; // roughness = 0
  81941. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81942. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81943. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81944. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81945. glTextureFromLod.isCube = true;
  81946. glTextureFromLod.invertY = true;
  81947. glTextureFromLod.generateMipMaps = false;
  81948. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81949. // Wrap in a base texture for easy binding.
  81950. var lodTexture = new BABYLON.BaseTexture(null);
  81951. lodTexture.isCube = true;
  81952. lodTexture._texture = glTextureFromLod;
  81953. lodTextures[mipmapIndex] = lodTexture;
  81954. switch (i) {
  81955. case 0:
  81956. texture._lodTextureLow = lodTexture;
  81957. break;
  81958. case 1:
  81959. texture._lodTextureMid = lodTexture;
  81960. break;
  81961. case 2:
  81962. texture._lodTextureHigh = lodTexture;
  81963. break;
  81964. }
  81965. }
  81966. }
  81967. }
  81968. var promises = [];
  81969. var _loop_3 = function (i) {
  81970. var _loop_4 = function (face) {
  81971. // Retrieves the face data
  81972. var imageData = specularInfo.mipmaps[i * 6 + face];
  81973. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81974. // Constructs an image element from bytes
  81975. var blob = new Blob([bytes], { type: 'image/png' });
  81976. var url = URL.createObjectURL(blob);
  81977. var image = new Image();
  81978. image.src = url;
  81979. // Enqueue promise to upload to the texture.
  81980. var promise = new Promise(function (resolve, reject) {
  81981. ;
  81982. image.onload = function () {
  81983. if (expandTexture) {
  81984. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81985. reject(message);
  81986. }, image);
  81987. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81988. // Uncompress the data to a RTT
  81989. rgbdPostProcess.onApply = function (effect) {
  81990. effect._bindTexture("textureSampler", tempTexture_1);
  81991. effect.setFloat2("scale", 1, 1);
  81992. };
  81993. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81994. // Cleanup
  81995. engine.restoreDefaultFramebuffer();
  81996. tempTexture_1.dispose();
  81997. window.URL.revokeObjectURL(url);
  81998. resolve();
  81999. });
  82000. }
  82001. else {
  82002. engine._uploadImageToTexture(texture, face, i, image);
  82003. // Upload the face to the none lod texture support
  82004. if (generateNonLODTextures) {
  82005. var lodTexture = lodTextures[i];
  82006. if (lodTexture) {
  82007. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82008. }
  82009. }
  82010. resolve();
  82011. }
  82012. };
  82013. image.onerror = function (error) {
  82014. reject(error);
  82015. };
  82016. });
  82017. promises.push(promise);
  82018. };
  82019. // All faces
  82020. for (var face = 0; face < 6; face++) {
  82021. _loop_4(face);
  82022. }
  82023. };
  82024. // All mipmaps
  82025. for (var i = 0; i < mipmapsCount; i++) {
  82026. _loop_3(i);
  82027. }
  82028. // Once all done, finishes the cleanup and return
  82029. return Promise.all(promises).then(function () {
  82030. // Relase temp RTT.
  82031. if (cubeRtt) {
  82032. engine._releaseFramebufferObjects(cubeRtt);
  82033. cubeRtt._swapAndDie(texture);
  82034. }
  82035. // Relase temp Post Process.
  82036. if (rgbdPostProcess) {
  82037. rgbdPostProcess.dispose();
  82038. }
  82039. // Flag internal texture as ready in case they are in use.
  82040. if (generateNonLODTextures) {
  82041. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82042. texture._lodTextureHigh._texture.isReady = true;
  82043. }
  82044. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82045. texture._lodTextureMid._texture.isReady = true;
  82046. }
  82047. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82048. texture._lodTextureLow._texture.isReady = true;
  82049. }
  82050. }
  82051. });
  82052. };
  82053. /**
  82054. * Uploads spherical polynomials information to the texture.
  82055. * @param texture defines the texture we are trying to upload the information to
  82056. * @param arrayBuffer defines the array buffer holding the data
  82057. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82058. */
  82059. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82060. if (info.version !== 1) {
  82061. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82062. }
  82063. var irradianceInfo = info.irradiance;
  82064. if (!irradianceInfo) {
  82065. return;
  82066. }
  82067. //harmonics now represent radiance
  82068. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82069. if (irradianceInfo.polynomials) {
  82070. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82071. }
  82072. else {
  82073. // convert From SH to SP.
  82074. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82075. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82076. }
  82077. };
  82078. /**
  82079. * Upload spherical polynomial coefficients to the texture
  82080. * @param polynmials Spherical polynmial coefficients (9)
  82081. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82082. */
  82083. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82084. outPolynomialCoefficents.x.x = polynmials.x[0];
  82085. outPolynomialCoefficents.x.y = polynmials.x[1];
  82086. outPolynomialCoefficents.x.z = polynmials.x[2];
  82087. outPolynomialCoefficents.y.x = polynmials.y[0];
  82088. outPolynomialCoefficents.y.y = polynmials.y[1];
  82089. outPolynomialCoefficents.y.z = polynmials.y[2];
  82090. outPolynomialCoefficents.z.x = polynmials.z[0];
  82091. outPolynomialCoefficents.z.y = polynmials.z[1];
  82092. outPolynomialCoefficents.z.z = polynmials.z[2];
  82093. //xx
  82094. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82095. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82096. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82097. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82098. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82099. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82100. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82101. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82102. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82103. //yz
  82104. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82105. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82106. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82107. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82108. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82109. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82110. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82111. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82112. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82113. };
  82114. /**
  82115. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82116. * L = (1/pi) * E * rho
  82117. *
  82118. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82119. * @param harmonics Spherical harmonic coefficients (9)
  82120. */
  82121. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82122. var scaleFactor = 1 / Math.PI;
  82123. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82124. // (The pixel shader must apply albedo after texture fetches, etc).
  82125. harmonics.l00[0] *= scaleFactor;
  82126. harmonics.l00[1] *= scaleFactor;
  82127. harmonics.l00[2] *= scaleFactor;
  82128. harmonics.l1_1[0] *= scaleFactor;
  82129. harmonics.l1_1[1] *= scaleFactor;
  82130. harmonics.l1_1[2] *= scaleFactor;
  82131. harmonics.l10[0] *= scaleFactor;
  82132. harmonics.l10[1] *= scaleFactor;
  82133. harmonics.l10[2] *= scaleFactor;
  82134. harmonics.l11[0] *= scaleFactor;
  82135. harmonics.l11[1] *= scaleFactor;
  82136. harmonics.l11[2] *= scaleFactor;
  82137. harmonics.l2_2[0] *= scaleFactor;
  82138. harmonics.l2_2[1] *= scaleFactor;
  82139. harmonics.l2_2[2] *= scaleFactor;
  82140. harmonics.l2_1[0] *= scaleFactor;
  82141. harmonics.l2_1[1] *= scaleFactor;
  82142. harmonics.l2_1[2] *= scaleFactor;
  82143. harmonics.l20[0] *= scaleFactor;
  82144. harmonics.l20[1] *= scaleFactor;
  82145. harmonics.l20[2] *= scaleFactor;
  82146. harmonics.l21[0] *= scaleFactor;
  82147. harmonics.l21[1] *= scaleFactor;
  82148. harmonics.l21[2] *= scaleFactor;
  82149. harmonics.l22[0] *= scaleFactor;
  82150. harmonics.l22[1] *= scaleFactor;
  82151. harmonics.l22[2] *= scaleFactor;
  82152. };
  82153. /**
  82154. * Convert spherical harmonics to spherical polynomial coefficients
  82155. * @param harmonics Spherical harmonic coefficients (9)
  82156. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82157. */
  82158. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82159. var rPi = 1 / Math.PI;
  82160. //x
  82161. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82162. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82163. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82164. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82165. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82166. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82167. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82168. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82169. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82170. //xx
  82171. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82172. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82173. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82174. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82175. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82176. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82177. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82178. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82179. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82180. //yz
  82181. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82182. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82183. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82184. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82185. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82186. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82187. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82188. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82189. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82190. };
  82191. /**
  82192. * Magic number identifying the env file.
  82193. */
  82194. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82195. return EnvironmentTextureTools;
  82196. }());
  82197. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82198. })(BABYLON || (BABYLON = {}));
  82199. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82200. var BABYLON;
  82201. (function (BABYLON) {
  82202. /**
  82203. * This represents a texture coming from an HDR input.
  82204. *
  82205. * The only supported format is currently panorama picture stored in RGBE format.
  82206. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82207. */
  82208. var HDRCubeTexture = /** @class */ (function (_super) {
  82209. __extends(HDRCubeTexture, _super);
  82210. /**
  82211. * Instantiates an HDRTexture from the following parameters.
  82212. *
  82213. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82214. * @param scene The scene the texture will be used in
  82215. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82216. * @param noMipmap Forces to not generate the mipmap if true
  82217. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82218. * @param gammaSpace 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)
  82219. * @param reserved Reserved flag for internal use.
  82220. */
  82221. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82222. if (noMipmap === void 0) { noMipmap = false; }
  82223. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82224. if (gammaSpace === void 0) { gammaSpace = false; }
  82225. if (reserved === void 0) { reserved = false; }
  82226. if (onLoad === void 0) { onLoad = null; }
  82227. if (onError === void 0) { onError = null; }
  82228. var _this = _super.call(this, scene) || this;
  82229. _this._generateHarmonics = true;
  82230. _this._onLoad = null;
  82231. _this._onError = null;
  82232. /**
  82233. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82234. */
  82235. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82236. _this._isBlocking = true;
  82237. _this._rotationY = 0;
  82238. /**
  82239. * Gets or sets the center of the bounding box associated with the cube texture
  82240. * It must define where the camera used to render the texture was set
  82241. */
  82242. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82243. if (!url) {
  82244. return _this;
  82245. }
  82246. _this.name = url;
  82247. _this.url = url;
  82248. _this.hasAlpha = false;
  82249. _this.isCube = true;
  82250. _this._textureMatrix = BABYLON.Matrix.Identity();
  82251. _this._onLoad = onLoad;
  82252. _this._onError = onError;
  82253. _this.gammaSpace = gammaSpace;
  82254. _this._noMipmap = noMipmap;
  82255. _this._size = size;
  82256. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82257. if (!_this._texture) {
  82258. if (!scene.useDelayedTextureLoading) {
  82259. _this.loadTexture();
  82260. }
  82261. else {
  82262. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82263. }
  82264. }
  82265. return _this;
  82266. }
  82267. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82268. /**
  82269. * Gets wether or not the texture is blocking during loading.
  82270. */
  82271. get: function () {
  82272. return this._isBlocking;
  82273. },
  82274. /**
  82275. * Sets wether or not the texture is blocking during loading.
  82276. */
  82277. set: function (value) {
  82278. this._isBlocking = value;
  82279. },
  82280. enumerable: true,
  82281. configurable: true
  82282. });
  82283. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82284. /**
  82285. * Gets texture matrix rotation angle around Y axis radians.
  82286. */
  82287. get: function () {
  82288. return this._rotationY;
  82289. },
  82290. /**
  82291. * Sets texture matrix rotation angle around Y axis in radians.
  82292. */
  82293. set: function (value) {
  82294. this._rotationY = value;
  82295. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82296. },
  82297. enumerable: true,
  82298. configurable: true
  82299. });
  82300. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82301. get: function () {
  82302. return this._boundingBoxSize;
  82303. },
  82304. /**
  82305. * Gets or sets the size of the bounding box associated with the cube texture
  82306. * When defined, the cubemap will switch to local mode
  82307. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82308. * @example https://www.babylonjs-playground.com/#RNASML
  82309. */
  82310. set: function (value) {
  82311. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82312. return;
  82313. }
  82314. this._boundingBoxSize = value;
  82315. var scene = this.getScene();
  82316. if (scene) {
  82317. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82318. }
  82319. },
  82320. enumerable: true,
  82321. configurable: true
  82322. });
  82323. /**
  82324. * Occurs when the file is raw .hdr file.
  82325. */
  82326. HDRCubeTexture.prototype.loadTexture = function () {
  82327. var _this = this;
  82328. var callback = function (buffer) {
  82329. _this.lodGenerationOffset = 0.0;
  82330. _this.lodGenerationScale = 0.8;
  82331. var scene = _this.getScene();
  82332. if (!scene) {
  82333. return null;
  82334. }
  82335. // Extract the raw linear data.
  82336. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82337. // Generate harmonics if needed.
  82338. if (_this._generateHarmonics) {
  82339. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82340. _this.sphericalPolynomial = sphericalPolynomial;
  82341. }
  82342. var results = [];
  82343. var byteArray = null;
  82344. // Push each faces.
  82345. for (var j = 0; j < 6; j++) {
  82346. // Create uintarray fallback.
  82347. if (!scene.getEngine().getCaps().textureFloat) {
  82348. // 3 channels of 1 bytes per pixel in bytes.
  82349. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82350. byteArray = new Uint8Array(byteBuffer);
  82351. }
  82352. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82353. // If special cases.
  82354. if (_this.gammaSpace || byteArray) {
  82355. for (var i = 0; i < _this._size * _this._size; i++) {
  82356. // Put in gamma space if requested.
  82357. if (_this.gammaSpace) {
  82358. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82359. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82360. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82361. }
  82362. // Convert to int texture for fallback.
  82363. if (byteArray) {
  82364. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82365. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82366. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82367. // May use luminance instead if the result is not accurate.
  82368. var max = Math.max(Math.max(r, g), b);
  82369. if (max > 255) {
  82370. var scale = 255 / max;
  82371. r *= scale;
  82372. g *= scale;
  82373. b *= scale;
  82374. }
  82375. byteArray[(i * 3) + 0] = r;
  82376. byteArray[(i * 3) + 1] = g;
  82377. byteArray[(i * 3) + 2] = b;
  82378. }
  82379. }
  82380. }
  82381. if (byteArray) {
  82382. results.push(byteArray);
  82383. }
  82384. else {
  82385. results.push(dataFace);
  82386. }
  82387. }
  82388. return results;
  82389. };
  82390. var scene = this.getScene();
  82391. if (scene) {
  82392. 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, null, this._onLoad, this._onError);
  82393. }
  82394. };
  82395. HDRCubeTexture.prototype.clone = function () {
  82396. var scene = this.getScene();
  82397. if (!scene) {
  82398. return this;
  82399. }
  82400. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82401. // Base texture
  82402. newTexture.level = this.level;
  82403. newTexture.wrapU = this.wrapU;
  82404. newTexture.wrapV = this.wrapV;
  82405. newTexture.coordinatesIndex = this.coordinatesIndex;
  82406. newTexture.coordinatesMode = this.coordinatesMode;
  82407. return newTexture;
  82408. };
  82409. // Methods
  82410. HDRCubeTexture.prototype.delayLoad = function () {
  82411. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82412. return;
  82413. }
  82414. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82415. this._texture = this._getFromCache(this.url, this._noMipmap);
  82416. if (!this._texture) {
  82417. this.loadTexture();
  82418. }
  82419. };
  82420. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82421. return this._textureMatrix;
  82422. };
  82423. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82424. this._textureMatrix = value;
  82425. };
  82426. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82427. var texture = null;
  82428. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82429. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82430. texture.name = parsedTexture.name;
  82431. texture.hasAlpha = parsedTexture.hasAlpha;
  82432. texture.level = parsedTexture.level;
  82433. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82434. texture.isBlocking = parsedTexture.isBlocking;
  82435. }
  82436. if (texture) {
  82437. if (parsedTexture.boundingBoxPosition) {
  82438. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82439. }
  82440. if (parsedTexture.boundingBoxSize) {
  82441. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82442. }
  82443. if (parsedTexture.rotationY) {
  82444. texture.rotationY = parsedTexture.rotationY;
  82445. }
  82446. }
  82447. return texture;
  82448. };
  82449. HDRCubeTexture.prototype.serialize = function () {
  82450. if (!this.name) {
  82451. return null;
  82452. }
  82453. var serializationObject = {};
  82454. serializationObject.name = this.name;
  82455. serializationObject.hasAlpha = this.hasAlpha;
  82456. serializationObject.isCube = true;
  82457. serializationObject.level = this.level;
  82458. serializationObject.size = this._size;
  82459. serializationObject.coordinatesMode = this.coordinatesMode;
  82460. serializationObject.useInGammaSpace = this.gammaSpace;
  82461. serializationObject.generateHarmonics = this._generateHarmonics;
  82462. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82463. serializationObject.noMipmap = this._noMipmap;
  82464. serializationObject.isBlocking = this._isBlocking;
  82465. serializationObject.rotationY = this._rotationY;
  82466. return serializationObject;
  82467. };
  82468. HDRCubeTexture._facesMapping = [
  82469. "right",
  82470. "left",
  82471. "up",
  82472. "down",
  82473. "front",
  82474. "back"
  82475. ];
  82476. return HDRCubeTexture;
  82477. }(BABYLON.BaseTexture));
  82478. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82479. })(BABYLON || (BABYLON = {}));
  82480. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82481. var BABYLON;
  82482. (function (BABYLON) {
  82483. var IndexedVector2 = /** @class */ (function (_super) {
  82484. __extends(IndexedVector2, _super);
  82485. function IndexedVector2(original, index) {
  82486. var _this = _super.call(this, original.x, original.y) || this;
  82487. _this.index = index;
  82488. return _this;
  82489. }
  82490. return IndexedVector2;
  82491. }(BABYLON.Vector2));
  82492. var PolygonPoints = /** @class */ (function () {
  82493. function PolygonPoints() {
  82494. this.elements = new Array();
  82495. }
  82496. PolygonPoints.prototype.add = function (originalPoints) {
  82497. var _this = this;
  82498. var result = new Array();
  82499. originalPoints.forEach(function (point) {
  82500. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82501. var newPoint = new IndexedVector2(point, _this.elements.length);
  82502. result.push(newPoint);
  82503. _this.elements.push(newPoint);
  82504. }
  82505. });
  82506. return result;
  82507. };
  82508. PolygonPoints.prototype.computeBounds = function () {
  82509. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82510. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82511. this.elements.forEach(function (point) {
  82512. // x
  82513. if (point.x < lmin.x) {
  82514. lmin.x = point.x;
  82515. }
  82516. else if (point.x > lmax.x) {
  82517. lmax.x = point.x;
  82518. }
  82519. // y
  82520. if (point.y < lmin.y) {
  82521. lmin.y = point.y;
  82522. }
  82523. else if (point.y > lmax.y) {
  82524. lmax.y = point.y;
  82525. }
  82526. });
  82527. return {
  82528. min: lmin,
  82529. max: lmax,
  82530. width: lmax.x - lmin.x,
  82531. height: lmax.y - lmin.y
  82532. };
  82533. };
  82534. return PolygonPoints;
  82535. }());
  82536. var Polygon = /** @class */ (function () {
  82537. function Polygon() {
  82538. }
  82539. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82540. return [
  82541. new BABYLON.Vector2(xmin, ymin),
  82542. new BABYLON.Vector2(xmax, ymin),
  82543. new BABYLON.Vector2(xmax, ymax),
  82544. new BABYLON.Vector2(xmin, ymax)
  82545. ];
  82546. };
  82547. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82548. if (cx === void 0) { cx = 0; }
  82549. if (cy === void 0) { cy = 0; }
  82550. if (numberOfSides === void 0) { numberOfSides = 32; }
  82551. var result = new Array();
  82552. var angle = 0;
  82553. var increment = (Math.PI * 2) / numberOfSides;
  82554. for (var i = 0; i < numberOfSides; i++) {
  82555. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82556. angle -= increment;
  82557. }
  82558. return result;
  82559. };
  82560. Polygon.Parse = function (input) {
  82561. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82562. var i, result = [];
  82563. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82564. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82565. }
  82566. return result;
  82567. };
  82568. Polygon.StartingAt = function (x, y) {
  82569. return BABYLON.Path2.StartingAt(x, y);
  82570. };
  82571. return Polygon;
  82572. }());
  82573. BABYLON.Polygon = Polygon;
  82574. var PolygonMeshBuilder = /** @class */ (function () {
  82575. function PolygonMeshBuilder(name, contours, scene) {
  82576. this._points = new PolygonPoints();
  82577. this._outlinepoints = new PolygonPoints();
  82578. this._holes = new Array();
  82579. this._epoints = new Array();
  82580. this._eholes = new Array();
  82581. this._name = name;
  82582. this._scene = scene;
  82583. var points;
  82584. if (contours instanceof BABYLON.Path2) {
  82585. points = contours.getPoints();
  82586. }
  82587. else {
  82588. points = contours;
  82589. }
  82590. this._addToepoint(points);
  82591. this._points.add(points);
  82592. this._outlinepoints.add(points);
  82593. if (typeof earcut === 'undefined') {
  82594. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82595. }
  82596. }
  82597. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82598. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82599. var p = points_1[_i];
  82600. this._epoints.push(p.x, p.y);
  82601. }
  82602. };
  82603. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82604. this._points.add(hole);
  82605. var holepoints = new PolygonPoints();
  82606. holepoints.add(hole);
  82607. this._holes.push(holepoints);
  82608. this._eholes.push(this._epoints.length / 2);
  82609. this._addToepoint(hole);
  82610. return this;
  82611. };
  82612. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82613. var _this = this;
  82614. if (updatable === void 0) { updatable = false; }
  82615. if (depth === void 0) { depth = 0; }
  82616. var result = new BABYLON.Mesh(this._name, this._scene);
  82617. var normals = new Array();
  82618. var positions = new Array();
  82619. var uvs = new Array();
  82620. var bounds = this._points.computeBounds();
  82621. this._points.elements.forEach(function (p) {
  82622. normals.push(0, 1.0, 0);
  82623. positions.push(p.x, 0, p.y);
  82624. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82625. });
  82626. var indices = new Array();
  82627. var res = earcut(this._epoints, this._eholes, 2);
  82628. for (var i = 0; i < res.length; i++) {
  82629. indices.push(res[i]);
  82630. }
  82631. if (depth > 0) {
  82632. var positionscount = (positions.length / 3); //get the current pointcount
  82633. this._points.elements.forEach(function (p) {
  82634. normals.push(0, -1.0, 0);
  82635. positions.push(p.x, -depth, p.y);
  82636. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82637. });
  82638. var totalCount = indices.length;
  82639. for (var i = 0; i < totalCount; i += 3) {
  82640. var i0 = indices[i + 0];
  82641. var i1 = indices[i + 1];
  82642. var i2 = indices[i + 2];
  82643. indices.push(i2 + positionscount);
  82644. indices.push(i1 + positionscount);
  82645. indices.push(i0 + positionscount);
  82646. }
  82647. //Add the sides
  82648. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82649. this._holes.forEach(function (hole) {
  82650. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82651. });
  82652. }
  82653. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82654. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82655. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82656. result.setIndices(indices);
  82657. return result;
  82658. };
  82659. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82660. var StartIndex = positions.length / 3;
  82661. var ulength = 0;
  82662. for (var i = 0; i < points.elements.length; i++) {
  82663. var p = points.elements[i];
  82664. var p1;
  82665. if ((i + 1) > points.elements.length - 1) {
  82666. p1 = points.elements[0];
  82667. }
  82668. else {
  82669. p1 = points.elements[i + 1];
  82670. }
  82671. positions.push(p.x, 0, p.y);
  82672. positions.push(p.x, -depth, p.y);
  82673. positions.push(p1.x, 0, p1.y);
  82674. positions.push(p1.x, -depth, p1.y);
  82675. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82676. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82677. var v3 = v2.subtract(v1);
  82678. var v4 = new BABYLON.Vector3(0, 1, 0);
  82679. var vn = BABYLON.Vector3.Cross(v3, v4);
  82680. vn = vn.normalize();
  82681. uvs.push(ulength / bounds.width, 0);
  82682. uvs.push(ulength / bounds.width, 1);
  82683. ulength += v3.length();
  82684. uvs.push((ulength / bounds.width), 0);
  82685. uvs.push((ulength / bounds.width), 1);
  82686. if (!flip) {
  82687. normals.push(-vn.x, -vn.y, -vn.z);
  82688. normals.push(-vn.x, -vn.y, -vn.z);
  82689. normals.push(-vn.x, -vn.y, -vn.z);
  82690. normals.push(-vn.x, -vn.y, -vn.z);
  82691. indices.push(StartIndex);
  82692. indices.push(StartIndex + 1);
  82693. indices.push(StartIndex + 2);
  82694. indices.push(StartIndex + 1);
  82695. indices.push(StartIndex + 3);
  82696. indices.push(StartIndex + 2);
  82697. }
  82698. else {
  82699. normals.push(vn.x, vn.y, vn.z);
  82700. normals.push(vn.x, vn.y, vn.z);
  82701. normals.push(vn.x, vn.y, vn.z);
  82702. normals.push(vn.x, vn.y, vn.z);
  82703. indices.push(StartIndex);
  82704. indices.push(StartIndex + 2);
  82705. indices.push(StartIndex + 1);
  82706. indices.push(StartIndex + 1);
  82707. indices.push(StartIndex + 2);
  82708. indices.push(StartIndex + 3);
  82709. }
  82710. StartIndex += 4;
  82711. }
  82712. ;
  82713. };
  82714. return PolygonMeshBuilder;
  82715. }());
  82716. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82717. })(BABYLON || (BABYLON = {}));
  82718. //# sourceMappingURL=babylon.polygonMesh.js.map
  82719. var BABYLON;
  82720. (function (BABYLON) {
  82721. // Unique ID when we import meshes from Babylon to CSG
  82722. var currentCSGMeshId = 0;
  82723. // # class Vertex
  82724. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82725. // one to provide additional features like texture coordinates and vertex
  82726. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82727. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82728. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82729. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82730. // is not used anywhere else.
  82731. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82732. var Vertex = /** @class */ (function () {
  82733. function Vertex(pos, normal, uv) {
  82734. this.pos = pos;
  82735. this.normal = normal;
  82736. this.uv = uv;
  82737. }
  82738. Vertex.prototype.clone = function () {
  82739. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82740. };
  82741. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82742. // orientation of a polygon is flipped.
  82743. Vertex.prototype.flip = function () {
  82744. this.normal = this.normal.scale(-1);
  82745. };
  82746. // Create a new vertex between this vertex and `other` by linearly
  82747. // interpolating all properties using a parameter of `t`. Subclasses should
  82748. // override this to interpolate additional properties.
  82749. Vertex.prototype.interpolate = function (other, t) {
  82750. 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));
  82751. };
  82752. return Vertex;
  82753. }());
  82754. // # class Plane
  82755. // Represents a plane in 3D space.
  82756. var Plane = /** @class */ (function () {
  82757. function Plane(normal, w) {
  82758. this.normal = normal;
  82759. this.w = w;
  82760. }
  82761. Plane.FromPoints = function (a, b, c) {
  82762. var v0 = c.subtract(a);
  82763. var v1 = b.subtract(a);
  82764. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82765. return null;
  82766. }
  82767. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82768. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82769. };
  82770. Plane.prototype.clone = function () {
  82771. return new Plane(this.normal.clone(), this.w);
  82772. };
  82773. Plane.prototype.flip = function () {
  82774. this.normal.scaleInPlace(-1);
  82775. this.w = -this.w;
  82776. };
  82777. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82778. // fragments in the appropriate lists. Coplanar polygons go into either
  82779. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82780. // respect to this plane. Polygons in front or in back of this plane go into
  82781. // either `front` or `back`.
  82782. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82783. var COPLANAR = 0;
  82784. var FRONT = 1;
  82785. var BACK = 2;
  82786. var SPANNING = 3;
  82787. // Classify each point as well as the entire polygon into one of the above
  82788. // four classes.
  82789. var polygonType = 0;
  82790. var types = [];
  82791. var i;
  82792. var t;
  82793. for (i = 0; i < polygon.vertices.length; i++) {
  82794. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82795. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82796. polygonType |= type;
  82797. types.push(type);
  82798. }
  82799. // Put the polygon in the correct list, splitting it when necessary.
  82800. switch (polygonType) {
  82801. case COPLANAR:
  82802. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82803. break;
  82804. case FRONT:
  82805. front.push(polygon);
  82806. break;
  82807. case BACK:
  82808. back.push(polygon);
  82809. break;
  82810. case SPANNING:
  82811. var f = [], b = [];
  82812. for (i = 0; i < polygon.vertices.length; i++) {
  82813. var j = (i + 1) % polygon.vertices.length;
  82814. var ti = types[i], tj = types[j];
  82815. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82816. if (ti !== BACK)
  82817. f.push(vi);
  82818. if (ti !== FRONT)
  82819. b.push(ti !== BACK ? vi.clone() : vi);
  82820. if ((ti | tj) === SPANNING) {
  82821. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82822. var v = vi.interpolate(vj, t);
  82823. f.push(v);
  82824. b.push(v.clone());
  82825. }
  82826. }
  82827. var poly;
  82828. if (f.length >= 3) {
  82829. poly = new Polygon(f, polygon.shared);
  82830. if (poly.plane)
  82831. front.push(poly);
  82832. }
  82833. if (b.length >= 3) {
  82834. poly = new Polygon(b, polygon.shared);
  82835. if (poly.plane)
  82836. back.push(poly);
  82837. }
  82838. break;
  82839. }
  82840. };
  82841. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82842. // point is on the plane.
  82843. Plane.EPSILON = 1e-5;
  82844. return Plane;
  82845. }());
  82846. // # class Polygon
  82847. // Represents a convex polygon. The vertices used to initialize a polygon must
  82848. // be coplanar and form a convex loop.
  82849. //
  82850. // Each convex polygon has a `shared` property, which is shared between all
  82851. // polygons that are clones of each other or were split from the same polygon.
  82852. // This can be used to define per-polygon properties (such as surface color).
  82853. var Polygon = /** @class */ (function () {
  82854. function Polygon(vertices, shared) {
  82855. this.vertices = vertices;
  82856. this.shared = shared;
  82857. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82858. }
  82859. Polygon.prototype.clone = function () {
  82860. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82861. return new Polygon(vertices, this.shared);
  82862. };
  82863. Polygon.prototype.flip = function () {
  82864. this.vertices.reverse().map(function (v) { v.flip(); });
  82865. this.plane.flip();
  82866. };
  82867. return Polygon;
  82868. }());
  82869. // # class Node
  82870. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82871. // by picking a polygon to split along. That polygon (and all other coplanar
  82872. // polygons) are added directly to that node and the other polygons are added to
  82873. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82874. // no distinction between internal and leaf nodes.
  82875. var Node = /** @class */ (function () {
  82876. function Node(polygons) {
  82877. this.plane = null;
  82878. this.front = null;
  82879. this.back = null;
  82880. this.polygons = new Array();
  82881. if (polygons) {
  82882. this.build(polygons);
  82883. }
  82884. }
  82885. Node.prototype.clone = function () {
  82886. var node = new Node();
  82887. node.plane = this.plane && this.plane.clone();
  82888. node.front = this.front && this.front.clone();
  82889. node.back = this.back && this.back.clone();
  82890. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82891. return node;
  82892. };
  82893. // Convert solid space to empty space and empty space to solid space.
  82894. Node.prototype.invert = function () {
  82895. for (var i = 0; i < this.polygons.length; i++) {
  82896. this.polygons[i].flip();
  82897. }
  82898. if (this.plane) {
  82899. this.plane.flip();
  82900. }
  82901. if (this.front) {
  82902. this.front.invert();
  82903. }
  82904. if (this.back) {
  82905. this.back.invert();
  82906. }
  82907. var temp = this.front;
  82908. this.front = this.back;
  82909. this.back = temp;
  82910. };
  82911. // Recursively remove all polygons in `polygons` that are inside this BSP
  82912. // tree.
  82913. Node.prototype.clipPolygons = function (polygons) {
  82914. if (!this.plane)
  82915. return polygons.slice();
  82916. var front = new Array(), back = new Array();
  82917. for (var i = 0; i < polygons.length; i++) {
  82918. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82919. }
  82920. if (this.front) {
  82921. front = this.front.clipPolygons(front);
  82922. }
  82923. if (this.back) {
  82924. back = this.back.clipPolygons(back);
  82925. }
  82926. else {
  82927. back = [];
  82928. }
  82929. return front.concat(back);
  82930. };
  82931. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82932. // `bsp`.
  82933. Node.prototype.clipTo = function (bsp) {
  82934. this.polygons = bsp.clipPolygons(this.polygons);
  82935. if (this.front)
  82936. this.front.clipTo(bsp);
  82937. if (this.back)
  82938. this.back.clipTo(bsp);
  82939. };
  82940. // Return a list of all polygons in this BSP tree.
  82941. Node.prototype.allPolygons = function () {
  82942. var polygons = this.polygons.slice();
  82943. if (this.front)
  82944. polygons = polygons.concat(this.front.allPolygons());
  82945. if (this.back)
  82946. polygons = polygons.concat(this.back.allPolygons());
  82947. return polygons;
  82948. };
  82949. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82950. // new polygons are filtered down to the bottom of the tree and become new
  82951. // nodes there. Each set of polygons is partitioned using the first polygon
  82952. // (no heuristic is used to pick a good split).
  82953. Node.prototype.build = function (polygons) {
  82954. if (!polygons.length)
  82955. return;
  82956. if (!this.plane)
  82957. this.plane = polygons[0].plane.clone();
  82958. var front = new Array(), back = new Array();
  82959. for (var i = 0; i < polygons.length; i++) {
  82960. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82961. }
  82962. if (front.length) {
  82963. if (!this.front)
  82964. this.front = new Node();
  82965. this.front.build(front);
  82966. }
  82967. if (back.length) {
  82968. if (!this.back)
  82969. this.back = new Node();
  82970. this.back.build(back);
  82971. }
  82972. };
  82973. return Node;
  82974. }());
  82975. var CSG = /** @class */ (function () {
  82976. function CSG() {
  82977. this.polygons = new Array();
  82978. }
  82979. // Convert BABYLON.Mesh to BABYLON.CSG
  82980. CSG.FromMesh = function (mesh) {
  82981. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82982. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82983. if (mesh instanceof BABYLON.Mesh) {
  82984. mesh.computeWorldMatrix(true);
  82985. matrix = mesh.getWorldMatrix();
  82986. meshPosition = mesh.position.clone();
  82987. meshRotation = mesh.rotation.clone();
  82988. if (mesh.rotationQuaternion) {
  82989. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82990. }
  82991. meshScaling = mesh.scaling.clone();
  82992. }
  82993. else {
  82994. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82995. }
  82996. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82997. var subMeshes = mesh.subMeshes;
  82998. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82999. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83000. vertices = [];
  83001. for (var j = 0; j < 3; j++) {
  83002. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83003. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83004. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83005. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83006. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83007. vertex = new Vertex(position, normal, uv);
  83008. vertices.push(vertex);
  83009. }
  83010. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83011. // To handle the case of degenerated triangle
  83012. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83013. if (polygon.plane)
  83014. polygons.push(polygon);
  83015. }
  83016. }
  83017. var csg = CSG.FromPolygons(polygons);
  83018. csg.matrix = matrix;
  83019. csg.position = meshPosition;
  83020. csg.rotation = meshRotation;
  83021. csg.scaling = meshScaling;
  83022. csg.rotationQuaternion = meshRotationQuaternion;
  83023. currentCSGMeshId++;
  83024. return csg;
  83025. };
  83026. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83027. CSG.FromPolygons = function (polygons) {
  83028. var csg = new CSG();
  83029. csg.polygons = polygons;
  83030. return csg;
  83031. };
  83032. CSG.prototype.clone = function () {
  83033. var csg = new CSG();
  83034. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83035. csg.copyTransformAttributes(this);
  83036. return csg;
  83037. };
  83038. CSG.prototype.union = function (csg) {
  83039. var a = new Node(this.clone().polygons);
  83040. var b = new Node(csg.clone().polygons);
  83041. a.clipTo(b);
  83042. b.clipTo(a);
  83043. b.invert();
  83044. b.clipTo(a);
  83045. b.invert();
  83046. a.build(b.allPolygons());
  83047. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83048. };
  83049. CSG.prototype.unionInPlace = function (csg) {
  83050. var a = new Node(this.polygons);
  83051. var b = new Node(csg.polygons);
  83052. a.clipTo(b);
  83053. b.clipTo(a);
  83054. b.invert();
  83055. b.clipTo(a);
  83056. b.invert();
  83057. a.build(b.allPolygons());
  83058. this.polygons = a.allPolygons();
  83059. };
  83060. CSG.prototype.subtract = function (csg) {
  83061. var a = new Node(this.clone().polygons);
  83062. var b = new Node(csg.clone().polygons);
  83063. a.invert();
  83064. a.clipTo(b);
  83065. b.clipTo(a);
  83066. b.invert();
  83067. b.clipTo(a);
  83068. b.invert();
  83069. a.build(b.allPolygons());
  83070. a.invert();
  83071. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83072. };
  83073. CSG.prototype.subtractInPlace = function (csg) {
  83074. var a = new Node(this.polygons);
  83075. var b = new Node(csg.polygons);
  83076. a.invert();
  83077. a.clipTo(b);
  83078. b.clipTo(a);
  83079. b.invert();
  83080. b.clipTo(a);
  83081. b.invert();
  83082. a.build(b.allPolygons());
  83083. a.invert();
  83084. this.polygons = a.allPolygons();
  83085. };
  83086. CSG.prototype.intersect = function (csg) {
  83087. var a = new Node(this.clone().polygons);
  83088. var b = new Node(csg.clone().polygons);
  83089. a.invert();
  83090. b.clipTo(a);
  83091. b.invert();
  83092. a.clipTo(b);
  83093. b.clipTo(a);
  83094. a.build(b.allPolygons());
  83095. a.invert();
  83096. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83097. };
  83098. CSG.prototype.intersectInPlace = function (csg) {
  83099. var a = new Node(this.polygons);
  83100. var b = new Node(csg.polygons);
  83101. a.invert();
  83102. b.clipTo(a);
  83103. b.invert();
  83104. a.clipTo(b);
  83105. b.clipTo(a);
  83106. a.build(b.allPolygons());
  83107. a.invert();
  83108. this.polygons = a.allPolygons();
  83109. };
  83110. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83111. // not modified.
  83112. CSG.prototype.inverse = function () {
  83113. var csg = this.clone();
  83114. csg.inverseInPlace();
  83115. return csg;
  83116. };
  83117. CSG.prototype.inverseInPlace = function () {
  83118. this.polygons.map(function (p) { p.flip(); });
  83119. };
  83120. // This is used to keep meshes transformations so they can be restored
  83121. // when we build back a Babylon Mesh
  83122. // NB : All CSG operations are performed in world coordinates
  83123. CSG.prototype.copyTransformAttributes = function (csg) {
  83124. this.matrix = csg.matrix;
  83125. this.position = csg.position;
  83126. this.rotation = csg.rotation;
  83127. this.scaling = csg.scaling;
  83128. this.rotationQuaternion = csg.rotationQuaternion;
  83129. return this;
  83130. };
  83131. // Build Raw mesh from CSG
  83132. // Coordinates here are in world space
  83133. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83134. var matrix = this.matrix.clone();
  83135. matrix.invert();
  83136. 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;
  83137. if (keepSubMeshes) {
  83138. // Sort Polygons, since subMeshes are indices range
  83139. polygons.sort(function (a, b) {
  83140. if (a.shared.meshId === b.shared.meshId) {
  83141. return a.shared.subMeshId - b.shared.subMeshId;
  83142. }
  83143. else {
  83144. return a.shared.meshId - b.shared.meshId;
  83145. }
  83146. });
  83147. }
  83148. for (var i = 0, il = polygons.length; i < il; i++) {
  83149. polygon = polygons[i];
  83150. // Building SubMeshes
  83151. if (!subMesh_dict[polygon.shared.meshId]) {
  83152. subMesh_dict[polygon.shared.meshId] = {};
  83153. }
  83154. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83155. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83156. indexStart: +Infinity,
  83157. indexEnd: -Infinity,
  83158. materialIndex: polygon.shared.materialIndex
  83159. };
  83160. }
  83161. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83162. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83163. polygonIndices[0] = 0;
  83164. polygonIndices[1] = j - 1;
  83165. polygonIndices[2] = j;
  83166. for (var k = 0; k < 3; k++) {
  83167. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83168. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83169. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83170. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83171. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83172. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83173. // Check if 2 points can be merged
  83174. if (!(typeof vertex_idx !== 'undefined' &&
  83175. normals[vertex_idx * 3] === localNormal.x &&
  83176. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83177. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83178. uvs[vertex_idx * 2] === uv.x &&
  83179. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83180. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83181. uvs.push(uv.x, uv.y);
  83182. normals.push(normal.x, normal.y, normal.z);
  83183. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83184. }
  83185. indices.push(vertex_idx);
  83186. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83187. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83188. currentIndex++;
  83189. }
  83190. }
  83191. }
  83192. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83193. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83194. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83195. mesh.setIndices(indices, null);
  83196. if (keepSubMeshes) {
  83197. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83198. var materialIndexOffset = 0, materialMaxIndex;
  83199. mesh.subMeshes = new Array();
  83200. for (var m in subMesh_dict) {
  83201. materialMaxIndex = -1;
  83202. for (var sm in subMesh_dict[m]) {
  83203. subMesh_obj = subMesh_dict[m][sm];
  83204. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83205. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83206. }
  83207. materialIndexOffset += ++materialMaxIndex;
  83208. }
  83209. }
  83210. return mesh;
  83211. };
  83212. // Build Mesh from CSG taking material and transforms into account
  83213. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83214. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83215. mesh.material = material;
  83216. mesh.position.copyFrom(this.position);
  83217. mesh.rotation.copyFrom(this.rotation);
  83218. if (this.rotationQuaternion) {
  83219. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83220. }
  83221. mesh.scaling.copyFrom(this.scaling);
  83222. mesh.computeWorldMatrix(true);
  83223. return mesh;
  83224. };
  83225. return CSG;
  83226. }());
  83227. BABYLON.CSG = CSG;
  83228. })(BABYLON || (BABYLON = {}));
  83229. //# sourceMappingURL=babylon.csg.js.map
  83230. var BABYLON;
  83231. (function (BABYLON) {
  83232. var LensFlare = /** @class */ (function () {
  83233. function LensFlare(size, position, color, imgUrl, system) {
  83234. this.size = size;
  83235. this.position = position;
  83236. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83237. this.color = color || new BABYLON.Color3(1, 1, 1);
  83238. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83239. this._system = system;
  83240. system.lensFlares.push(this);
  83241. }
  83242. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83243. return new LensFlare(size, position, color, imgUrl, system);
  83244. };
  83245. LensFlare.prototype.dispose = function () {
  83246. if (this.texture) {
  83247. this.texture.dispose();
  83248. }
  83249. // Remove from scene
  83250. var index = this._system.lensFlares.indexOf(this);
  83251. this._system.lensFlares.splice(index, 1);
  83252. };
  83253. ;
  83254. return LensFlare;
  83255. }());
  83256. BABYLON.LensFlare = LensFlare;
  83257. })(BABYLON || (BABYLON = {}));
  83258. //# sourceMappingURL=babylon.lensFlare.js.map
  83259. var BABYLON;
  83260. (function (BABYLON) {
  83261. var LensFlareSystem = /** @class */ (function () {
  83262. function LensFlareSystem(name, emitter, scene) {
  83263. this.name = name;
  83264. this.lensFlares = new Array();
  83265. this.borderLimit = 300;
  83266. this.viewportBorder = 0;
  83267. this.layerMask = 0x0FFFFFFF;
  83268. this._vertexBuffers = {};
  83269. this._isEnabled = true;
  83270. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83271. this._emitter = emitter;
  83272. this.id = name;
  83273. scene.lensFlareSystems.push(this);
  83274. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83275. var engine = scene.getEngine();
  83276. // VBO
  83277. var vertices = [];
  83278. vertices.push(1, 1);
  83279. vertices.push(-1, 1);
  83280. vertices.push(-1, -1);
  83281. vertices.push(1, -1);
  83282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83283. // Indices
  83284. var indices = [];
  83285. indices.push(0);
  83286. indices.push(1);
  83287. indices.push(2);
  83288. indices.push(0);
  83289. indices.push(2);
  83290. indices.push(3);
  83291. this._indexBuffer = engine.createIndexBuffer(indices);
  83292. // Effects
  83293. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83294. }
  83295. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83296. get: function () {
  83297. return this._isEnabled;
  83298. },
  83299. set: function (value) {
  83300. this._isEnabled = value;
  83301. },
  83302. enumerable: true,
  83303. configurable: true
  83304. });
  83305. LensFlareSystem.prototype.getScene = function () {
  83306. return this._scene;
  83307. };
  83308. LensFlareSystem.prototype.getEmitter = function () {
  83309. return this._emitter;
  83310. };
  83311. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83312. this._emitter = newEmitter;
  83313. };
  83314. LensFlareSystem.prototype.getEmitterPosition = function () {
  83315. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83316. };
  83317. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83318. var position = this.getEmitterPosition();
  83319. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83320. this._positionX = position.x;
  83321. this._positionY = position.y;
  83322. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83323. if (this.viewportBorder > 0) {
  83324. globalViewport.x -= this.viewportBorder;
  83325. globalViewport.y -= this.viewportBorder;
  83326. globalViewport.width += this.viewportBorder * 2;
  83327. globalViewport.height += this.viewportBorder * 2;
  83328. position.x += this.viewportBorder;
  83329. position.y += this.viewportBorder;
  83330. this._positionX += this.viewportBorder;
  83331. this._positionY += this.viewportBorder;
  83332. }
  83333. if (position.z > 0) {
  83334. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83335. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83336. return true;
  83337. }
  83338. return true;
  83339. }
  83340. return false;
  83341. };
  83342. LensFlareSystem.prototype._isVisible = function () {
  83343. if (!this._isEnabled || !this._scene.activeCamera) {
  83344. return false;
  83345. }
  83346. var emitterPosition = this.getEmitterPosition();
  83347. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83348. var distance = direction.length();
  83349. direction.normalize();
  83350. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83351. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83352. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83353. };
  83354. LensFlareSystem.prototype.render = function () {
  83355. if (!this._effect.isReady() || !this._scene.activeCamera)
  83356. return false;
  83357. var engine = this._scene.getEngine();
  83358. var viewport = this._scene.activeCamera.viewport;
  83359. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83360. // Position
  83361. if (!this.computeEffectivePosition(globalViewport)) {
  83362. return false;
  83363. }
  83364. // Visibility
  83365. if (!this._isVisible()) {
  83366. return false;
  83367. }
  83368. // Intensity
  83369. var awayX;
  83370. var awayY;
  83371. if (this._positionX < this.borderLimit + globalViewport.x) {
  83372. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83373. }
  83374. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83375. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83376. }
  83377. else {
  83378. awayX = 0;
  83379. }
  83380. if (this._positionY < this.borderLimit + globalViewport.y) {
  83381. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83382. }
  83383. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83384. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83385. }
  83386. else {
  83387. awayY = 0;
  83388. }
  83389. var away = (awayX > awayY) ? awayX : awayY;
  83390. away -= this.viewportBorder;
  83391. if (away > this.borderLimit) {
  83392. away = this.borderLimit;
  83393. }
  83394. var intensity = 1.0 - (away / this.borderLimit);
  83395. if (intensity < 0) {
  83396. return false;
  83397. }
  83398. if (intensity > 1.0) {
  83399. intensity = 1.0;
  83400. }
  83401. if (this.viewportBorder > 0) {
  83402. globalViewport.x += this.viewportBorder;
  83403. globalViewport.y += this.viewportBorder;
  83404. globalViewport.width -= this.viewportBorder * 2;
  83405. globalViewport.height -= this.viewportBorder * 2;
  83406. this._positionX -= this.viewportBorder;
  83407. this._positionY -= this.viewportBorder;
  83408. }
  83409. // Position
  83410. var centerX = globalViewport.x + globalViewport.width / 2;
  83411. var centerY = globalViewport.y + globalViewport.height / 2;
  83412. var distX = centerX - this._positionX;
  83413. var distY = centerY - this._positionY;
  83414. // Effects
  83415. engine.enableEffect(this._effect);
  83416. engine.setState(false);
  83417. engine.setDepthBuffer(false);
  83418. // VBOs
  83419. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83420. // Flares
  83421. for (var index = 0; index < this.lensFlares.length; index++) {
  83422. var flare = this.lensFlares[index];
  83423. engine.setAlphaMode(flare.alphaMode);
  83424. var x = centerX - (distX * flare.position);
  83425. var y = centerY - (distY * flare.position);
  83426. var cw = flare.size;
  83427. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83428. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83429. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83430. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83431. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83432. // Texture
  83433. this._effect.setTexture("textureSampler", flare.texture);
  83434. // Color
  83435. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83436. // Draw order
  83437. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83438. }
  83439. engine.setDepthBuffer(true);
  83440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83441. return true;
  83442. };
  83443. LensFlareSystem.prototype.dispose = function () {
  83444. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83445. if (vertexBuffer) {
  83446. vertexBuffer.dispose();
  83447. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83448. }
  83449. if (this._indexBuffer) {
  83450. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83451. this._indexBuffer = null;
  83452. }
  83453. while (this.lensFlares.length) {
  83454. this.lensFlares[0].dispose();
  83455. }
  83456. // Remove from scene
  83457. var index = this._scene.lensFlareSystems.indexOf(this);
  83458. this._scene.lensFlareSystems.splice(index, 1);
  83459. };
  83460. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83461. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83462. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83463. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83464. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83465. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83466. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83467. var parsedFlare = parsedLensFlareSystem.flares[index];
  83468. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83469. }
  83470. return lensFlareSystem;
  83471. };
  83472. LensFlareSystem.prototype.serialize = function () {
  83473. var serializationObject = {};
  83474. serializationObject.id = this.id;
  83475. serializationObject.name = this.name;
  83476. serializationObject.emitterId = this.getEmitter().id;
  83477. serializationObject.borderLimit = this.borderLimit;
  83478. serializationObject.flares = [];
  83479. for (var index = 0; index < this.lensFlares.length; index++) {
  83480. var flare = this.lensFlares[index];
  83481. serializationObject.flares.push({
  83482. size: flare.size,
  83483. position: flare.position,
  83484. color: flare.color.asArray(),
  83485. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83486. });
  83487. }
  83488. return serializationObject;
  83489. };
  83490. return LensFlareSystem;
  83491. }());
  83492. BABYLON.LensFlareSystem = LensFlareSystem;
  83493. })(BABYLON || (BABYLON = {}));
  83494. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83495. var BABYLON;
  83496. (function (BABYLON) {
  83497. /**
  83498. * This is a holder class for the physics joint created by the physics plugin.
  83499. * It holds a set of functions to control the underlying joint.
  83500. */
  83501. var PhysicsJoint = /** @class */ (function () {
  83502. function PhysicsJoint(type, jointData) {
  83503. this.type = type;
  83504. this.jointData = jointData;
  83505. jointData.nativeParams = jointData.nativeParams || {};
  83506. }
  83507. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83508. get: function () {
  83509. return this._physicsJoint;
  83510. },
  83511. set: function (newJoint) {
  83512. if (this._physicsJoint) {
  83513. //remove from the wolrd
  83514. }
  83515. this._physicsJoint = newJoint;
  83516. },
  83517. enumerable: true,
  83518. configurable: true
  83519. });
  83520. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83521. set: function (physicsPlugin) {
  83522. this._physicsPlugin = physicsPlugin;
  83523. },
  83524. enumerable: true,
  83525. configurable: true
  83526. });
  83527. /**
  83528. * Execute a function that is physics-plugin specific.
  83529. * @param {Function} func the function that will be executed.
  83530. * It accepts two parameters: the physics world and the physics joint.
  83531. */
  83532. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83533. func(this._physicsPlugin.world, this._physicsJoint);
  83534. };
  83535. //TODO check if the native joints are the same
  83536. //Joint Types
  83537. PhysicsJoint.DistanceJoint = 0;
  83538. PhysicsJoint.HingeJoint = 1;
  83539. PhysicsJoint.BallAndSocketJoint = 2;
  83540. PhysicsJoint.WheelJoint = 3;
  83541. PhysicsJoint.SliderJoint = 4;
  83542. //OIMO
  83543. PhysicsJoint.PrismaticJoint = 5;
  83544. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83545. PhysicsJoint.UniversalJoint = 6;
  83546. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83547. //Cannon
  83548. //Similar to a Ball-Joint. Different in params
  83549. PhysicsJoint.PointToPointJoint = 8;
  83550. //Cannon only at the moment
  83551. PhysicsJoint.SpringJoint = 9;
  83552. PhysicsJoint.LockJoint = 10;
  83553. return PhysicsJoint;
  83554. }());
  83555. BABYLON.PhysicsJoint = PhysicsJoint;
  83556. /**
  83557. * A class representing a physics distance joint.
  83558. */
  83559. var DistanceJoint = /** @class */ (function (_super) {
  83560. __extends(DistanceJoint, _super);
  83561. function DistanceJoint(jointData) {
  83562. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83563. }
  83564. /**
  83565. * Update the predefined distance.
  83566. */
  83567. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83568. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83569. };
  83570. return DistanceJoint;
  83571. }(PhysicsJoint));
  83572. BABYLON.DistanceJoint = DistanceJoint;
  83573. var MotorEnabledJoint = /** @class */ (function (_super) {
  83574. __extends(MotorEnabledJoint, _super);
  83575. function MotorEnabledJoint(type, jointData) {
  83576. return _super.call(this, type, jointData) || this;
  83577. }
  83578. /**
  83579. * Set the motor values.
  83580. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83581. * @param {number} force the force to apply
  83582. * @param {number} maxForce max force for this motor.
  83583. */
  83584. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83585. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83586. };
  83587. /**
  83588. * Set the motor's limits.
  83589. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83590. */
  83591. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83592. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83593. };
  83594. return MotorEnabledJoint;
  83595. }(PhysicsJoint));
  83596. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83597. /**
  83598. * This class represents a single hinge physics joint
  83599. */
  83600. var HingeJoint = /** @class */ (function (_super) {
  83601. __extends(HingeJoint, _super);
  83602. function HingeJoint(jointData) {
  83603. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83604. }
  83605. /**
  83606. * Set the motor values.
  83607. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83608. * @param {number} force the force to apply
  83609. * @param {number} maxForce max force for this motor.
  83610. */
  83611. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83612. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83613. };
  83614. /**
  83615. * Set the motor's limits.
  83616. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83617. */
  83618. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83619. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83620. };
  83621. return HingeJoint;
  83622. }(MotorEnabledJoint));
  83623. BABYLON.HingeJoint = HingeJoint;
  83624. /**
  83625. * This class represents a dual hinge physics joint (same as wheel joint)
  83626. */
  83627. var Hinge2Joint = /** @class */ (function (_super) {
  83628. __extends(Hinge2Joint, _super);
  83629. function Hinge2Joint(jointData) {
  83630. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83631. }
  83632. /**
  83633. * Set the motor values.
  83634. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83635. * @param {number} force the force to apply
  83636. * @param {number} maxForce max force for this motor.
  83637. * @param {motorIndex} the motor's index, 0 or 1.
  83638. */
  83639. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83640. if (motorIndex === void 0) { motorIndex = 0; }
  83641. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83642. };
  83643. /**
  83644. * Set the motor limits.
  83645. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83646. * @param {number} upperLimit the upper limit
  83647. * @param {number} lowerLimit lower limit
  83648. * @param {motorIndex} the motor's index, 0 or 1.
  83649. */
  83650. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83651. if (motorIndex === void 0) { motorIndex = 0; }
  83652. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83653. };
  83654. return Hinge2Joint;
  83655. }(MotorEnabledJoint));
  83656. BABYLON.Hinge2Joint = Hinge2Joint;
  83657. })(BABYLON || (BABYLON = {}));
  83658. //# sourceMappingURL=babylon.physicsJoint.js.map
  83659. var BABYLON;
  83660. (function (BABYLON) {
  83661. var PhysicsImpostor = /** @class */ (function () {
  83662. function PhysicsImpostor(object, type, _options, _scene) {
  83663. if (_options === void 0) { _options = { mass: 0 }; }
  83664. var _this = this;
  83665. this.object = object;
  83666. this.type = type;
  83667. this._options = _options;
  83668. this._scene = _scene;
  83669. this._bodyUpdateRequired = false;
  83670. this._onBeforePhysicsStepCallbacks = new Array();
  83671. this._onAfterPhysicsStepCallbacks = new Array();
  83672. this._onPhysicsCollideCallbacks = [];
  83673. this._deltaPosition = BABYLON.Vector3.Zero();
  83674. this._isDisposed = false;
  83675. //temp variables for parent rotation calculations
  83676. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83677. this._tmpQuat = new BABYLON.Quaternion();
  83678. this._tmpQuat2 = new BABYLON.Quaternion();
  83679. /**
  83680. * this function is executed by the physics engine.
  83681. */
  83682. this.beforeStep = function () {
  83683. if (!_this._physicsEngine) {
  83684. return;
  83685. }
  83686. _this.object.translate(_this._deltaPosition, -1);
  83687. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83688. _this.object.computeWorldMatrix(false);
  83689. if (_this.object.parent && _this.object.rotationQuaternion) {
  83690. _this.getParentsRotation();
  83691. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83692. }
  83693. else {
  83694. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83695. }
  83696. if (!_this._options.disableBidirectionalTransformation) {
  83697. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83698. }
  83699. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83700. func(_this);
  83701. });
  83702. };
  83703. /**
  83704. * this function is executed by the physics engine.
  83705. */
  83706. this.afterStep = function () {
  83707. if (!_this._physicsEngine) {
  83708. return;
  83709. }
  83710. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83711. func(_this);
  83712. });
  83713. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83714. // object has now its world rotation. needs to be converted to local.
  83715. if (_this.object.parent && _this.object.rotationQuaternion) {
  83716. _this.getParentsRotation();
  83717. _this._tmpQuat.conjugateInPlace();
  83718. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83719. }
  83720. // take the position set and make it the absolute position of this object.
  83721. _this.object.setAbsolutePosition(_this.object.position);
  83722. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83723. _this.object.translate(_this._deltaPosition, 1);
  83724. };
  83725. /**
  83726. * Legacy collision detection event support
  83727. */
  83728. this.onCollideEvent = null;
  83729. //event and body object due to cannon's event-based architecture.
  83730. this.onCollide = function (e) {
  83731. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83732. return;
  83733. }
  83734. if (!_this._physicsEngine) {
  83735. return;
  83736. }
  83737. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83738. if (otherImpostor) {
  83739. // Legacy collision detection event support
  83740. if (_this.onCollideEvent) {
  83741. _this.onCollideEvent(_this, otherImpostor);
  83742. }
  83743. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83744. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83745. }).forEach(function (obj) {
  83746. obj.callback(_this, otherImpostor);
  83747. });
  83748. }
  83749. };
  83750. //sanity check!
  83751. if (!this.object) {
  83752. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83753. return;
  83754. }
  83755. //legacy support for old syntax.
  83756. if (!this._scene && object.getScene) {
  83757. this._scene = object.getScene();
  83758. }
  83759. if (!this._scene) {
  83760. return;
  83761. }
  83762. this._physicsEngine = this._scene.getPhysicsEngine();
  83763. if (!this._physicsEngine) {
  83764. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83765. }
  83766. else {
  83767. //set the object's quaternion, if not set
  83768. if (!this.object.rotationQuaternion) {
  83769. if (this.object.rotation) {
  83770. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83771. }
  83772. else {
  83773. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83774. }
  83775. }
  83776. //default options params
  83777. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83778. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83779. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83780. this._joints = [];
  83781. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83782. if (!this.object.parent || this._options.ignoreParent) {
  83783. this._init();
  83784. }
  83785. else if (this.object.parent.physicsImpostor) {
  83786. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83787. }
  83788. }
  83789. }
  83790. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83791. get: function () {
  83792. return this._isDisposed;
  83793. },
  83794. enumerable: true,
  83795. configurable: true
  83796. });
  83797. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83798. get: function () {
  83799. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83800. },
  83801. set: function (value) {
  83802. this.setMass(value);
  83803. },
  83804. enumerable: true,
  83805. configurable: true
  83806. });
  83807. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83808. get: function () {
  83809. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83810. },
  83811. set: function (value) {
  83812. if (!this._physicsEngine) {
  83813. return;
  83814. }
  83815. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83816. },
  83817. enumerable: true,
  83818. configurable: true
  83819. });
  83820. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83821. get: function () {
  83822. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83823. },
  83824. set: function (value) {
  83825. if (!this._physicsEngine) {
  83826. return;
  83827. }
  83828. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83829. },
  83830. enumerable: true,
  83831. configurable: true
  83832. });
  83833. /**
  83834. * This function will completly initialize this impostor.
  83835. * It will create a new body - but only if this mesh has no parent.
  83836. * If it has, this impostor will not be used other than to define the impostor
  83837. * of the child mesh.
  83838. */
  83839. PhysicsImpostor.prototype._init = function () {
  83840. if (!this._physicsEngine) {
  83841. return;
  83842. }
  83843. this._physicsEngine.removeImpostor(this);
  83844. this.physicsBody = null;
  83845. this._parent = this._parent || this._getPhysicsParent();
  83846. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83847. this._physicsEngine.addImpostor(this);
  83848. }
  83849. };
  83850. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83851. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83852. var parentMesh = this.object.parent;
  83853. return parentMesh.physicsImpostor;
  83854. }
  83855. return null;
  83856. };
  83857. /**
  83858. * Should a new body be generated.
  83859. */
  83860. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83861. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83862. };
  83863. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83864. this.forceUpdate();
  83865. };
  83866. /**
  83867. * Force a regeneration of this or the parent's impostor's body.
  83868. * Use under cautious - This will remove all joints already implemented.
  83869. */
  83870. PhysicsImpostor.prototype.forceUpdate = function () {
  83871. this._init();
  83872. if (this.parent && !this._options.ignoreParent) {
  83873. this.parent.forceUpdate();
  83874. }
  83875. };
  83876. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83877. /*public get mesh(): AbstractMesh {
  83878. return this._mesh;
  83879. }*/
  83880. /**
  83881. * Gets the body that holds this impostor. Either its own, or its parent.
  83882. */
  83883. get: function () {
  83884. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83885. },
  83886. /**
  83887. * Set the physics body. Used mainly by the physics engine/plugin
  83888. */
  83889. set: function (physicsBody) {
  83890. if (this._physicsBody && this._physicsEngine) {
  83891. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83892. }
  83893. this._physicsBody = physicsBody;
  83894. this.resetUpdateFlags();
  83895. },
  83896. enumerable: true,
  83897. configurable: true
  83898. });
  83899. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83900. get: function () {
  83901. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83902. },
  83903. set: function (value) {
  83904. this._parent = value;
  83905. },
  83906. enumerable: true,
  83907. configurable: true
  83908. });
  83909. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83910. this._bodyUpdateRequired = false;
  83911. };
  83912. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83913. if (this.object.getBoundingInfo) {
  83914. var q = this.object.rotationQuaternion;
  83915. //reset rotation
  83916. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83917. //calculate the world matrix with no rotation
  83918. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83919. var boundingInfo = this.object.getBoundingInfo();
  83920. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83921. //bring back the rotation
  83922. this.object.rotationQuaternion = q;
  83923. //calculate the world matrix with the new rotation
  83924. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83925. return size;
  83926. }
  83927. else {
  83928. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83929. }
  83930. };
  83931. PhysicsImpostor.prototype.getObjectCenter = function () {
  83932. if (this.object.getBoundingInfo) {
  83933. var boundingInfo = this.object.getBoundingInfo();
  83934. return boundingInfo.boundingBox.centerWorld;
  83935. }
  83936. else {
  83937. return this.object.position;
  83938. }
  83939. };
  83940. /**
  83941. * Get a specific parametes from the options parameter.
  83942. */
  83943. PhysicsImpostor.prototype.getParam = function (paramName) {
  83944. return this._options[paramName];
  83945. };
  83946. /**
  83947. * Sets a specific parameter in the options given to the physics plugin
  83948. */
  83949. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83950. this._options[paramName] = value;
  83951. this._bodyUpdateRequired = true;
  83952. };
  83953. /**
  83954. * Specifically change the body's mass option. Won't recreate the physics body object
  83955. */
  83956. PhysicsImpostor.prototype.setMass = function (mass) {
  83957. if (this.getParam("mass") !== mass) {
  83958. this.setParam("mass", mass);
  83959. }
  83960. if (this._physicsEngine) {
  83961. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83962. }
  83963. };
  83964. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83965. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83966. };
  83967. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83968. if (this._physicsEngine) {
  83969. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83970. }
  83971. };
  83972. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83973. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83974. };
  83975. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83976. if (this._physicsEngine) {
  83977. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83978. }
  83979. };
  83980. /**
  83981. * Execute a function with the physics plugin native code.
  83982. * Provide a function the will have two variables - the world object and the physics body object.
  83983. */
  83984. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83985. if (this._physicsEngine) {
  83986. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83987. }
  83988. };
  83989. /**
  83990. * Register a function that will be executed before the physics world is stepping forward.
  83991. */
  83992. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83993. this._onBeforePhysicsStepCallbacks.push(func);
  83994. };
  83995. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83996. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83997. if (index > -1) {
  83998. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83999. }
  84000. else {
  84001. BABYLON.Tools.Warn("Function to remove was not found");
  84002. }
  84003. };
  84004. /**
  84005. * Register a function that will be executed after the physics step
  84006. */
  84007. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84008. this._onAfterPhysicsStepCallbacks.push(func);
  84009. };
  84010. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84011. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84012. if (index > -1) {
  84013. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84014. }
  84015. else {
  84016. BABYLON.Tools.Warn("Function to remove was not found");
  84017. }
  84018. };
  84019. /**
  84020. * register a function that will be executed when this impostor collides against a different body.
  84021. */
  84022. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84023. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84024. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84025. };
  84026. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84027. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84028. var index = -1;
  84029. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84030. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84031. // chcek the arrays match
  84032. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84033. return collidedAgainstList.indexOf(impostor) > -1;
  84034. });
  84035. if (sameList) {
  84036. index = idx;
  84037. }
  84038. return sameList;
  84039. }
  84040. return false;
  84041. });
  84042. if (found) {
  84043. this._onPhysicsCollideCallbacks.splice(index, 1);
  84044. }
  84045. else {
  84046. BABYLON.Tools.Warn("Function to remove was not found");
  84047. }
  84048. };
  84049. PhysicsImpostor.prototype.getParentsRotation = function () {
  84050. var parent = this.object.parent;
  84051. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84052. while (parent) {
  84053. if (parent.rotationQuaternion) {
  84054. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84055. }
  84056. else {
  84057. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84058. }
  84059. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84060. parent = parent.parent;
  84061. }
  84062. return this._tmpQuat;
  84063. };
  84064. /**
  84065. * Apply a force
  84066. */
  84067. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84068. if (this._physicsEngine) {
  84069. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84070. }
  84071. return this;
  84072. };
  84073. /**
  84074. * Apply an impulse
  84075. */
  84076. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84077. if (this._physicsEngine) {
  84078. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84079. }
  84080. return this;
  84081. };
  84082. /**
  84083. * A help function to create a joint.
  84084. */
  84085. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84086. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84087. this.addJoint(otherImpostor, joint);
  84088. return this;
  84089. };
  84090. /**
  84091. * Add a joint to this impostor with a different impostor.
  84092. */
  84093. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84094. this._joints.push({
  84095. otherImpostor: otherImpostor,
  84096. joint: joint
  84097. });
  84098. if (this._physicsEngine) {
  84099. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84100. }
  84101. return this;
  84102. };
  84103. /**
  84104. * Will keep this body still, in a sleep mode.
  84105. */
  84106. PhysicsImpostor.prototype.sleep = function () {
  84107. if (this._physicsEngine) {
  84108. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84109. }
  84110. return this;
  84111. };
  84112. /**
  84113. * Wake the body up.
  84114. */
  84115. PhysicsImpostor.prototype.wakeUp = function () {
  84116. if (this._physicsEngine) {
  84117. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84118. }
  84119. return this;
  84120. };
  84121. PhysicsImpostor.prototype.clone = function (newObject) {
  84122. if (!newObject)
  84123. return null;
  84124. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84125. };
  84126. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84127. var _this = this;
  84128. //no dispose if no physics engine is available.
  84129. if (!this._physicsEngine) {
  84130. return;
  84131. }
  84132. this._joints.forEach(function (j) {
  84133. if (_this._physicsEngine) {
  84134. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84135. }
  84136. });
  84137. //dispose the physics body
  84138. this._physicsEngine.removeImpostor(this);
  84139. if (this.parent) {
  84140. this.parent.forceUpdate();
  84141. }
  84142. else {
  84143. /*this._object.getChildMeshes().forEach(function(mesh) {
  84144. if (mesh.physicsImpostor) {
  84145. if (disposeChildren) {
  84146. mesh.physicsImpostor.dispose();
  84147. mesh.physicsImpostor = null;
  84148. }
  84149. }
  84150. })*/
  84151. }
  84152. this._isDisposed = true;
  84153. };
  84154. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84155. this._deltaPosition.copyFrom(position);
  84156. };
  84157. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84158. if (!this._deltaRotation) {
  84159. this._deltaRotation = new BABYLON.Quaternion();
  84160. }
  84161. this._deltaRotation.copyFrom(rotation);
  84162. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84163. };
  84164. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84165. if (this._physicsEngine) {
  84166. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84167. }
  84168. return this;
  84169. };
  84170. PhysicsImpostor.prototype.getRadius = function () {
  84171. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84172. };
  84173. /**
  84174. * Sync a bone with this impostor
  84175. * @param bone The bone to sync to the impostor.
  84176. * @param boneMesh The mesh that the bone is influencing.
  84177. * @param jointPivot The pivot of the joint / bone in local space.
  84178. * @param distToJoint Optional distance from the impostor to the joint.
  84179. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84180. */
  84181. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84182. var tempVec = PhysicsImpostor._tmpVecs[0];
  84183. var mesh = this.object;
  84184. if (mesh.rotationQuaternion) {
  84185. if (adjustRotation) {
  84186. var tempQuat = PhysicsImpostor._tmpQuat;
  84187. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84188. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84189. }
  84190. else {
  84191. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84192. }
  84193. }
  84194. tempVec.x = 0;
  84195. tempVec.y = 0;
  84196. tempVec.z = 0;
  84197. if (jointPivot) {
  84198. tempVec.x = jointPivot.x;
  84199. tempVec.y = jointPivot.y;
  84200. tempVec.z = jointPivot.z;
  84201. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84202. if (distToJoint === undefined || distToJoint === null) {
  84203. distToJoint = jointPivot.length();
  84204. }
  84205. tempVec.x *= distToJoint;
  84206. tempVec.y *= distToJoint;
  84207. tempVec.z *= distToJoint;
  84208. }
  84209. if (bone.getParent()) {
  84210. tempVec.addInPlace(mesh.getAbsolutePosition());
  84211. bone.setAbsolutePosition(tempVec, boneMesh);
  84212. }
  84213. else {
  84214. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84215. boneMesh.position.x -= tempVec.x;
  84216. boneMesh.position.y -= tempVec.y;
  84217. boneMesh.position.z -= tempVec.z;
  84218. }
  84219. };
  84220. /**
  84221. * Sync impostor to a bone
  84222. * @param bone The bone that the impostor will be synced to.
  84223. * @param boneMesh The mesh that the bone is influencing.
  84224. * @param jointPivot The pivot of the joint / bone in local space.
  84225. * @param distToJoint Optional distance from the impostor to the joint.
  84226. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84227. * @param boneAxis Optional vector3 axis the bone is aligned with
  84228. */
  84229. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84230. var mesh = this.object;
  84231. if (mesh.rotationQuaternion) {
  84232. if (adjustRotation) {
  84233. var tempQuat = PhysicsImpostor._tmpQuat;
  84234. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84235. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84236. }
  84237. else {
  84238. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84239. }
  84240. }
  84241. var pos = PhysicsImpostor._tmpVecs[0];
  84242. var boneDir = PhysicsImpostor._tmpVecs[1];
  84243. if (!boneAxis) {
  84244. boneAxis = PhysicsImpostor._tmpVecs[2];
  84245. boneAxis.x = 0;
  84246. boneAxis.y = 1;
  84247. boneAxis.z = 0;
  84248. }
  84249. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84250. bone.getAbsolutePositionToRef(boneMesh, pos);
  84251. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84252. distToJoint = jointPivot.length();
  84253. }
  84254. if (distToJoint !== undefined && distToJoint !== null) {
  84255. pos.x += boneDir.x * distToJoint;
  84256. pos.y += boneDir.y * distToJoint;
  84257. pos.z += boneDir.z * distToJoint;
  84258. }
  84259. mesh.setAbsolutePosition(pos);
  84260. };
  84261. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84262. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84263. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84264. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84265. //Impostor types
  84266. PhysicsImpostor.NoImpostor = 0;
  84267. PhysicsImpostor.SphereImpostor = 1;
  84268. PhysicsImpostor.BoxImpostor = 2;
  84269. PhysicsImpostor.PlaneImpostor = 3;
  84270. PhysicsImpostor.MeshImpostor = 4;
  84271. PhysicsImpostor.CylinderImpostor = 7;
  84272. PhysicsImpostor.ParticleImpostor = 8;
  84273. PhysicsImpostor.HeightmapImpostor = 9;
  84274. return PhysicsImpostor;
  84275. }());
  84276. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84277. })(BABYLON || (BABYLON = {}));
  84278. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84279. var BABYLON;
  84280. (function (BABYLON) {
  84281. var PhysicsEngine = /** @class */ (function () {
  84282. function PhysicsEngine(gravity, _physicsPlugin) {
  84283. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84284. this._physicsPlugin = _physicsPlugin;
  84285. //new methods and parameters
  84286. this._impostors = [];
  84287. this._joints = [];
  84288. if (!this._physicsPlugin.isSupported()) {
  84289. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84290. + "Please make sure it is included.");
  84291. }
  84292. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84293. this.setGravity(gravity);
  84294. this.setTimeStep();
  84295. }
  84296. PhysicsEngine.prototype.setGravity = function (gravity) {
  84297. this.gravity = gravity;
  84298. this._physicsPlugin.setGravity(this.gravity);
  84299. };
  84300. /**
  84301. * Set the time step of the physics engine.
  84302. * default is 1/60.
  84303. * To slow it down, enter 1/600 for example.
  84304. * To speed it up, 1/30
  84305. * @param {number} newTimeStep the new timestep to apply to this world.
  84306. */
  84307. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84308. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84309. this._physicsPlugin.setTimeStep(newTimeStep);
  84310. };
  84311. /**
  84312. * Get the time step of the physics engine.
  84313. */
  84314. PhysicsEngine.prototype.getTimeStep = function () {
  84315. return this._physicsPlugin.getTimeStep();
  84316. };
  84317. PhysicsEngine.prototype.dispose = function () {
  84318. this._impostors.forEach(function (impostor) {
  84319. impostor.dispose();
  84320. });
  84321. this._physicsPlugin.dispose();
  84322. };
  84323. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84324. return this._physicsPlugin.name;
  84325. };
  84326. /**
  84327. * Adding a new impostor for the impostor tracking.
  84328. * This will be done by the impostor itself.
  84329. * @param {PhysicsImpostor} impostor the impostor to add
  84330. */
  84331. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84332. impostor.uniqueId = this._impostors.push(impostor);
  84333. //if no parent, generate the body
  84334. if (!impostor.parent) {
  84335. this._physicsPlugin.generatePhysicsBody(impostor);
  84336. }
  84337. };
  84338. /**
  84339. * Remove an impostor from the engine.
  84340. * This impostor and its mesh will not longer be updated by the physics engine.
  84341. * @param {PhysicsImpostor} impostor the impostor to remove
  84342. */
  84343. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84344. var index = this._impostors.indexOf(impostor);
  84345. if (index > -1) {
  84346. var removed = this._impostors.splice(index, 1);
  84347. //Is it needed?
  84348. if (removed.length) {
  84349. //this will also remove it from the world.
  84350. removed[0].physicsBody = null;
  84351. }
  84352. }
  84353. };
  84354. /**
  84355. * Add a joint to the physics engine
  84356. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84357. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84358. * @param {PhysicsJoint} the joint that will connect both impostors.
  84359. */
  84360. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84361. var impostorJoint = {
  84362. mainImpostor: mainImpostor,
  84363. connectedImpostor: connectedImpostor,
  84364. joint: joint
  84365. };
  84366. joint.physicsPlugin = this._physicsPlugin;
  84367. this._joints.push(impostorJoint);
  84368. this._physicsPlugin.generateJoint(impostorJoint);
  84369. };
  84370. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84371. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84372. return (impostorJoint.connectedImpostor === connectedImpostor
  84373. && impostorJoint.joint === joint
  84374. && impostorJoint.mainImpostor === mainImpostor);
  84375. });
  84376. if (matchingJoints.length) {
  84377. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84378. //TODO remove it from the list as well
  84379. }
  84380. };
  84381. /**
  84382. * Called by the scene. no need to call it.
  84383. */
  84384. PhysicsEngine.prototype._step = function (delta) {
  84385. var _this = this;
  84386. //check if any mesh has no body / requires an update
  84387. this._impostors.forEach(function (impostor) {
  84388. if (impostor.isBodyInitRequired()) {
  84389. _this._physicsPlugin.generatePhysicsBody(impostor);
  84390. }
  84391. });
  84392. if (delta > 0.1) {
  84393. delta = 0.1;
  84394. }
  84395. else if (delta <= 0) {
  84396. delta = 1.0 / 60.0;
  84397. }
  84398. this._physicsPlugin.executeStep(delta, this._impostors);
  84399. };
  84400. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84401. return this._physicsPlugin;
  84402. };
  84403. PhysicsEngine.prototype.getImpostors = function () {
  84404. return this._impostors;
  84405. };
  84406. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84407. for (var i = 0; i < this._impostors.length; ++i) {
  84408. if (this._impostors[i].object === object) {
  84409. return this._impostors[i];
  84410. }
  84411. }
  84412. return null;
  84413. };
  84414. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84415. for (var i = 0; i < this._impostors.length; ++i) {
  84416. if (this._impostors[i].physicsBody === body) {
  84417. return this._impostors[i];
  84418. }
  84419. }
  84420. return null;
  84421. };
  84422. // Statics
  84423. PhysicsEngine.Epsilon = 0.001;
  84424. return PhysicsEngine;
  84425. }());
  84426. BABYLON.PhysicsEngine = PhysicsEngine;
  84427. })(BABYLON || (BABYLON = {}));
  84428. //# sourceMappingURL=babylon.physicsEngine.js.map
  84429. var BABYLON;
  84430. (function (BABYLON) {
  84431. var PhysicsHelper = /** @class */ (function () {
  84432. function PhysicsHelper(scene) {
  84433. this._scene = scene;
  84434. this._physicsEngine = this._scene.getPhysicsEngine();
  84435. if (!this._physicsEngine) {
  84436. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84437. }
  84438. }
  84439. /**
  84440. * @param {Vector3} origin the origin of the explosion
  84441. * @param {number} radius the explosion radius
  84442. * @param {number} strength the explosion strength
  84443. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84444. */
  84445. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84446. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84447. if (!this._physicsEngine) {
  84448. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84449. return null;
  84450. }
  84451. var impostors = this._physicsEngine.getImpostors();
  84452. if (impostors.length === 0) {
  84453. return null;
  84454. }
  84455. var event = new PhysicsRadialExplosionEvent(this._scene);
  84456. impostors.forEach(function (impostor) {
  84457. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84458. if (!impostorForceAndContactPoint) {
  84459. return;
  84460. }
  84461. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84462. });
  84463. event.dispose(false);
  84464. return event;
  84465. };
  84466. /**
  84467. * @param {Vector3} origin the origin of the explosion
  84468. * @param {number} radius the explosion radius
  84469. * @param {number} strength the explosion strength
  84470. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84471. */
  84472. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84473. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84474. if (!this._physicsEngine) {
  84475. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84476. return null;
  84477. }
  84478. var impostors = this._physicsEngine.getImpostors();
  84479. if (impostors.length === 0) {
  84480. return null;
  84481. }
  84482. var event = new PhysicsRadialExplosionEvent(this._scene);
  84483. impostors.forEach(function (impostor) {
  84484. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84485. if (!impostorForceAndContactPoint) {
  84486. return;
  84487. }
  84488. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84489. });
  84490. event.dispose(false);
  84491. return event;
  84492. };
  84493. /**
  84494. * @param {Vector3} origin the origin of the explosion
  84495. * @param {number} radius the explosion radius
  84496. * @param {number} strength the explosion strength
  84497. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84498. */
  84499. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84500. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84501. if (!this._physicsEngine) {
  84502. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84503. return null;
  84504. }
  84505. var impostors = this._physicsEngine.getImpostors();
  84506. if (impostors.length === 0) {
  84507. return null;
  84508. }
  84509. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84510. event.dispose(false);
  84511. return event;
  84512. };
  84513. /**
  84514. * @param {Vector3} origin the origin of the updraft
  84515. * @param {number} radius the radius of the updraft
  84516. * @param {number} strength the strength of the updraft
  84517. * @param {number} height the height of the updraft
  84518. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84519. */
  84520. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84521. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84522. if (!this._physicsEngine) {
  84523. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84524. return null;
  84525. }
  84526. if (this._physicsEngine.getImpostors().length === 0) {
  84527. return null;
  84528. }
  84529. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84530. event.dispose(false);
  84531. return event;
  84532. };
  84533. /**
  84534. * @param {Vector3} origin the of the vortex
  84535. * @param {number} radius the radius of the vortex
  84536. * @param {number} strength the strength of the vortex
  84537. * @param {number} height the height of the vortex
  84538. */
  84539. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84540. if (!this._physicsEngine) {
  84541. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84542. return null;
  84543. }
  84544. if (this._physicsEngine.getImpostors().length === 0) {
  84545. return null;
  84546. }
  84547. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84548. event.dispose(false);
  84549. return event;
  84550. };
  84551. return PhysicsHelper;
  84552. }());
  84553. BABYLON.PhysicsHelper = PhysicsHelper;
  84554. /***** Radial explosion *****/
  84555. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84556. function PhysicsRadialExplosionEvent(scene) {
  84557. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84558. this._rays = [];
  84559. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84560. this._scene = scene;
  84561. }
  84562. /**
  84563. * Returns the data related to the radial explosion event (sphere & rays).
  84564. * @returns {PhysicsRadialExplosionEventData}
  84565. */
  84566. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84567. this._dataFetched = true;
  84568. return {
  84569. sphere: this._sphere,
  84570. rays: this._rays,
  84571. };
  84572. };
  84573. /**
  84574. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84575. * @param impostor
  84576. * @param {Vector3} origin the origin of the explosion
  84577. * @param {number} radius the explosion radius
  84578. * @param {number} strength the explosion strength
  84579. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84580. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84581. */
  84582. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84583. if (impostor.mass === 0) {
  84584. return null;
  84585. }
  84586. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84587. return null;
  84588. }
  84589. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84590. return null;
  84591. }
  84592. var impostorObjectCenter = impostor.getObjectCenter();
  84593. var direction = impostorObjectCenter.subtract(origin);
  84594. var ray = new BABYLON.Ray(origin, direction, radius);
  84595. this._rays.push(ray);
  84596. var hit = ray.intersectsMesh(impostor.object);
  84597. var contactPoint = hit.pickedPoint;
  84598. if (!contactPoint) {
  84599. return null;
  84600. }
  84601. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84602. if (distanceFromOrigin > radius) {
  84603. return null;
  84604. }
  84605. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84606. ? strength
  84607. : strength * (1 - (distanceFromOrigin / radius));
  84608. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84609. return { force: force, contactPoint: contactPoint };
  84610. };
  84611. /**
  84612. * Disposes the sphere.
  84613. * @param {bolean} force
  84614. */
  84615. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84616. var _this = this;
  84617. if (force === void 0) { force = true; }
  84618. if (force) {
  84619. this._sphere.dispose();
  84620. }
  84621. else {
  84622. setTimeout(function () {
  84623. if (!_this._dataFetched) {
  84624. _this._sphere.dispose();
  84625. }
  84626. }, 0);
  84627. }
  84628. };
  84629. /*** Helpers ***/
  84630. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84631. if (!this._sphere) {
  84632. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84633. this._sphere.isVisible = false;
  84634. }
  84635. };
  84636. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84637. var impostorObject = impostor.object;
  84638. this._prepareSphere();
  84639. this._sphere.position = origin;
  84640. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84641. this._sphere._updateBoundingInfo();
  84642. this._sphere.computeWorldMatrix(true);
  84643. return this._sphere.intersectsMesh(impostorObject, true);
  84644. };
  84645. return PhysicsRadialExplosionEvent;
  84646. }());
  84647. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84648. /***** Gravitational Field *****/
  84649. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84650. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84651. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84652. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84653. this._physicsHelper = physicsHelper;
  84654. this._scene = scene;
  84655. this._origin = origin;
  84656. this._radius = radius;
  84657. this._strength = strength;
  84658. this._falloff = falloff;
  84659. this._tickCallback = this._tick.bind(this);
  84660. }
  84661. /**
  84662. * Returns the data related to the gravitational field event (sphere).
  84663. * @returns {PhysicsGravitationalFieldEventData}
  84664. */
  84665. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84666. this._dataFetched = true;
  84667. return {
  84668. sphere: this._sphere,
  84669. };
  84670. };
  84671. /**
  84672. * Enables the gravitational field.
  84673. */
  84674. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84675. this._tickCallback.call(this);
  84676. this._scene.registerBeforeRender(this._tickCallback);
  84677. };
  84678. /**
  84679. * Disables the gravitational field.
  84680. */
  84681. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84682. this._scene.unregisterBeforeRender(this._tickCallback);
  84683. };
  84684. /**
  84685. * Disposes the sphere.
  84686. * @param {bolean} force
  84687. */
  84688. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84689. var _this = this;
  84690. if (force === void 0) { force = true; }
  84691. if (force) {
  84692. this._sphere.dispose();
  84693. }
  84694. else {
  84695. setTimeout(function () {
  84696. if (!_this._dataFetched) {
  84697. _this._sphere.dispose();
  84698. }
  84699. }, 0);
  84700. }
  84701. };
  84702. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84703. // Since the params won't change, we fetch the event only once
  84704. if (this._sphere) {
  84705. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84706. }
  84707. else {
  84708. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84709. if (radialExplosionEvent) {
  84710. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84711. }
  84712. }
  84713. };
  84714. return PhysicsGravitationalFieldEvent;
  84715. }());
  84716. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84717. /***** Updraft *****/
  84718. var PhysicsUpdraftEvent = /** @class */ (function () {
  84719. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84720. this._scene = _scene;
  84721. this._origin = _origin;
  84722. this._radius = _radius;
  84723. this._strength = _strength;
  84724. this._height = _height;
  84725. this._updraftMode = _updraftMode;
  84726. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84727. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84728. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84729. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84730. this._physicsEngine = this._scene.getPhysicsEngine();
  84731. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84732. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84733. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84734. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84735. }
  84736. this._tickCallback = this._tick.bind(this);
  84737. }
  84738. /**
  84739. * Returns the data related to the updraft event (cylinder).
  84740. * @returns {PhysicsUpdraftEventData}
  84741. */
  84742. PhysicsUpdraftEvent.prototype.getData = function () {
  84743. this._dataFetched = true;
  84744. return {
  84745. cylinder: this._cylinder,
  84746. };
  84747. };
  84748. /**
  84749. * Enables the updraft.
  84750. */
  84751. PhysicsUpdraftEvent.prototype.enable = function () {
  84752. this._tickCallback.call(this);
  84753. this._scene.registerBeforeRender(this._tickCallback);
  84754. };
  84755. /**
  84756. * Disables the cortex.
  84757. */
  84758. PhysicsUpdraftEvent.prototype.disable = function () {
  84759. this._scene.unregisterBeforeRender(this._tickCallback);
  84760. };
  84761. /**
  84762. * Disposes the sphere.
  84763. * @param {bolean} force
  84764. */
  84765. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84766. var _this = this;
  84767. if (force === void 0) { force = true; }
  84768. if (force) {
  84769. this._cylinder.dispose();
  84770. }
  84771. else {
  84772. setTimeout(function () {
  84773. if (!_this._dataFetched) {
  84774. _this._cylinder.dispose();
  84775. }
  84776. }, 0);
  84777. }
  84778. };
  84779. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84780. if (impostor.mass === 0) {
  84781. return null;
  84782. }
  84783. if (!this._intersectsWithCylinder(impostor)) {
  84784. return null;
  84785. }
  84786. var impostorObjectCenter = impostor.getObjectCenter();
  84787. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84788. var direction = this._originDirection;
  84789. }
  84790. else {
  84791. var direction = impostorObjectCenter.subtract(this._originTop);
  84792. }
  84793. var multiplier = this._strength * -1;
  84794. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84795. return { force: force, contactPoint: impostorObjectCenter };
  84796. };
  84797. PhysicsUpdraftEvent.prototype._tick = function () {
  84798. var _this = this;
  84799. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84800. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84801. if (!impostorForceAndContactPoint) {
  84802. return;
  84803. }
  84804. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84805. });
  84806. };
  84807. /*** Helpers ***/
  84808. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84809. if (!this._cylinder) {
  84810. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84811. height: this._height,
  84812. diameter: this._radius * 2,
  84813. }, this._scene);
  84814. this._cylinder.isVisible = false;
  84815. }
  84816. };
  84817. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84818. var impostorObject = impostor.object;
  84819. this._prepareCylinder();
  84820. this._cylinder.position = this._cylinderPosition;
  84821. return this._cylinder.intersectsMesh(impostorObject, true);
  84822. };
  84823. return PhysicsUpdraftEvent;
  84824. }());
  84825. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84826. /***** Vortex *****/
  84827. var PhysicsVortexEvent = /** @class */ (function () {
  84828. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84829. this._scene = _scene;
  84830. this._origin = _origin;
  84831. this._radius = _radius;
  84832. this._strength = _strength;
  84833. this._height = _height;
  84834. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84835. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84836. this._updraftMultiplier = 0.02;
  84837. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84838. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84839. this._physicsEngine = this._scene.getPhysicsEngine();
  84840. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84841. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84842. this._tickCallback = this._tick.bind(this);
  84843. }
  84844. /**
  84845. * Returns the data related to the vortex event (cylinder).
  84846. * @returns {PhysicsVortexEventData}
  84847. */
  84848. PhysicsVortexEvent.prototype.getData = function () {
  84849. this._dataFetched = true;
  84850. return {
  84851. cylinder: this._cylinder,
  84852. };
  84853. };
  84854. /**
  84855. * Enables the vortex.
  84856. */
  84857. PhysicsVortexEvent.prototype.enable = function () {
  84858. this._tickCallback.call(this);
  84859. this._scene.registerBeforeRender(this._tickCallback);
  84860. };
  84861. /**
  84862. * Disables the cortex.
  84863. */
  84864. PhysicsVortexEvent.prototype.disable = function () {
  84865. this._scene.unregisterBeforeRender(this._tickCallback);
  84866. };
  84867. /**
  84868. * Disposes the sphere.
  84869. * @param {bolean} force
  84870. */
  84871. PhysicsVortexEvent.prototype.dispose = function (force) {
  84872. var _this = this;
  84873. if (force === void 0) { force = true; }
  84874. if (force) {
  84875. this._cylinder.dispose();
  84876. }
  84877. else {
  84878. setTimeout(function () {
  84879. if (!_this._dataFetched) {
  84880. _this._cylinder.dispose();
  84881. }
  84882. }, 0);
  84883. }
  84884. };
  84885. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84886. if (impostor.mass === 0) {
  84887. return null;
  84888. }
  84889. if (!this._intersectsWithCylinder(impostor)) {
  84890. return null;
  84891. }
  84892. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84893. return null;
  84894. }
  84895. var impostorObjectCenter = impostor.getObjectCenter();
  84896. 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)
  84897. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84898. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84899. var hit = ray.intersectsMesh(impostor.object);
  84900. var contactPoint = hit.pickedPoint;
  84901. if (!contactPoint) {
  84902. return null;
  84903. }
  84904. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84905. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84906. var directionToOrigin = contactPoint.normalize();
  84907. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84908. directionToOrigin = directionToOrigin.negate();
  84909. }
  84910. // TODO: find a more physically based solution
  84911. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84912. var forceX = directionToOrigin.x * this._strength / 8;
  84913. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84914. var forceZ = directionToOrigin.z * this._strength / 8;
  84915. }
  84916. else {
  84917. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84918. var forceY = this._originTop.y * this._updraftMultiplier;
  84919. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84920. }
  84921. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84922. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84923. return { force: force, contactPoint: impostorObjectCenter };
  84924. };
  84925. PhysicsVortexEvent.prototype._tick = function () {
  84926. var _this = this;
  84927. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84928. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84929. if (!impostorForceAndContactPoint) {
  84930. return;
  84931. }
  84932. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84933. });
  84934. };
  84935. /*** Helpers ***/
  84936. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84937. if (!this._cylinder) {
  84938. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84939. height: this._height,
  84940. diameter: this._radius * 2,
  84941. }, this._scene);
  84942. this._cylinder.isVisible = false;
  84943. }
  84944. };
  84945. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84946. var impostorObject = impostor.object;
  84947. this._prepareCylinder();
  84948. this._cylinder.position = this._cylinderPosition;
  84949. return this._cylinder.intersectsMesh(impostorObject, true);
  84950. };
  84951. return PhysicsVortexEvent;
  84952. }());
  84953. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84954. /***** Enums *****/
  84955. /**
  84956. * The strenght of the force in correspondence to the distance of the affected object
  84957. */
  84958. var PhysicsRadialImpulseFalloff;
  84959. (function (PhysicsRadialImpulseFalloff) {
  84960. /** Defines that impulse is constant in strength across it's whole radius */
  84961. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84962. /** DEfines that impulse gets weaker if it's further from the origin */
  84963. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84964. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84965. /**
  84966. * The strenght of the force in correspondence to the distance of the affected object
  84967. */
  84968. var PhysicsUpdraftMode;
  84969. (function (PhysicsUpdraftMode) {
  84970. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84971. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84972. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84973. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84974. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84975. })(BABYLON || (BABYLON = {}));
  84976. //# sourceMappingURL=babylon.physicsHelper.js.map
  84977. var BABYLON;
  84978. (function (BABYLON) {
  84979. var CannonJSPlugin = /** @class */ (function () {
  84980. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84981. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84982. if (iterations === void 0) { iterations = 10; }
  84983. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84984. this.name = "CannonJSPlugin";
  84985. this._physicsMaterials = new Array();
  84986. this._fixedTimeStep = 1 / 60;
  84987. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84988. this.BJSCANNON = CANNON;
  84989. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84990. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84991. this._tmpPosition = BABYLON.Vector3.Zero();
  84992. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84993. this._tmpUnityRotation = new BABYLON.Quaternion();
  84994. if (!this.isSupported()) {
  84995. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84996. return;
  84997. }
  84998. this._extendNamespace();
  84999. this.world = new this.BJSCANNON.World();
  85000. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85001. this.world.solver.iterations = iterations;
  85002. }
  85003. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85004. this.world.gravity.copy(gravity);
  85005. };
  85006. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85007. this._fixedTimeStep = timeStep;
  85008. };
  85009. CannonJSPlugin.prototype.getTimeStep = function () {
  85010. return this._fixedTimeStep;
  85011. };
  85012. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85013. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85014. };
  85015. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85016. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85017. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85018. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85019. };
  85020. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85021. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85022. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85023. impostor.physicsBody.applyForce(impulse, worldPoint);
  85024. };
  85025. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85026. //parent-child relationship. Does this impostor has a parent impostor?
  85027. if (impostor.parent) {
  85028. if (impostor.physicsBody) {
  85029. this.removePhysicsBody(impostor);
  85030. //TODO is that needed?
  85031. impostor.forceUpdate();
  85032. }
  85033. return;
  85034. }
  85035. //should a new body be created for this impostor?
  85036. if (impostor.isBodyInitRequired()) {
  85037. var shape = this._createShape(impostor);
  85038. //unregister events, if body is being changed
  85039. var oldBody = impostor.physicsBody;
  85040. if (oldBody) {
  85041. this.removePhysicsBody(impostor);
  85042. }
  85043. //create the body and material
  85044. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85045. var bodyCreationObject = {
  85046. mass: impostor.getParam("mass"),
  85047. material: material
  85048. };
  85049. // A simple extend, in case native options were used.
  85050. var nativeOptions = impostor.getParam("nativeOptions");
  85051. for (var key in nativeOptions) {
  85052. if (nativeOptions.hasOwnProperty(key)) {
  85053. bodyCreationObject[key] = nativeOptions[key];
  85054. }
  85055. }
  85056. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85057. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85058. this.world.addEventListener("preStep", impostor.beforeStep);
  85059. this.world.addEventListener("postStep", impostor.afterStep);
  85060. impostor.physicsBody.addShape(shape);
  85061. this.world.add(impostor.physicsBody);
  85062. //try to keep the body moving in the right direction by taking old properties.
  85063. //Should be tested!
  85064. if (oldBody) {
  85065. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85066. impostor.physicsBody[param].copy(oldBody[param]);
  85067. });
  85068. }
  85069. this._processChildMeshes(impostor);
  85070. }
  85071. //now update the body's transformation
  85072. this._updatePhysicsBodyTransformation(impostor);
  85073. };
  85074. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85075. var _this = this;
  85076. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85077. var currentRotation = mainImpostor.object.rotationQuaternion;
  85078. if (meshChildren.length) {
  85079. var processMesh = function (localPosition, mesh) {
  85080. if (!currentRotation || !mesh.rotationQuaternion) {
  85081. return;
  85082. }
  85083. var childImpostor = mesh.getPhysicsImpostor();
  85084. if (childImpostor) {
  85085. var parent = childImpostor.parent;
  85086. if (parent !== mainImpostor) {
  85087. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85088. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85089. if (childImpostor.physicsBody) {
  85090. _this.removePhysicsBody(childImpostor);
  85091. childImpostor.physicsBody = null;
  85092. }
  85093. childImpostor.parent = mainImpostor;
  85094. childImpostor.resetUpdateFlags();
  85095. 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));
  85096. //Add the mass of the children.
  85097. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85098. }
  85099. }
  85100. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85101. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85102. };
  85103. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85104. }
  85105. };
  85106. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85107. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85108. this.world.removeEventListener("preStep", impostor.beforeStep);
  85109. this.world.removeEventListener("postStep", impostor.afterStep);
  85110. this.world.remove(impostor.physicsBody);
  85111. };
  85112. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85113. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85114. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85115. if (!mainBody || !connectedBody) {
  85116. return;
  85117. }
  85118. var constraint;
  85119. var jointData = impostorJoint.joint.jointData;
  85120. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85121. var constraintData = {
  85122. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85123. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85124. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85125. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85126. maxForce: jointData.nativeParams.maxForce,
  85127. collideConnected: !!jointData.collision
  85128. };
  85129. switch (impostorJoint.joint.type) {
  85130. case BABYLON.PhysicsJoint.HingeJoint:
  85131. case BABYLON.PhysicsJoint.Hinge2Joint:
  85132. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85133. break;
  85134. case BABYLON.PhysicsJoint.DistanceJoint:
  85135. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85136. break;
  85137. case BABYLON.PhysicsJoint.SpringJoint:
  85138. var springData = jointData;
  85139. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85140. restLength: springData.length,
  85141. stiffness: springData.stiffness,
  85142. damping: springData.damping,
  85143. localAnchorA: constraintData.pivotA,
  85144. localAnchorB: constraintData.pivotB
  85145. });
  85146. break;
  85147. case BABYLON.PhysicsJoint.LockJoint:
  85148. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85149. break;
  85150. case BABYLON.PhysicsJoint.PointToPointJoint:
  85151. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85152. default:
  85153. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85154. break;
  85155. }
  85156. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85157. constraint.collideConnected = !!jointData.collision;
  85158. impostorJoint.joint.physicsJoint = constraint;
  85159. //don't add spring as constraint, as it is not one.
  85160. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85161. this.world.addConstraint(constraint);
  85162. }
  85163. else {
  85164. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85165. constraint.applyForce();
  85166. });
  85167. }
  85168. };
  85169. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85170. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85171. };
  85172. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85173. var index;
  85174. var mat;
  85175. for (index = 0; index < this._physicsMaterials.length; index++) {
  85176. mat = this._physicsMaterials[index];
  85177. if (mat.friction === friction && mat.restitution === restitution) {
  85178. return mat;
  85179. }
  85180. }
  85181. var currentMat = new this.BJSCANNON.Material(name);
  85182. currentMat.friction = friction;
  85183. currentMat.restitution = restitution;
  85184. this._physicsMaterials.push(currentMat);
  85185. return currentMat;
  85186. };
  85187. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85188. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85189. };
  85190. CannonJSPlugin.prototype._createShape = function (impostor) {
  85191. var object = impostor.object;
  85192. var returnValue;
  85193. var extendSize = impostor.getObjectExtendSize();
  85194. switch (impostor.type) {
  85195. case BABYLON.PhysicsImpostor.SphereImpostor:
  85196. var radiusX = extendSize.x;
  85197. var radiusY = extendSize.y;
  85198. var radiusZ = extendSize.z;
  85199. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85200. break;
  85201. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85202. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85203. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85204. break;
  85205. case BABYLON.PhysicsImpostor.BoxImpostor:
  85206. var box = extendSize.scale(0.5);
  85207. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85208. break;
  85209. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85210. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85211. returnValue = new this.BJSCANNON.Plane();
  85212. break;
  85213. case BABYLON.PhysicsImpostor.MeshImpostor:
  85214. // should transform the vertex data to world coordinates!!
  85215. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85216. var rawFaces = object.getIndices ? object.getIndices() : [];
  85217. if (!rawVerts)
  85218. return;
  85219. // get only scale! so the object could transform correctly.
  85220. var oldPosition = object.position.clone();
  85221. var oldRotation = object.rotation && object.rotation.clone();
  85222. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85223. object.position.copyFromFloats(0, 0, 0);
  85224. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85225. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85226. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85227. var transform = object.computeWorldMatrix(true);
  85228. // convert rawVerts to object space
  85229. var temp = new Array();
  85230. var index;
  85231. for (index = 0; index < rawVerts.length; index += 3) {
  85232. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85233. }
  85234. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85235. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85236. //now set back the transformation!
  85237. object.position.copyFrom(oldPosition);
  85238. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85239. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85240. break;
  85241. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85242. var oldPosition2 = object.position.clone();
  85243. var oldRotation2 = object.rotation && object.rotation.clone();
  85244. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85245. object.position.copyFromFloats(0, 0, 0);
  85246. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85247. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85248. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85249. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85250. returnValue = this._createHeightmap(object);
  85251. object.position.copyFrom(oldPosition2);
  85252. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85253. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85254. object.computeWorldMatrix(true);
  85255. break;
  85256. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85257. returnValue = new this.BJSCANNON.Particle();
  85258. break;
  85259. }
  85260. return returnValue;
  85261. };
  85262. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85263. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85264. var transform = object.computeWorldMatrix(true);
  85265. // convert rawVerts to object space
  85266. var temp = new Array();
  85267. var index;
  85268. for (index = 0; index < pos.length; index += 3) {
  85269. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85270. }
  85271. pos = temp;
  85272. var matrix = new Array();
  85273. //For now pointDepth will not be used and will be automatically calculated.
  85274. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85275. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85276. var boundingInfo = object.getBoundingInfo();
  85277. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85278. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85279. var elementSize = dim * 2 / arraySize;
  85280. for (var i = 0; i < pos.length; i = i + 3) {
  85281. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85282. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85283. var y = -pos[i + 2] + minY;
  85284. if (!matrix[x]) {
  85285. matrix[x] = [];
  85286. }
  85287. if (!matrix[x][z]) {
  85288. matrix[x][z] = y;
  85289. }
  85290. matrix[x][z] = Math.max(y, matrix[x][z]);
  85291. }
  85292. for (var x = 0; x <= arraySize; ++x) {
  85293. if (!matrix[x]) {
  85294. var loc = 1;
  85295. while (!matrix[(x + loc) % arraySize]) {
  85296. loc++;
  85297. }
  85298. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85299. //console.log("missing x", x);
  85300. }
  85301. for (var z = 0; z <= arraySize; ++z) {
  85302. if (!matrix[x][z]) {
  85303. var loc = 1;
  85304. var newValue;
  85305. while (newValue === undefined) {
  85306. newValue = matrix[x][(z + loc++) % arraySize];
  85307. }
  85308. matrix[x][z] = newValue;
  85309. }
  85310. }
  85311. }
  85312. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85313. elementSize: elementSize
  85314. });
  85315. //For future reference, needed for body transformation
  85316. shape.minY = minY;
  85317. return shape;
  85318. };
  85319. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85320. var object = impostor.object;
  85321. //make sure it is updated...
  85322. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85323. // The delta between the mesh position and the mesh bounding box center
  85324. var bInfo = object.getBoundingInfo();
  85325. if (!bInfo)
  85326. return;
  85327. var center = impostor.getObjectCenter();
  85328. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85329. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85330. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85331. this._tmpPosition.copyFrom(center);
  85332. var quaternion = object.rotationQuaternion;
  85333. if (!quaternion) {
  85334. return;
  85335. }
  85336. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85337. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85338. //-90 DEG in X, precalculated
  85339. quaternion = quaternion.multiply(this._minus90X);
  85340. //Invert! (Precalculated, 90 deg in X)
  85341. //No need to clone. this will never change.
  85342. impostor.setDeltaRotation(this._plus90X);
  85343. }
  85344. //If it is a heightfield, if should be centered.
  85345. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85346. var mesh = object;
  85347. var boundingInfo = mesh.getBoundingInfo();
  85348. //calculate the correct body position:
  85349. var rotationQuaternion = mesh.rotationQuaternion;
  85350. mesh.rotationQuaternion = this._tmpUnityRotation;
  85351. mesh.computeWorldMatrix(true);
  85352. //get original center with no rotation
  85353. var c = center.clone();
  85354. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85355. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85356. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85357. mesh.setPreTransformMatrix(p);
  85358. mesh.computeWorldMatrix(true);
  85359. //calculate the translation
  85360. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85361. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85362. //add it inverted to the delta
  85363. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85364. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85365. //rotation is back
  85366. mesh.rotationQuaternion = rotationQuaternion;
  85367. mesh.setPreTransformMatrix(oldPivot);
  85368. mesh.computeWorldMatrix(true);
  85369. }
  85370. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85371. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85372. //this._tmpPosition.copyFrom(object.position);
  85373. }
  85374. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85375. //Now update the impostor object
  85376. impostor.physicsBody.position.copy(this._tmpPosition);
  85377. impostor.physicsBody.quaternion.copy(quaternion);
  85378. };
  85379. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85380. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85381. if (impostor.object.rotationQuaternion) {
  85382. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85383. }
  85384. };
  85385. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85386. impostor.physicsBody.position.copy(newPosition);
  85387. impostor.physicsBody.quaternion.copy(newRotation);
  85388. };
  85389. CannonJSPlugin.prototype.isSupported = function () {
  85390. return this.BJSCANNON !== undefined;
  85391. };
  85392. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85393. impostor.physicsBody.velocity.copy(velocity);
  85394. };
  85395. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85396. impostor.physicsBody.angularVelocity.copy(velocity);
  85397. };
  85398. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85399. var v = impostor.physicsBody.velocity;
  85400. if (!v) {
  85401. return null;
  85402. }
  85403. return new BABYLON.Vector3(v.x, v.y, v.z);
  85404. };
  85405. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85406. var v = impostor.physicsBody.angularVelocity;
  85407. if (!v) {
  85408. return null;
  85409. }
  85410. return new BABYLON.Vector3(v.x, v.y, v.z);
  85411. };
  85412. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85413. impostor.physicsBody.mass = mass;
  85414. impostor.physicsBody.updateMassProperties();
  85415. };
  85416. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85417. return impostor.physicsBody.mass;
  85418. };
  85419. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85420. return impostor.physicsBody.material.friction;
  85421. };
  85422. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85423. impostor.physicsBody.material.friction = friction;
  85424. };
  85425. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85426. return impostor.physicsBody.material.restitution;
  85427. };
  85428. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85429. impostor.physicsBody.material.restitution = restitution;
  85430. };
  85431. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85432. impostor.physicsBody.sleep();
  85433. };
  85434. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85435. impostor.physicsBody.wakeUp();
  85436. };
  85437. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85438. joint.physicsJoint.distance = maxDistance;
  85439. };
  85440. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85441. // if (!motorIndex) {
  85442. // joint.physicsJoint.enableMotor();
  85443. // }
  85444. // }
  85445. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85446. // if (!motorIndex) {
  85447. // joint.physicsJoint.disableMotor();
  85448. // }
  85449. // }
  85450. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85451. if (!motorIndex) {
  85452. joint.physicsJoint.enableMotor();
  85453. joint.physicsJoint.setMotorSpeed(speed);
  85454. if (maxForce) {
  85455. this.setLimit(joint, maxForce);
  85456. }
  85457. }
  85458. };
  85459. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85460. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85461. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85462. };
  85463. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85464. var body = impostor.physicsBody;
  85465. mesh.position.x = body.position.x;
  85466. mesh.position.y = body.position.y;
  85467. mesh.position.z = body.position.z;
  85468. if (mesh.rotationQuaternion) {
  85469. mesh.rotationQuaternion.x = body.quaternion.x;
  85470. mesh.rotationQuaternion.y = body.quaternion.y;
  85471. mesh.rotationQuaternion.z = body.quaternion.z;
  85472. mesh.rotationQuaternion.w = body.quaternion.w;
  85473. }
  85474. };
  85475. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85476. var shape = impostor.physicsBody.shapes[0];
  85477. return shape.boundingSphereRadius;
  85478. };
  85479. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85480. var shape = impostor.physicsBody.shapes[0];
  85481. result.x = shape.halfExtents.x * 2;
  85482. result.y = shape.halfExtents.y * 2;
  85483. result.z = shape.halfExtents.z * 2;
  85484. };
  85485. CannonJSPlugin.prototype.dispose = function () {
  85486. };
  85487. CannonJSPlugin.prototype._extendNamespace = function () {
  85488. //this will force cannon to execute at least one step when using interpolation
  85489. var step_tmp1 = new this.BJSCANNON.Vec3();
  85490. var Engine = this.BJSCANNON;
  85491. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85492. maxSubSteps = maxSubSteps || 10;
  85493. timeSinceLastCalled = timeSinceLastCalled || 0;
  85494. if (timeSinceLastCalled === 0) {
  85495. this.internalStep(dt);
  85496. this.time += dt;
  85497. }
  85498. else {
  85499. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85500. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85501. var t0 = performance.now();
  85502. for (var i = 0; i !== internalSteps; i++) {
  85503. this.internalStep(dt);
  85504. if (performance.now() - t0 > dt * 1000) {
  85505. break;
  85506. }
  85507. }
  85508. this.time += timeSinceLastCalled;
  85509. var h = this.time % dt;
  85510. var h_div_dt = h / dt;
  85511. var interpvelo = step_tmp1;
  85512. var bodies = this.bodies;
  85513. for (var j = 0; j !== bodies.length; j++) {
  85514. var b = bodies[j];
  85515. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85516. b.position.vsub(b.previousPosition, interpvelo);
  85517. interpvelo.scale(h_div_dt, interpvelo);
  85518. b.position.vadd(interpvelo, b.interpolatedPosition);
  85519. }
  85520. else {
  85521. b.interpolatedPosition.copy(b.position);
  85522. b.interpolatedQuaternion.copy(b.quaternion);
  85523. }
  85524. }
  85525. }
  85526. };
  85527. };
  85528. return CannonJSPlugin;
  85529. }());
  85530. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85531. })(BABYLON || (BABYLON = {}));
  85532. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85533. var BABYLON;
  85534. (function (BABYLON) {
  85535. var OimoJSPlugin = /** @class */ (function () {
  85536. function OimoJSPlugin(iterations) {
  85537. this.name = "OimoJSPlugin";
  85538. this._tmpImpostorsArray = [];
  85539. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85540. this.BJSOIMO = OIMO;
  85541. this.world = new this.BJSOIMO.World({
  85542. iterations: iterations
  85543. });
  85544. this.world.clear();
  85545. }
  85546. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85547. this.world.gravity.copy(gravity);
  85548. };
  85549. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85550. this.world.timeStep = timeStep;
  85551. };
  85552. OimoJSPlugin.prototype.getTimeStep = function () {
  85553. return this.world.timeStep;
  85554. };
  85555. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85556. var _this = this;
  85557. impostors.forEach(function (impostor) {
  85558. impostor.beforeStep();
  85559. });
  85560. this.world.step();
  85561. impostors.forEach(function (impostor) {
  85562. impostor.afterStep();
  85563. //update the ordered impostors array
  85564. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85565. });
  85566. //check for collisions
  85567. var contact = this.world.contacts;
  85568. while (contact !== null) {
  85569. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85570. contact = contact.next;
  85571. continue;
  85572. }
  85573. //is this body colliding with any other? get the impostor
  85574. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85575. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85576. if (!mainImpostor || !collidingImpostor) {
  85577. contact = contact.next;
  85578. continue;
  85579. }
  85580. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85581. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85582. contact = contact.next;
  85583. }
  85584. };
  85585. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85586. var mass = impostor.physicsBody.mass;
  85587. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85588. };
  85589. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85590. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85591. this.applyImpulse(impostor, force, contactPoint);
  85592. };
  85593. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85594. var _this = this;
  85595. //parent-child relationship. Does this impostor has a parent impostor?
  85596. if (impostor.parent) {
  85597. if (impostor.physicsBody) {
  85598. this.removePhysicsBody(impostor);
  85599. //TODO is that needed?
  85600. impostor.forceUpdate();
  85601. }
  85602. return;
  85603. }
  85604. if (impostor.isBodyInitRequired()) {
  85605. var bodyConfig = {
  85606. name: impostor.uniqueId,
  85607. //Oimo must have mass, also for static objects.
  85608. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85609. size: [],
  85610. type: [],
  85611. pos: [],
  85612. posShape: [],
  85613. rot: [],
  85614. rotShape: [],
  85615. move: impostor.getParam("mass") !== 0,
  85616. density: impostor.getParam("mass"),
  85617. friction: impostor.getParam("friction"),
  85618. restitution: impostor.getParam("restitution"),
  85619. //Supporting older versions of Oimo
  85620. world: this.world
  85621. };
  85622. var impostors = [impostor];
  85623. var addToArray = function (parent) {
  85624. if (!parent.getChildMeshes)
  85625. return;
  85626. parent.getChildMeshes().forEach(function (m) {
  85627. if (m.physicsImpostor) {
  85628. impostors.push(m.physicsImpostor);
  85629. //m.physicsImpostor._init();
  85630. }
  85631. });
  85632. };
  85633. addToArray(impostor.object);
  85634. var checkWithEpsilon_1 = function (value) {
  85635. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85636. };
  85637. impostors.forEach(function (i) {
  85638. if (!i.object.rotationQuaternion) {
  85639. return;
  85640. }
  85641. //get the correct bounding box
  85642. var oldQuaternion = i.object.rotationQuaternion;
  85643. var rot = oldQuaternion.toEulerAngles();
  85644. var extendSize = i.getObjectExtendSize();
  85645. var radToDeg = 57.295779513082320876;
  85646. if (i === impostor) {
  85647. var center = impostor.getObjectCenter();
  85648. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85649. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85650. //Can also use Array.prototype.push.apply
  85651. bodyConfig.pos.push(center.x);
  85652. bodyConfig.pos.push(center.y);
  85653. bodyConfig.pos.push(center.z);
  85654. bodyConfig.posShape.push(0, 0, 0);
  85655. //tmp solution
  85656. bodyConfig.rot.push(rot.x * radToDeg);
  85657. bodyConfig.rot.push(rot.y * radToDeg);
  85658. bodyConfig.rot.push(rot.z * radToDeg);
  85659. bodyConfig.rotShape.push(0, 0, 0);
  85660. }
  85661. else {
  85662. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85663. bodyConfig.posShape.push(localPosition.x);
  85664. bodyConfig.posShape.push(localPosition.y);
  85665. bodyConfig.posShape.push(localPosition.z);
  85666. bodyConfig.pos.push(0, 0, 0);
  85667. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85668. bodyConfig.rot.push(0);
  85669. bodyConfig.rot.push(0);
  85670. bodyConfig.rot.push(0);
  85671. bodyConfig.rotShape.push(rot.x * radToDeg);
  85672. bodyConfig.rotShape.push(rot.y * radToDeg);
  85673. bodyConfig.rotShape.push(rot.z * radToDeg);
  85674. }
  85675. // register mesh
  85676. switch (i.type) {
  85677. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85678. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85679. case BABYLON.PhysicsImpostor.SphereImpostor:
  85680. var radiusX = extendSize.x;
  85681. var radiusY = extendSize.y;
  85682. var radiusZ = extendSize.z;
  85683. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85684. bodyConfig.type.push('sphere');
  85685. //due to the way oimo works with compounds, add 3 times
  85686. bodyConfig.size.push(size);
  85687. bodyConfig.size.push(size);
  85688. bodyConfig.size.push(size);
  85689. break;
  85690. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85691. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85692. var sizeY = checkWithEpsilon_1(extendSize.y);
  85693. bodyConfig.type.push('cylinder');
  85694. bodyConfig.size.push(sizeX);
  85695. bodyConfig.size.push(sizeY);
  85696. //due to the way oimo works with compounds, add one more value.
  85697. bodyConfig.size.push(sizeY);
  85698. break;
  85699. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85700. case BABYLON.PhysicsImpostor.BoxImpostor:
  85701. default:
  85702. var sizeX = checkWithEpsilon_1(extendSize.x);
  85703. var sizeY = checkWithEpsilon_1(extendSize.y);
  85704. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85705. bodyConfig.type.push('box');
  85706. //if (i === impostor) {
  85707. bodyConfig.size.push(sizeX);
  85708. bodyConfig.size.push(sizeY);
  85709. bodyConfig.size.push(sizeZ);
  85710. //} else {
  85711. // bodyConfig.size.push(0,0,0);
  85712. //}
  85713. break;
  85714. }
  85715. //actually not needed, but hey...
  85716. i.object.rotationQuaternion = oldQuaternion;
  85717. });
  85718. impostor.physicsBody = this.world.add(bodyConfig);
  85719. }
  85720. else {
  85721. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85722. }
  85723. impostor.setDeltaPosition(this._tmpPositionVector);
  85724. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85725. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85726. };
  85727. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85728. //impostor.physicsBody.dispose();
  85729. //Same as : (older oimo versions)
  85730. this.world.removeRigidBody(impostor.physicsBody);
  85731. };
  85732. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85733. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85734. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85735. if (!mainBody || !connectedBody) {
  85736. return;
  85737. }
  85738. var jointData = impostorJoint.joint.jointData;
  85739. var options = jointData.nativeParams || {};
  85740. var type;
  85741. var nativeJointData = {
  85742. body1: mainBody,
  85743. body2: connectedBody,
  85744. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85745. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85746. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85747. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85748. min: options.min,
  85749. max: options.max,
  85750. collision: options.collision || jointData.collision,
  85751. spring: options.spring,
  85752. //supporting older version of Oimo
  85753. world: this.world
  85754. };
  85755. switch (impostorJoint.joint.type) {
  85756. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85757. type = "jointBall";
  85758. break;
  85759. case BABYLON.PhysicsJoint.SpringJoint:
  85760. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85761. var springData = jointData;
  85762. nativeJointData.min = springData.length || nativeJointData.min;
  85763. //Max should also be set, just make sure it is at least min
  85764. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85765. case BABYLON.PhysicsJoint.DistanceJoint:
  85766. type = "jointDistance";
  85767. nativeJointData.max = jointData.maxDistance;
  85768. break;
  85769. case BABYLON.PhysicsJoint.PrismaticJoint:
  85770. type = "jointPrisme";
  85771. break;
  85772. case BABYLON.PhysicsJoint.SliderJoint:
  85773. type = "jointSlide";
  85774. break;
  85775. case BABYLON.PhysicsJoint.WheelJoint:
  85776. type = "jointWheel";
  85777. break;
  85778. case BABYLON.PhysicsJoint.HingeJoint:
  85779. default:
  85780. type = "jointHinge";
  85781. break;
  85782. }
  85783. nativeJointData.type = type;
  85784. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85785. };
  85786. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85787. //Bug in Oimo prevents us from disposing a joint in the playground
  85788. //joint.joint.physicsJoint.dispose();
  85789. //So we will bruteforce it!
  85790. try {
  85791. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85792. }
  85793. catch (e) {
  85794. BABYLON.Tools.Warn(e);
  85795. }
  85796. };
  85797. OimoJSPlugin.prototype.isSupported = function () {
  85798. return this.BJSOIMO !== undefined;
  85799. };
  85800. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85801. if (!impostor.physicsBody.sleeping) {
  85802. //TODO check that
  85803. /*if (impostor.physicsBody.shapes.next) {
  85804. var parentShape = this._getLastShape(impostor.physicsBody);
  85805. impostor.object.position.copyFrom(parentShape.position);
  85806. console.log(parentShape.position);
  85807. } else {*/
  85808. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85809. //}
  85810. if (impostor.object.rotationQuaternion) {
  85811. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85812. }
  85813. }
  85814. };
  85815. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85816. var body = impostor.physicsBody;
  85817. body.position.copy(newPosition);
  85818. body.orientation.copy(newRotation);
  85819. body.syncShapes();
  85820. body.awake();
  85821. };
  85822. /*private _getLastShape(body: any): any {
  85823. var lastShape = body.shapes;
  85824. while (lastShape.next) {
  85825. lastShape = lastShape.next;
  85826. }
  85827. return lastShape;
  85828. }*/
  85829. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85830. impostor.physicsBody.linearVelocity.copy(velocity);
  85831. };
  85832. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85833. impostor.physicsBody.angularVelocity.copy(velocity);
  85834. };
  85835. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85836. var v = impostor.physicsBody.linearVelocity;
  85837. if (!v) {
  85838. return null;
  85839. }
  85840. return new BABYLON.Vector3(v.x, v.y, v.z);
  85841. };
  85842. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85843. var v = impostor.physicsBody.angularVelocity;
  85844. if (!v) {
  85845. return null;
  85846. }
  85847. return new BABYLON.Vector3(v.x, v.y, v.z);
  85848. };
  85849. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85850. var staticBody = mass === 0;
  85851. //this will actually set the body's density and not its mass.
  85852. //But this is how oimo treats the mass variable.
  85853. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85854. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85855. };
  85856. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85857. return impostor.physicsBody.shapes.density;
  85858. };
  85859. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85860. return impostor.physicsBody.shapes.friction;
  85861. };
  85862. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85863. impostor.physicsBody.shapes.friction = friction;
  85864. };
  85865. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85866. return impostor.physicsBody.shapes.restitution;
  85867. };
  85868. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85869. impostor.physicsBody.shapes.restitution = restitution;
  85870. };
  85871. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85872. impostor.physicsBody.sleep();
  85873. };
  85874. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85875. impostor.physicsBody.awake();
  85876. };
  85877. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85878. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85879. if (minDistance !== void 0) {
  85880. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85881. }
  85882. };
  85883. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85884. //TODO separate rotational and transational motors.
  85885. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85886. if (motor) {
  85887. motor.setMotor(speed, maxForce);
  85888. }
  85889. };
  85890. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85891. //TODO separate rotational and transational motors.
  85892. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85893. if (motor) {
  85894. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85895. }
  85896. };
  85897. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85898. var body = impostor.physicsBody;
  85899. mesh.position.x = body.position.x;
  85900. mesh.position.y = body.position.y;
  85901. mesh.position.z = body.position.z;
  85902. if (mesh.rotationQuaternion) {
  85903. mesh.rotationQuaternion.x = body.orientation.x;
  85904. mesh.rotationQuaternion.y = body.orientation.y;
  85905. mesh.rotationQuaternion.z = body.orientation.z;
  85906. mesh.rotationQuaternion.w = body.orientation.s;
  85907. }
  85908. };
  85909. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85910. return impostor.physicsBody.shapes.radius;
  85911. };
  85912. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85913. var shape = impostor.physicsBody.shapes;
  85914. result.x = shape.halfWidth * 2;
  85915. result.y = shape.halfHeight * 2;
  85916. result.z = shape.halfDepth * 2;
  85917. };
  85918. OimoJSPlugin.prototype.dispose = function () {
  85919. this.world.clear();
  85920. };
  85921. return OimoJSPlugin;
  85922. }());
  85923. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85924. })(BABYLON || (BABYLON = {}));
  85925. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85926. var BABYLON;
  85927. (function (BABYLON) {
  85928. /*
  85929. * Based on jsTGALoader - Javascript loader for TGA file
  85930. * By Vincent Thibault
  85931. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85932. */
  85933. var TGATools = /** @class */ (function () {
  85934. function TGATools() {
  85935. }
  85936. TGATools.GetTGAHeader = function (data) {
  85937. var offset = 0;
  85938. var header = {
  85939. id_length: data[offset++],
  85940. colormap_type: data[offset++],
  85941. image_type: data[offset++],
  85942. colormap_index: data[offset++] | data[offset++] << 8,
  85943. colormap_length: data[offset++] | data[offset++] << 8,
  85944. colormap_size: data[offset++],
  85945. origin: [
  85946. data[offset++] | data[offset++] << 8,
  85947. data[offset++] | data[offset++] << 8
  85948. ],
  85949. width: data[offset++] | data[offset++] << 8,
  85950. height: data[offset++] | data[offset++] << 8,
  85951. pixel_size: data[offset++],
  85952. flags: data[offset++]
  85953. };
  85954. return header;
  85955. };
  85956. TGATools.UploadContent = function (gl, data) {
  85957. // Not enough data to contain header ?
  85958. if (data.length < 19) {
  85959. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85960. return;
  85961. }
  85962. // Read Header
  85963. var offset = 18;
  85964. var header = TGATools.GetTGAHeader(data);
  85965. // Assume it's a valid Targa file.
  85966. if (header.id_length + offset > data.length) {
  85967. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85968. return;
  85969. }
  85970. // Skip not needed data
  85971. offset += header.id_length;
  85972. var use_rle = false;
  85973. var use_pal = false;
  85974. var use_grey = false;
  85975. // Get some informations.
  85976. switch (header.image_type) {
  85977. case TGATools._TYPE_RLE_INDEXED:
  85978. use_rle = true;
  85979. case TGATools._TYPE_INDEXED:
  85980. use_pal = true;
  85981. break;
  85982. case TGATools._TYPE_RLE_RGB:
  85983. use_rle = true;
  85984. case TGATools._TYPE_RGB:
  85985. // use_rgb = true;
  85986. break;
  85987. case TGATools._TYPE_RLE_GREY:
  85988. use_rle = true;
  85989. case TGATools._TYPE_GREY:
  85990. use_grey = true;
  85991. break;
  85992. }
  85993. var pixel_data;
  85994. // var numAlphaBits = header.flags & 0xf;
  85995. var pixel_size = header.pixel_size >> 3;
  85996. var pixel_total = header.width * header.height * pixel_size;
  85997. // Read palettes
  85998. var palettes;
  85999. if (use_pal) {
  86000. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86001. }
  86002. // Read LRE
  86003. if (use_rle) {
  86004. pixel_data = new Uint8Array(pixel_total);
  86005. var c, count, i;
  86006. var localOffset = 0;
  86007. var pixels = new Uint8Array(pixel_size);
  86008. while (offset < pixel_total && localOffset < pixel_total) {
  86009. c = data[offset++];
  86010. count = (c & 0x7f) + 1;
  86011. // RLE pixels
  86012. if (c & 0x80) {
  86013. // Bind pixel tmp array
  86014. for (i = 0; i < pixel_size; ++i) {
  86015. pixels[i] = data[offset++];
  86016. }
  86017. // Copy pixel array
  86018. for (i = 0; i < count; ++i) {
  86019. pixel_data.set(pixels, localOffset + i * pixel_size);
  86020. }
  86021. localOffset += pixel_size * count;
  86022. }
  86023. // Raw pixels
  86024. else {
  86025. count *= pixel_size;
  86026. for (i = 0; i < count; ++i) {
  86027. pixel_data[localOffset + i] = data[offset++];
  86028. }
  86029. localOffset += count;
  86030. }
  86031. }
  86032. }
  86033. // RAW Pixels
  86034. else {
  86035. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86036. }
  86037. // Load to texture
  86038. var x_start, y_start, x_step, y_step, y_end, x_end;
  86039. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86040. default:
  86041. case TGATools._ORIGIN_UL:
  86042. x_start = 0;
  86043. x_step = 1;
  86044. x_end = header.width;
  86045. y_start = 0;
  86046. y_step = 1;
  86047. y_end = header.height;
  86048. break;
  86049. case TGATools._ORIGIN_BL:
  86050. x_start = 0;
  86051. x_step = 1;
  86052. x_end = header.width;
  86053. y_start = header.height - 1;
  86054. y_step = -1;
  86055. y_end = -1;
  86056. break;
  86057. case TGATools._ORIGIN_UR:
  86058. x_start = header.width - 1;
  86059. x_step = -1;
  86060. x_end = -1;
  86061. y_start = 0;
  86062. y_step = 1;
  86063. y_end = header.height;
  86064. break;
  86065. case TGATools._ORIGIN_BR:
  86066. x_start = header.width - 1;
  86067. x_step = -1;
  86068. x_end = -1;
  86069. y_start = header.height - 1;
  86070. y_step = -1;
  86071. y_end = -1;
  86072. break;
  86073. }
  86074. // Load the specify method
  86075. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86076. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86077. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86078. };
  86079. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86080. var image = pixel_data, colormap = palettes;
  86081. var width = header.width, height = header.height;
  86082. var color, i = 0, x, y;
  86083. var imageData = new Uint8Array(width * height * 4);
  86084. for (y = y_start; y !== y_end; y += y_step) {
  86085. for (x = x_start; x !== x_end; x += x_step, i++) {
  86086. color = image[i];
  86087. imageData[(x + width * y) * 4 + 3] = 255;
  86088. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86089. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86090. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86091. }
  86092. }
  86093. return imageData;
  86094. };
  86095. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86096. var image = pixel_data;
  86097. var width = header.width, height = header.height;
  86098. var color, i = 0, x, y;
  86099. var imageData = new Uint8Array(width * height * 4);
  86100. for (y = y_start; y !== y_end; y += y_step) {
  86101. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86102. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86103. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86104. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86105. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86106. imageData[(x + width * y) * 4 + 0] = r;
  86107. imageData[(x + width * y) * 4 + 1] = g;
  86108. imageData[(x + width * y) * 4 + 2] = b;
  86109. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86110. }
  86111. }
  86112. return imageData;
  86113. };
  86114. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86115. var image = pixel_data;
  86116. var width = header.width, height = header.height;
  86117. var i = 0, x, y;
  86118. var imageData = new Uint8Array(width * height * 4);
  86119. for (y = y_start; y !== y_end; y += y_step) {
  86120. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86121. imageData[(x + width * y) * 4 + 3] = 255;
  86122. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86123. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86124. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86125. }
  86126. }
  86127. return imageData;
  86128. };
  86129. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86130. var image = pixel_data;
  86131. var width = header.width, height = header.height;
  86132. var i = 0, x, y;
  86133. var imageData = new Uint8Array(width * height * 4);
  86134. for (y = y_start; y !== y_end; y += y_step) {
  86135. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86136. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86137. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86138. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86139. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86140. }
  86141. }
  86142. return imageData;
  86143. };
  86144. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86145. var image = pixel_data;
  86146. var width = header.width, height = header.height;
  86147. var color, i = 0, x, y;
  86148. var imageData = new Uint8Array(width * height * 4);
  86149. for (y = y_start; y !== y_end; y += y_step) {
  86150. for (x = x_start; x !== x_end; x += x_step, i++) {
  86151. color = image[i];
  86152. imageData[(x + width * y) * 4 + 0] = color;
  86153. imageData[(x + width * y) * 4 + 1] = color;
  86154. imageData[(x + width * y) * 4 + 2] = color;
  86155. imageData[(x + width * y) * 4 + 3] = 255;
  86156. }
  86157. }
  86158. return imageData;
  86159. };
  86160. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86161. var image = pixel_data;
  86162. var width = header.width, height = header.height;
  86163. var i = 0, x, y;
  86164. var imageData = new Uint8Array(width * height * 4);
  86165. for (y = y_start; y !== y_end; y += y_step) {
  86166. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86167. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86168. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86169. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86170. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86171. }
  86172. }
  86173. return imageData;
  86174. };
  86175. //private static _TYPE_NO_DATA = 0;
  86176. TGATools._TYPE_INDEXED = 1;
  86177. TGATools._TYPE_RGB = 2;
  86178. TGATools._TYPE_GREY = 3;
  86179. TGATools._TYPE_RLE_INDEXED = 9;
  86180. TGATools._TYPE_RLE_RGB = 10;
  86181. TGATools._TYPE_RLE_GREY = 11;
  86182. TGATools._ORIGIN_MASK = 0x30;
  86183. TGATools._ORIGIN_SHIFT = 0x04;
  86184. TGATools._ORIGIN_BL = 0x00;
  86185. TGATools._ORIGIN_BR = 0x01;
  86186. TGATools._ORIGIN_UL = 0x02;
  86187. TGATools._ORIGIN_UR = 0x03;
  86188. return TGATools;
  86189. }());
  86190. BABYLON.TGATools = TGATools;
  86191. })(BABYLON || (BABYLON = {}));
  86192. //# sourceMappingURL=babylon.tga.js.map
  86193. var BABYLON;
  86194. (function (BABYLON) {
  86195. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86196. // All values and structures referenced from:
  86197. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86198. var DDS_MAGIC = 0x20534444;
  86199. var
  86200. //DDSD_CAPS = 0x1,
  86201. //DDSD_HEIGHT = 0x2,
  86202. //DDSD_WIDTH = 0x4,
  86203. //DDSD_PITCH = 0x8,
  86204. //DDSD_PIXELFORMAT = 0x1000,
  86205. DDSD_MIPMAPCOUNT = 0x20000;
  86206. //DDSD_LINEARSIZE = 0x80000,
  86207. //DDSD_DEPTH = 0x800000;
  86208. // var DDSCAPS_COMPLEX = 0x8,
  86209. // DDSCAPS_MIPMAP = 0x400000,
  86210. // DDSCAPS_TEXTURE = 0x1000;
  86211. var DDSCAPS2_CUBEMAP = 0x200;
  86212. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86213. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86214. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86215. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86216. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86217. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86218. // DDSCAPS2_VOLUME = 0x200000;
  86219. var
  86220. //DDPF_ALPHAPIXELS = 0x1,
  86221. //DDPF_ALPHA = 0x2,
  86222. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86223. //DDPF_YUV = 0x200,
  86224. DDPF_LUMINANCE = 0x20000;
  86225. function FourCCToInt32(value) {
  86226. return value.charCodeAt(0) +
  86227. (value.charCodeAt(1) << 8) +
  86228. (value.charCodeAt(2) << 16) +
  86229. (value.charCodeAt(3) << 24);
  86230. }
  86231. function Int32ToFourCC(value) {
  86232. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86233. }
  86234. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86235. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86236. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86237. var FOURCC_DX10 = FourCCToInt32("DX10");
  86238. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86239. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86240. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86241. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86242. var headerLengthInt = 31; // The header length in 32 bit ints
  86243. // Offsets into the header array
  86244. var off_magic = 0;
  86245. var off_size = 1;
  86246. var off_flags = 2;
  86247. var off_height = 3;
  86248. var off_width = 4;
  86249. var off_mipmapCount = 7;
  86250. var off_pfFlags = 20;
  86251. var off_pfFourCC = 21;
  86252. var off_RGBbpp = 22;
  86253. var off_RMask = 23;
  86254. var off_GMask = 24;
  86255. var off_BMask = 25;
  86256. var off_AMask = 26;
  86257. // var off_caps1 = 27;
  86258. var off_caps2 = 28;
  86259. // var off_caps3 = 29;
  86260. // var off_caps4 = 30;
  86261. var off_dxgiFormat = 32;
  86262. ;
  86263. var DDSTools = /** @class */ (function () {
  86264. function DDSTools() {
  86265. }
  86266. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86267. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86268. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86269. var mipmapCount = 1;
  86270. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86271. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86272. }
  86273. var fourCC = header[off_pfFourCC];
  86274. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86275. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86276. switch (fourCC) {
  86277. case FOURCC_D3DFMT_R16G16B16A16F:
  86278. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86279. break;
  86280. case FOURCC_D3DFMT_R32G32B32A32F:
  86281. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86282. break;
  86283. case FOURCC_DX10:
  86284. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86285. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86286. break;
  86287. }
  86288. }
  86289. return {
  86290. width: header[off_width],
  86291. height: header[off_height],
  86292. mipmapCount: mipmapCount,
  86293. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86294. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86295. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86296. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86297. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86298. dxgiFormat: dxgiFormat,
  86299. textureType: textureType
  86300. };
  86301. };
  86302. DDSTools._ToHalfFloat = function (value) {
  86303. if (!DDSTools._FloatView) {
  86304. DDSTools._FloatView = new Float32Array(1);
  86305. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86306. }
  86307. DDSTools._FloatView[0] = value;
  86308. var x = DDSTools._Int32View[0];
  86309. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86310. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86311. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86312. /* If zero, or denormal, or exponent underflows too much for a denormal
  86313. * half, return signed zero. */
  86314. if (e < 103) {
  86315. return bits;
  86316. }
  86317. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86318. if (e > 142) {
  86319. bits |= 0x7c00;
  86320. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86321. * not Inf, so make sure we set one mantissa bit too. */
  86322. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86323. return bits;
  86324. }
  86325. /* If exponent underflows but not too much, return a denormal */
  86326. if (e < 113) {
  86327. m |= 0x0800;
  86328. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86329. * to 1, which is OK. */
  86330. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86331. return bits;
  86332. }
  86333. bits |= ((e - 112) << 10) | (m >> 1);
  86334. bits += m & 1;
  86335. return bits;
  86336. };
  86337. DDSTools._FromHalfFloat = function (value) {
  86338. var s = (value & 0x8000) >> 15;
  86339. var e = (value & 0x7C00) >> 10;
  86340. var f = value & 0x03FF;
  86341. if (e === 0) {
  86342. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86343. }
  86344. else if (e == 0x1F) {
  86345. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86346. }
  86347. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86348. };
  86349. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86350. var destArray = new Float32Array(dataLength);
  86351. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86352. var index = 0;
  86353. for (var y = 0; y < height; y++) {
  86354. for (var x = 0; x < width; x++) {
  86355. var srcPos = (x + y * width) * 4;
  86356. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86357. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86358. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86359. if (DDSTools.StoreLODInAlphaChannel) {
  86360. destArray[index + 3] = lod;
  86361. }
  86362. else {
  86363. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86364. }
  86365. index += 4;
  86366. }
  86367. }
  86368. return destArray;
  86369. };
  86370. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86371. if (DDSTools.StoreLODInAlphaChannel) {
  86372. var destArray = new Uint16Array(dataLength);
  86373. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86374. var index = 0;
  86375. for (var y = 0; y < height; y++) {
  86376. for (var x = 0; x < width; x++) {
  86377. var srcPos = (x + y * width) * 4;
  86378. destArray[index] = srcData[srcPos];
  86379. destArray[index + 1] = srcData[srcPos + 1];
  86380. destArray[index + 2] = srcData[srcPos + 2];
  86381. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86382. index += 4;
  86383. }
  86384. }
  86385. return destArray;
  86386. }
  86387. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86388. };
  86389. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86390. if (DDSTools.StoreLODInAlphaChannel) {
  86391. var destArray = new Float32Array(dataLength);
  86392. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86393. var index = 0;
  86394. for (var y = 0; y < height; y++) {
  86395. for (var x = 0; x < width; x++) {
  86396. var srcPos = (x + y * width) * 4;
  86397. destArray[index] = srcData[srcPos];
  86398. destArray[index + 1] = srcData[srcPos + 1];
  86399. destArray[index + 2] = srcData[srcPos + 2];
  86400. destArray[index + 3] = lod;
  86401. index += 4;
  86402. }
  86403. }
  86404. return destArray;
  86405. }
  86406. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86407. };
  86408. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86409. var destArray = new Uint8Array(dataLength);
  86410. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86411. var index = 0;
  86412. for (var y = 0; y < height; y++) {
  86413. for (var x = 0; x < width; x++) {
  86414. var srcPos = (x + y * width) * 4;
  86415. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86416. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86417. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86418. if (DDSTools.StoreLODInAlphaChannel) {
  86419. destArray[index + 3] = lod;
  86420. }
  86421. else {
  86422. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86423. }
  86424. index += 4;
  86425. }
  86426. }
  86427. return destArray;
  86428. };
  86429. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86430. var destArray = new Uint8Array(dataLength);
  86431. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86432. var index = 0;
  86433. for (var y = 0; y < height; y++) {
  86434. for (var x = 0; x < width; x++) {
  86435. var srcPos = (x + y * width) * 4;
  86436. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86437. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86438. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86439. if (DDSTools.StoreLODInAlphaChannel) {
  86440. destArray[index + 3] = lod;
  86441. }
  86442. else {
  86443. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86444. }
  86445. index += 4;
  86446. }
  86447. }
  86448. return destArray;
  86449. };
  86450. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86451. var byteArray = new Uint8Array(dataLength);
  86452. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86453. var index = 0;
  86454. for (var y = 0; y < height; y++) {
  86455. for (var x = 0; x < width; x++) {
  86456. var srcPos = (x + y * width) * 4;
  86457. byteArray[index] = srcData[srcPos + rOffset];
  86458. byteArray[index + 1] = srcData[srcPos + gOffset];
  86459. byteArray[index + 2] = srcData[srcPos + bOffset];
  86460. byteArray[index + 3] = srcData[srcPos + aOffset];
  86461. index += 4;
  86462. }
  86463. }
  86464. return byteArray;
  86465. };
  86466. DDSTools._ExtractLongWordOrder = function (value) {
  86467. if (value === 0 || value === 255 || value === -16777216) {
  86468. return 0;
  86469. }
  86470. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86471. };
  86472. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86473. var byteArray = new Uint8Array(dataLength);
  86474. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86475. var index = 0;
  86476. for (var y = 0; y < height; y++) {
  86477. for (var x = 0; x < width; x++) {
  86478. var srcPos = (x + y * width) * 3;
  86479. byteArray[index] = srcData[srcPos + rOffset];
  86480. byteArray[index + 1] = srcData[srcPos + gOffset];
  86481. byteArray[index + 2] = srcData[srcPos + bOffset];
  86482. index += 3;
  86483. }
  86484. }
  86485. return byteArray;
  86486. };
  86487. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86488. var byteArray = new Uint8Array(dataLength);
  86489. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86490. var index = 0;
  86491. for (var y = 0; y < height; y++) {
  86492. for (var x = 0; x < width; x++) {
  86493. var srcPos = (x + y * width);
  86494. byteArray[index] = srcData[srcPos];
  86495. index++;
  86496. }
  86497. }
  86498. return byteArray;
  86499. };
  86500. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86501. if (lodIndex === void 0) { lodIndex = -1; }
  86502. var sphericalPolynomialFaces = null;
  86503. if (info.sphericalPolynomial) {
  86504. sphericalPolynomialFaces = new Array();
  86505. }
  86506. var ext = engine.getCaps().s3tc;
  86507. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86508. var fourCC, width, height, dataLength = 0, dataOffset;
  86509. var byteArray, mipmapCount, mip;
  86510. var internalFormat = 0;
  86511. var format = 0;
  86512. var blockBytes = 1;
  86513. if (header[off_magic] !== DDS_MAGIC) {
  86514. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86515. return;
  86516. }
  86517. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86518. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86519. return;
  86520. }
  86521. if (info.isCompressed && !ext) {
  86522. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86523. return;
  86524. }
  86525. var bpp = header[off_RGBbpp];
  86526. dataOffset = header[off_size] + 4;
  86527. var computeFormats = false;
  86528. if (info.isFourCC) {
  86529. fourCC = header[off_pfFourCC];
  86530. switch (fourCC) {
  86531. case FOURCC_DXT1:
  86532. blockBytes = 8;
  86533. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86534. break;
  86535. case FOURCC_DXT3:
  86536. blockBytes = 16;
  86537. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86538. break;
  86539. case FOURCC_DXT5:
  86540. blockBytes = 16;
  86541. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86542. break;
  86543. case FOURCC_D3DFMT_R16G16B16A16F:
  86544. computeFormats = true;
  86545. break;
  86546. case FOURCC_D3DFMT_R32G32B32A32F:
  86547. computeFormats = true;
  86548. break;
  86549. case FOURCC_DX10:
  86550. // There is an additionnal header so dataOffset need to be changed
  86551. dataOffset += 5 * 4; // 5 uints
  86552. var supported = false;
  86553. switch (info.dxgiFormat) {
  86554. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86555. computeFormats = true;
  86556. supported = true;
  86557. break;
  86558. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86559. info.isRGB = true;
  86560. info.isFourCC = false;
  86561. bpp = 32;
  86562. supported = true;
  86563. break;
  86564. }
  86565. if (supported) {
  86566. break;
  86567. }
  86568. default:
  86569. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86570. return;
  86571. }
  86572. }
  86573. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86574. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86575. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86576. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86577. if (computeFormats) {
  86578. format = engine._getWebGLTextureType(info.textureType);
  86579. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86580. }
  86581. mipmapCount = 1;
  86582. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86583. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86584. }
  86585. for (var face = 0; face < faces; face++) {
  86586. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86587. width = header[off_width];
  86588. height = header[off_height];
  86589. for (mip = 0; mip < mipmapCount; ++mip) {
  86590. if (lodIndex === -1 || lodIndex === mip) {
  86591. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86592. var i = (lodIndex === -1) ? mip : 0;
  86593. if (!info.isCompressed && info.isFourCC) {
  86594. dataLength = width * height * 4;
  86595. var floatArray = null;
  86596. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86597. if (bpp === 128) {
  86598. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86599. if (sphericalPolynomialFaces && i == 0) {
  86600. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86601. }
  86602. }
  86603. else if (bpp === 64) {
  86604. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86605. if (sphericalPolynomialFaces && i == 0) {
  86606. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86607. }
  86608. }
  86609. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86610. format = engine._getWebGLTextureType(info.textureType);
  86611. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86612. }
  86613. else {
  86614. if (bpp === 128) {
  86615. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86616. if (sphericalPolynomialFaces && i == 0) {
  86617. sphericalPolynomialFaces.push(floatArray);
  86618. }
  86619. }
  86620. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86621. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86622. if (sphericalPolynomialFaces && i == 0) {
  86623. sphericalPolynomialFaces.push(floatArray);
  86624. }
  86625. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86626. format = engine._getWebGLTextureType(info.textureType);
  86627. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86628. }
  86629. else { // 64
  86630. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86631. if (sphericalPolynomialFaces && i == 0) {
  86632. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86633. }
  86634. }
  86635. }
  86636. if (floatArray) {
  86637. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86638. }
  86639. }
  86640. else if (info.isRGB) {
  86641. if (bpp === 24) {
  86642. dataLength = width * height * 3;
  86643. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86644. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86645. }
  86646. else { // 32
  86647. dataLength = width * height * 4;
  86648. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86649. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86650. }
  86651. }
  86652. else if (info.isLuminance) {
  86653. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86654. var unpaddedRowSize = width;
  86655. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86656. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86657. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86658. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86659. }
  86660. else {
  86661. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86662. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86663. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86664. }
  86665. }
  86666. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86667. width *= 0.5;
  86668. height *= 0.5;
  86669. width = Math.max(1.0, width);
  86670. height = Math.max(1.0, height);
  86671. }
  86672. if (currentFace !== undefined) {
  86673. // Loading a single face
  86674. break;
  86675. }
  86676. }
  86677. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86678. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86679. size: header[off_width],
  86680. right: sphericalPolynomialFaces[0],
  86681. left: sphericalPolynomialFaces[1],
  86682. up: sphericalPolynomialFaces[2],
  86683. down: sphericalPolynomialFaces[3],
  86684. front: sphericalPolynomialFaces[4],
  86685. back: sphericalPolynomialFaces[5],
  86686. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86687. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86688. gammaSpace: false,
  86689. });
  86690. }
  86691. else {
  86692. info.sphericalPolynomial = undefined;
  86693. }
  86694. };
  86695. DDSTools.StoreLODInAlphaChannel = false;
  86696. return DDSTools;
  86697. }());
  86698. BABYLON.DDSTools = DDSTools;
  86699. })(BABYLON || (BABYLON = {}));
  86700. //# sourceMappingURL=babylon.dds.js.map
  86701. var BABYLON;
  86702. (function (BABYLON) {
  86703. /**
  86704. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86705. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86706. */
  86707. var KhronosTextureContainer = /** @class */ (function () {
  86708. /**
  86709. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86710. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86711. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86712. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86713. */
  86714. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86715. this.arrayBuffer = arrayBuffer;
  86716. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86717. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86718. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86719. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86720. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86721. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86722. BABYLON.Tools.Error("texture missing KTX identifier");
  86723. return;
  86724. }
  86725. // load the reset of the header in native 32 bit int
  86726. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86727. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86728. var oppositeEndianess = header[0] === 0x01020304;
  86729. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86730. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86731. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86732. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86733. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86734. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86735. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86736. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86737. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86738. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86739. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86740. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86741. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86742. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86743. if (this.glType !== 0) {
  86744. BABYLON.Tools.Error("only compressed formats currently supported");
  86745. return;
  86746. }
  86747. else {
  86748. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86749. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86750. }
  86751. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86752. BABYLON.Tools.Error("only 2D textures currently supported");
  86753. return;
  86754. }
  86755. if (this.numberOfArrayElements !== 0) {
  86756. BABYLON.Tools.Error("texture arrays not currently supported");
  86757. return;
  86758. }
  86759. if (this.numberOfFaces !== facesExpected) {
  86760. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86761. return;
  86762. }
  86763. // we now have a completely validated file, so could use existence of loadType as success
  86764. // would need to make this more elaborate & adjust checks above to support more than one load type
  86765. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86766. }
  86767. // not as fast hardware based, but will probably never need to use
  86768. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86769. return ((val & 0xFF) << 24)
  86770. | ((val & 0xFF00) << 8)
  86771. | ((val >> 8) & 0xFF00)
  86772. | ((val >> 24) & 0xFF);
  86773. };
  86774. /**
  86775. * It is assumed that the texture has already been created & is currently bound
  86776. */
  86777. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86778. switch (this.loadType) {
  86779. case KhronosTextureContainer.COMPRESSED_2D:
  86780. this._upload2DCompressedLevels(gl, loadMipmaps);
  86781. break;
  86782. case KhronosTextureContainer.TEX_2D:
  86783. case KhronosTextureContainer.COMPRESSED_3D:
  86784. case KhronosTextureContainer.TEX_3D:
  86785. }
  86786. };
  86787. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86788. // initialize width & height for level 1
  86789. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86790. var width = this.pixelWidth;
  86791. var height = this.pixelHeight;
  86792. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86793. for (var level = 0; level < mipmapCount; level++) {
  86794. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86795. for (var face = 0; face < this.numberOfFaces; face++) {
  86796. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86797. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86798. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86799. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86800. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86801. }
  86802. width = Math.max(1.0, width * 0.5);
  86803. height = Math.max(1.0, height * 0.5);
  86804. }
  86805. };
  86806. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86807. // load types
  86808. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86809. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86810. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86811. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86812. return KhronosTextureContainer;
  86813. }());
  86814. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86815. })(BABYLON || (BABYLON = {}));
  86816. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86817. var BABYLON;
  86818. (function (BABYLON) {
  86819. var Debug;
  86820. (function (Debug) {
  86821. /**
  86822. * Class used to render a debug view of a given skeleton
  86823. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86824. */
  86825. var SkeletonViewer = /** @class */ (function () {
  86826. /**
  86827. * Creates a new SkeletonViewer
  86828. * @param skeleton defines the skeleton to render
  86829. * @param mesh defines the mesh attached to the skeleton
  86830. * @param scene defines the hosting scene
  86831. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86832. * @param renderingGroupId defines the rendering group id to use with the viewer
  86833. */
  86834. function SkeletonViewer(
  86835. /** defines the skeleton to render */
  86836. skeleton,
  86837. /** defines the mesh attached to the skeleton */
  86838. mesh, scene,
  86839. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86840. autoUpdateBonesMatrices,
  86841. /** defines the rendering group id to use with the viewer */
  86842. renderingGroupId) {
  86843. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86844. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86845. this.skeleton = skeleton;
  86846. this.mesh = mesh;
  86847. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86848. this.renderingGroupId = renderingGroupId;
  86849. /** Gets or sets the color used to render the skeleton */
  86850. this.color = BABYLON.Color3.White();
  86851. this._debugLines = new Array();
  86852. this._isEnabled = false;
  86853. this._scene = scene;
  86854. this.update();
  86855. this._renderFunction = this.update.bind(this);
  86856. }
  86857. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86858. get: function () {
  86859. return this._isEnabled;
  86860. },
  86861. /** Gets or sets a boolean indicating if the viewer is enabled */
  86862. set: function (value) {
  86863. if (this._isEnabled === value) {
  86864. return;
  86865. }
  86866. this._isEnabled = value;
  86867. if (value) {
  86868. this._scene.registerBeforeRender(this._renderFunction);
  86869. }
  86870. else {
  86871. this._scene.unregisterBeforeRender(this._renderFunction);
  86872. }
  86873. },
  86874. enumerable: true,
  86875. configurable: true
  86876. });
  86877. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86878. if (x === void 0) { x = 0; }
  86879. if (y === void 0) { y = 0; }
  86880. if (z === void 0) { z = 0; }
  86881. var tmat = BABYLON.Tmp.Matrix[0];
  86882. var parentBone = bone.getParent();
  86883. tmat.copyFrom(bone.getLocalMatrix());
  86884. if (x !== 0 || y !== 0 || z !== 0) {
  86885. var tmat2 = BABYLON.Tmp.Matrix[1];
  86886. BABYLON.Matrix.IdentityToRef(tmat2);
  86887. tmat2.m[12] = x;
  86888. tmat2.m[13] = y;
  86889. tmat2.m[14] = z;
  86890. tmat2.multiplyToRef(tmat, tmat);
  86891. }
  86892. if (parentBone) {
  86893. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86894. }
  86895. tmat.multiplyToRef(meshMat, tmat);
  86896. position.x = tmat.m[12];
  86897. position.y = tmat.m[13];
  86898. position.z = tmat.m[14];
  86899. };
  86900. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86901. var len = bones.length;
  86902. var meshPos = this.mesh.position;
  86903. for (var i = 0; i < len; i++) {
  86904. var bone = bones[i];
  86905. var points = this._debugLines[i];
  86906. if (!points) {
  86907. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86908. this._debugLines[i] = points;
  86909. }
  86910. this._getBonePosition(points[0], bone, meshMat);
  86911. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86912. points[0].subtractInPlace(meshPos);
  86913. points[1].subtractInPlace(meshPos);
  86914. }
  86915. };
  86916. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86917. var len = bones.length;
  86918. var boneNum = 0;
  86919. var meshPos = this.mesh.position;
  86920. for (var i = len - 1; i >= 0; i--) {
  86921. var childBone = bones[i];
  86922. var parentBone = childBone.getParent();
  86923. if (!parentBone) {
  86924. continue;
  86925. }
  86926. var points = this._debugLines[boneNum];
  86927. if (!points) {
  86928. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86929. this._debugLines[boneNum] = points;
  86930. }
  86931. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86932. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86933. points[0].subtractInPlace(meshPos);
  86934. points[1].subtractInPlace(meshPos);
  86935. boneNum++;
  86936. }
  86937. };
  86938. /** Update the viewer to sync with current skeleton state */
  86939. SkeletonViewer.prototype.update = function () {
  86940. if (this.autoUpdateBonesMatrices) {
  86941. this.skeleton.computeAbsoluteTransforms();
  86942. }
  86943. if (this.skeleton.bones[0].length === undefined) {
  86944. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86945. }
  86946. else {
  86947. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86948. }
  86949. if (!this._debugMesh) {
  86950. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86951. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86952. }
  86953. else {
  86954. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86955. }
  86956. this._debugMesh.position.copyFrom(this.mesh.position);
  86957. this._debugMesh.color = this.color;
  86958. };
  86959. /** Release associated resources */
  86960. SkeletonViewer.prototype.dispose = function () {
  86961. if (this._debugMesh) {
  86962. this.isEnabled = false;
  86963. this._debugMesh.dispose();
  86964. this._debugMesh = null;
  86965. }
  86966. };
  86967. return SkeletonViewer;
  86968. }());
  86969. Debug.SkeletonViewer = SkeletonViewer;
  86970. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86971. })(BABYLON || (BABYLON = {}));
  86972. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86973. /**
  86974. * Module Debug contains the (visual) components to debug a scene correctly
  86975. */
  86976. var BABYLON;
  86977. (function (BABYLON) {
  86978. var Debug;
  86979. (function (Debug) {
  86980. /**
  86981. * The Axes viewer will show 3 axes in a specific point in space
  86982. */
  86983. var AxesViewer = /** @class */ (function () {
  86984. /**
  86985. * Creates a new AxesViewer
  86986. * @param scene defines the hosting scene
  86987. * @param scaleLines defines a number used to scale line length (1 by default)
  86988. */
  86989. function AxesViewer(scene, scaleLines) {
  86990. if (scaleLines === void 0) { scaleLines = 1; }
  86991. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86992. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86993. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86994. /**
  86995. * Gets or sets a number used to scale line length
  86996. */
  86997. this.scaleLines = 1;
  86998. this.scaleLines = scaleLines;
  86999. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87000. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87001. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87002. this._xmesh.renderingGroupId = 2;
  87003. this._ymesh.renderingGroupId = 2;
  87004. this._zmesh.renderingGroupId = 2;
  87005. this._xmesh.material.checkReadyOnlyOnce = true;
  87006. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87007. this._ymesh.material.checkReadyOnlyOnce = true;
  87008. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87009. this._zmesh.material.checkReadyOnlyOnce = true;
  87010. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87011. this.scene = scene;
  87012. }
  87013. /**
  87014. * Force the viewer to update
  87015. * @param position defines the position of the viewer
  87016. * @param xaxis defines the x axis of the viewer
  87017. * @param yaxis defines the y axis of the viewer
  87018. * @param zaxis defines the z axis of the viewer
  87019. */
  87020. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87021. var scaleLines = this.scaleLines;
  87022. if (this._xmesh) {
  87023. this._xmesh.position.copyFrom(position);
  87024. }
  87025. if (this._ymesh) {
  87026. this._ymesh.position.copyFrom(position);
  87027. }
  87028. if (this._zmesh) {
  87029. this._zmesh.position.copyFrom(position);
  87030. }
  87031. var point2 = this._xline[1];
  87032. point2.x = xaxis.x * scaleLines;
  87033. point2.y = xaxis.y * scaleLines;
  87034. point2.z = xaxis.z * scaleLines;
  87035. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87036. point2 = this._yline[1];
  87037. point2.x = yaxis.x * scaleLines;
  87038. point2.y = yaxis.y * scaleLines;
  87039. point2.z = yaxis.z * scaleLines;
  87040. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87041. point2 = this._zline[1];
  87042. point2.x = zaxis.x * scaleLines;
  87043. point2.y = zaxis.y * scaleLines;
  87044. point2.z = zaxis.z * scaleLines;
  87045. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87046. };
  87047. /** Releases resources */
  87048. AxesViewer.prototype.dispose = function () {
  87049. if (this._xmesh) {
  87050. this._xmesh.dispose();
  87051. }
  87052. if (this._ymesh) {
  87053. this._ymesh.dispose();
  87054. }
  87055. if (this._zmesh) {
  87056. this._zmesh.dispose();
  87057. }
  87058. this._xmesh = null;
  87059. this._ymesh = null;
  87060. this._zmesh = null;
  87061. this.scene = null;
  87062. };
  87063. return AxesViewer;
  87064. }());
  87065. Debug.AxesViewer = AxesViewer;
  87066. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87067. })(BABYLON || (BABYLON = {}));
  87068. //# sourceMappingURL=babylon.axesViewer.js.map
  87069. var BABYLON;
  87070. (function (BABYLON) {
  87071. var Debug;
  87072. (function (Debug) {
  87073. /**
  87074. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87075. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87076. */
  87077. var BoneAxesViewer = /** @class */ (function (_super) {
  87078. __extends(BoneAxesViewer, _super);
  87079. /**
  87080. * Creates a new BoneAxesViewer
  87081. * @param scene defines the hosting scene
  87082. * @param bone defines the target bone
  87083. * @param mesh defines the target mesh
  87084. * @param scaleLines defines a scaling factor for line length (1 by default)
  87085. */
  87086. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87087. if (scaleLines === void 0) { scaleLines = 1; }
  87088. var _this = _super.call(this, scene, scaleLines) || this;
  87089. /** Gets current position */
  87090. _this.pos = BABYLON.Vector3.Zero();
  87091. /** Gets direction of X axis */
  87092. _this.xaxis = BABYLON.Vector3.Zero();
  87093. /** Gets direction of Y axis */
  87094. _this.yaxis = BABYLON.Vector3.Zero();
  87095. /** Gets direction of Z axis */
  87096. _this.zaxis = BABYLON.Vector3.Zero();
  87097. _this.mesh = mesh;
  87098. _this.bone = bone;
  87099. return _this;
  87100. }
  87101. /**
  87102. * Force the viewer to update
  87103. */
  87104. BoneAxesViewer.prototype.update = function () {
  87105. if (!this.mesh || !this.bone) {
  87106. return;
  87107. }
  87108. var bone = this.bone;
  87109. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87110. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87111. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87112. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87113. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87114. };
  87115. /** Releases resources */
  87116. BoneAxesViewer.prototype.dispose = function () {
  87117. if (this.mesh) {
  87118. this.mesh = null;
  87119. this.bone = null;
  87120. _super.prototype.dispose.call(this);
  87121. }
  87122. };
  87123. return BoneAxesViewer;
  87124. }(Debug.AxesViewer));
  87125. Debug.BoneAxesViewer = BoneAxesViewer;
  87126. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87127. })(BABYLON || (BABYLON = {}));
  87128. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87129. var BABYLON;
  87130. (function (BABYLON) {
  87131. var RayHelper = /** @class */ (function () {
  87132. function RayHelper(ray) {
  87133. this.ray = ray;
  87134. }
  87135. RayHelper.CreateAndShow = function (ray, scene, color) {
  87136. var helper = new RayHelper(ray);
  87137. helper.show(scene, color);
  87138. return helper;
  87139. };
  87140. RayHelper.prototype.show = function (scene, color) {
  87141. if (!this._renderFunction && this.ray) {
  87142. var ray = this.ray;
  87143. this._renderFunction = this._render.bind(this);
  87144. this._scene = scene;
  87145. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87146. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87147. if (this._renderFunction) {
  87148. this._scene.registerBeforeRender(this._renderFunction);
  87149. }
  87150. }
  87151. if (color && this._renderLine) {
  87152. this._renderLine.color.copyFrom(color);
  87153. }
  87154. };
  87155. RayHelper.prototype.hide = function () {
  87156. if (this._renderFunction && this._scene) {
  87157. this._scene.unregisterBeforeRender(this._renderFunction);
  87158. this._scene = null;
  87159. this._renderFunction = null;
  87160. if (this._renderLine) {
  87161. this._renderLine.dispose();
  87162. this._renderLine = null;
  87163. }
  87164. this._renderPoints = [];
  87165. }
  87166. };
  87167. RayHelper.prototype._render = function () {
  87168. var ray = this.ray;
  87169. if (!ray) {
  87170. return;
  87171. }
  87172. var point = this._renderPoints[1];
  87173. var len = Math.min(ray.length, 1000000);
  87174. point.copyFrom(ray.direction);
  87175. point.scaleInPlace(len);
  87176. point.addInPlace(ray.origin);
  87177. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87178. };
  87179. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87180. this._attachedToMesh = mesh;
  87181. var ray = this.ray;
  87182. if (!ray) {
  87183. return;
  87184. }
  87185. if (!ray.direction) {
  87186. ray.direction = BABYLON.Vector3.Zero();
  87187. }
  87188. if (!ray.origin) {
  87189. ray.origin = BABYLON.Vector3.Zero();
  87190. }
  87191. if (length) {
  87192. ray.length = length;
  87193. }
  87194. if (!meshSpaceOrigin) {
  87195. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87196. }
  87197. if (!meshSpaceDirection) {
  87198. // -1 so that this will work with Mesh.lookAt
  87199. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87200. }
  87201. if (!this._meshSpaceDirection) {
  87202. this._meshSpaceDirection = meshSpaceDirection.clone();
  87203. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87204. }
  87205. else {
  87206. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87207. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87208. }
  87209. if (!this._updateToMeshFunction) {
  87210. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87211. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87212. }
  87213. this._updateToMesh();
  87214. };
  87215. RayHelper.prototype.detachFromMesh = function () {
  87216. if (this._attachedToMesh) {
  87217. if (this._updateToMeshFunction) {
  87218. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87219. }
  87220. this._attachedToMesh = null;
  87221. this._updateToMeshFunction = null;
  87222. }
  87223. };
  87224. RayHelper.prototype._updateToMesh = function () {
  87225. var ray = this.ray;
  87226. if (!this._attachedToMesh || !ray) {
  87227. return;
  87228. }
  87229. if (this._attachedToMesh._isDisposed) {
  87230. this.detachFromMesh();
  87231. return;
  87232. }
  87233. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87234. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87235. };
  87236. RayHelper.prototype.dispose = function () {
  87237. this.hide();
  87238. this.detachFromMesh();
  87239. this.ray = null;
  87240. };
  87241. return RayHelper;
  87242. }());
  87243. BABYLON.RayHelper = RayHelper;
  87244. })(BABYLON || (BABYLON = {}));
  87245. //# sourceMappingURL=babylon.rayHelper.js.map
  87246. var BABYLON;
  87247. (function (BABYLON) {
  87248. // load the inspector using require, if not present in the global namespace.
  87249. var DebugLayer = /** @class */ (function () {
  87250. function DebugLayer(scene) {
  87251. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87252. this._scene = scene;
  87253. // load inspector using require, if it doesn't exist on the global namespace.
  87254. }
  87255. /** Creates the inspector window. */
  87256. DebugLayer.prototype._createInspector = function (config) {
  87257. if (config === void 0) { config = {}; }
  87258. var popup = config.popup || false;
  87259. var initialTab = config.initialTab || 0;
  87260. var parentElement = config.parentElement || null;
  87261. if (!this._inspector) {
  87262. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87263. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87264. } // else nothing to do,; instance is already existing
  87265. };
  87266. DebugLayer.prototype.isVisible = function () {
  87267. if (!this._inspector) {
  87268. return false;
  87269. }
  87270. return true;
  87271. };
  87272. DebugLayer.prototype.hide = function () {
  87273. if (this._inspector) {
  87274. try {
  87275. this._inspector.dispose();
  87276. }
  87277. catch (e) {
  87278. // If the inspector has been removed directly from the inspector tool
  87279. }
  87280. this.onPropertyChangedObservable.clear();
  87281. this._inspector = null;
  87282. }
  87283. };
  87284. /**
  87285. *
  87286. * Launch the debugLayer.
  87287. *
  87288. * initialTab:
  87289. * | Value | Tab Name |
  87290. * | --- | --- |
  87291. * | 0 | Scene |
  87292. * | 1 | Console |
  87293. * | 2 | Stats |
  87294. * | 3 | Textures |
  87295. * | 4 | Mesh |
  87296. * | 5 | Light |
  87297. * | 6 | Material |
  87298. * | 7 | GLTF |
  87299. * | 8 | GUI |
  87300. * | 9 | Physics |
  87301. * | 10 | Camera |
  87302. * | 11 | Audio |
  87303. *
  87304. */
  87305. DebugLayer.prototype.show = function (config) {
  87306. if (config === void 0) { config = {}; }
  87307. if (typeof this.BJSINSPECTOR == 'undefined') {
  87308. // Load inspector and add it to the DOM
  87309. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87310. }
  87311. else {
  87312. // Otherwise creates the inspector
  87313. this._createInspector(config);
  87314. this.onPropertyChangedObservable = new BABYLON.Observable();
  87315. }
  87316. };
  87317. /**
  87318. * Gets the active tab
  87319. * @return the index of the active tab or -1 if the inspector is hidden
  87320. */
  87321. DebugLayer.prototype.getActiveTab = function () {
  87322. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87323. };
  87324. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87325. return DebugLayer;
  87326. }());
  87327. BABYLON.DebugLayer = DebugLayer;
  87328. })(BABYLON || (BABYLON = {}));
  87329. //# sourceMappingURL=babylon.debugLayer.js.map
  87330. var BABYLON;
  87331. (function (BABYLON) {
  87332. var Debug;
  87333. (function (Debug) {
  87334. /**
  87335. * Used to show the physics impostor around the specific mesh
  87336. */
  87337. var PhysicsViewer = /** @class */ (function () {
  87338. /**
  87339. * Creates a new PhysicsViewer
  87340. * @param scene defines the hosting scene
  87341. */
  87342. function PhysicsViewer(scene) {
  87343. /** @hidden */
  87344. this._impostors = [];
  87345. /** @hidden */
  87346. this._meshes = [];
  87347. /** @hidden */
  87348. this._numMeshes = 0;
  87349. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87350. var physicEngine = this._scene.getPhysicsEngine();
  87351. if (physicEngine) {
  87352. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87353. }
  87354. }
  87355. /** @hidden */
  87356. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87357. var plugin = this._physicsEnginePlugin;
  87358. for (var i = 0; i < this._numMeshes; i++) {
  87359. var impostor = this._impostors[i];
  87360. if (!impostor) {
  87361. continue;
  87362. }
  87363. if (impostor.isDisposed) {
  87364. this.hideImpostor(this._impostors[i--]);
  87365. }
  87366. else {
  87367. var mesh = this._meshes[i];
  87368. if (mesh && plugin) {
  87369. plugin.syncMeshWithImpostor(mesh, impostor);
  87370. }
  87371. }
  87372. }
  87373. };
  87374. /**
  87375. * Renders a specified physic impostor
  87376. * @param impostor defines the impostor to render
  87377. */
  87378. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87379. if (!this._scene) {
  87380. return;
  87381. }
  87382. for (var i = 0; i < this._numMeshes; i++) {
  87383. if (this._impostors[i] == impostor) {
  87384. return;
  87385. }
  87386. }
  87387. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87388. if (debugMesh) {
  87389. this._impostors[this._numMeshes] = impostor;
  87390. this._meshes[this._numMeshes] = debugMesh;
  87391. if (this._numMeshes === 0) {
  87392. this._renderFunction = this._updateDebugMeshes.bind(this);
  87393. this._scene.registerBeforeRender(this._renderFunction);
  87394. }
  87395. this._numMeshes++;
  87396. }
  87397. };
  87398. /**
  87399. * Hides a specified physic impostor
  87400. * @param impostor defines the impostor to hide
  87401. */
  87402. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87403. if (!impostor || !this._scene) {
  87404. return;
  87405. }
  87406. var removed = false;
  87407. for (var i = 0; i < this._numMeshes; i++) {
  87408. if (this._impostors[i] == impostor) {
  87409. var mesh = this._meshes[i];
  87410. if (!mesh) {
  87411. continue;
  87412. }
  87413. this._scene.removeMesh(mesh);
  87414. mesh.dispose();
  87415. this._numMeshes--;
  87416. if (this._numMeshes > 0) {
  87417. this._meshes[i] = this._meshes[this._numMeshes];
  87418. this._impostors[i] = this._impostors[this._numMeshes];
  87419. this._meshes[this._numMeshes] = null;
  87420. this._impostors[this._numMeshes] = null;
  87421. }
  87422. else {
  87423. this._meshes[0] = null;
  87424. this._impostors[0] = null;
  87425. }
  87426. removed = true;
  87427. break;
  87428. }
  87429. }
  87430. if (removed && this._numMeshes === 0) {
  87431. this._scene.unregisterBeforeRender(this._renderFunction);
  87432. }
  87433. };
  87434. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87435. if (!this._debugMaterial) {
  87436. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87437. this._debugMaterial.wireframe = true;
  87438. }
  87439. return this._debugMaterial;
  87440. };
  87441. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87442. if (!this._debugBoxMesh) {
  87443. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87444. this._debugBoxMesh.renderingGroupId = 1;
  87445. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87446. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87447. scene.removeMesh(this._debugBoxMesh);
  87448. }
  87449. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87450. };
  87451. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87452. if (!this._debugSphereMesh) {
  87453. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87454. this._debugSphereMesh.renderingGroupId = 1;
  87455. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87456. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87457. scene.removeMesh(this._debugSphereMesh);
  87458. }
  87459. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87460. };
  87461. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87462. var mesh = null;
  87463. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87464. mesh = this._getDebugBoxMesh(scene);
  87465. impostor.getBoxSizeToRef(mesh.scaling);
  87466. }
  87467. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87468. mesh = this._getDebugSphereMesh(scene);
  87469. var radius = impostor.getRadius();
  87470. mesh.scaling.x = radius * 2;
  87471. mesh.scaling.y = radius * 2;
  87472. mesh.scaling.z = radius * 2;
  87473. }
  87474. return mesh;
  87475. };
  87476. /** Releases all resources */
  87477. PhysicsViewer.prototype.dispose = function () {
  87478. for (var i = 0; i < this._numMeshes; i++) {
  87479. this.hideImpostor(this._impostors[i]);
  87480. }
  87481. if (this._debugBoxMesh) {
  87482. this._debugBoxMesh.dispose();
  87483. }
  87484. if (this._debugSphereMesh) {
  87485. this._debugSphereMesh.dispose();
  87486. }
  87487. if (this._debugMaterial) {
  87488. this._debugMaterial.dispose();
  87489. }
  87490. this._impostors.length = 0;
  87491. this._scene = null;
  87492. this._physicsEnginePlugin = null;
  87493. };
  87494. return PhysicsViewer;
  87495. }());
  87496. Debug.PhysicsViewer = PhysicsViewer;
  87497. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87498. })(BABYLON || (BABYLON = {}));
  87499. //# sourceMappingURL=babylon.physicsViewer.js.map
  87500. var BABYLON;
  87501. (function (BABYLON) {
  87502. var BoundingBoxRenderer = /** @class */ (function () {
  87503. function BoundingBoxRenderer(scene) {
  87504. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87505. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87506. this.showBackLines = true;
  87507. this.renderList = new BABYLON.SmartArray(32);
  87508. this._vertexBuffers = {};
  87509. this._scene = scene;
  87510. }
  87511. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87512. if (this._colorShader) {
  87513. return;
  87514. }
  87515. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87516. attributes: [BABYLON.VertexBuffer.PositionKind],
  87517. uniforms: ["world", "viewProjection", "color"]
  87518. });
  87519. var engine = this._scene.getEngine();
  87520. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87521. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87522. this._createIndexBuffer();
  87523. };
  87524. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87525. var engine = this._scene.getEngine();
  87526. 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]);
  87527. };
  87528. BoundingBoxRenderer.prototype._rebuild = function () {
  87529. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87530. if (vb) {
  87531. vb._rebuild();
  87532. }
  87533. this._createIndexBuffer();
  87534. };
  87535. BoundingBoxRenderer.prototype.reset = function () {
  87536. this.renderList.reset();
  87537. };
  87538. BoundingBoxRenderer.prototype.render = function () {
  87539. if (this.renderList.length === 0) {
  87540. return;
  87541. }
  87542. this._prepareRessources();
  87543. if (!this._colorShader.isReady()) {
  87544. return;
  87545. }
  87546. var engine = this._scene.getEngine();
  87547. engine.setDepthWrite(false);
  87548. this._colorShader._preBind();
  87549. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87550. var boundingBox = this.renderList.data[boundingBoxIndex];
  87551. var min = boundingBox.minimum;
  87552. var max = boundingBox.maximum;
  87553. var diff = max.subtract(min);
  87554. var median = min.add(diff.scale(0.5));
  87555. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87556. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87557. .multiply(boundingBox.getWorldMatrix());
  87558. // VBOs
  87559. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87560. if (this.showBackLines) {
  87561. // Back
  87562. engine.setDepthFunctionToGreaterOrEqual();
  87563. this._scene.resetCachedMaterial();
  87564. this._colorShader.setColor4("color", this.backColor.toColor4());
  87565. this._colorShader.bind(worldMatrix);
  87566. // Draw order
  87567. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87568. }
  87569. // Front
  87570. engine.setDepthFunctionToLess();
  87571. this._scene.resetCachedMaterial();
  87572. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87573. this._colorShader.bind(worldMatrix);
  87574. // Draw order
  87575. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87576. }
  87577. this._colorShader.unbind();
  87578. engine.setDepthFunctionToLessOrEqual();
  87579. engine.setDepthWrite(true);
  87580. };
  87581. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87582. this._prepareRessources();
  87583. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87584. return;
  87585. }
  87586. var engine = this._scene.getEngine();
  87587. engine.setDepthWrite(false);
  87588. engine.setColorWrite(false);
  87589. this._colorShader._preBind();
  87590. var boundingBox = mesh._boundingInfo.boundingBox;
  87591. var min = boundingBox.minimum;
  87592. var max = boundingBox.maximum;
  87593. var diff = max.subtract(min);
  87594. var median = min.add(diff.scale(0.5));
  87595. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87596. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87597. .multiply(boundingBox.getWorldMatrix());
  87598. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87599. engine.setDepthFunctionToLess();
  87600. this._scene.resetCachedMaterial();
  87601. this._colorShader.bind(worldMatrix);
  87602. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87603. this._colorShader.unbind();
  87604. engine.setDepthFunctionToLessOrEqual();
  87605. engine.setDepthWrite(true);
  87606. engine.setColorWrite(true);
  87607. };
  87608. BoundingBoxRenderer.prototype.dispose = function () {
  87609. if (!this._colorShader) {
  87610. return;
  87611. }
  87612. this.renderList.dispose();
  87613. this._colorShader.dispose();
  87614. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87615. if (buffer) {
  87616. buffer.dispose();
  87617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87618. }
  87619. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87620. };
  87621. return BoundingBoxRenderer;
  87622. }());
  87623. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87624. })(BABYLON || (BABYLON = {}));
  87625. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87626. var BABYLON;
  87627. (function (BABYLON) {
  87628. /**
  87629. * Renders a layer on top of an existing scene
  87630. */
  87631. var UtilityLayerRenderer = /** @class */ (function () {
  87632. /**
  87633. * Instantiates a UtilityLayerRenderer
  87634. * @param originalScene the original scene that will be rendered on top of
  87635. */
  87636. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87637. var _this = this;
  87638. this.originalScene = originalScene;
  87639. this._pointerCaptures = {};
  87640. this._lastPointerEvents = {};
  87641. /**
  87642. * If the utility layer should automatically be rendered on top of existing scene
  87643. */
  87644. this.shouldRender = true;
  87645. /**
  87646. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87647. */
  87648. this.onlyCheckPointerDownEvents = true;
  87649. /**
  87650. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87651. */
  87652. this.processAllEvents = false;
  87653. /**
  87654. * Observable raised when the pointer move from the utility layer scene to the main scene
  87655. */
  87656. this.onPointerOutObservable = new BABYLON.Observable();
  87657. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87658. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87659. originalScene.getEngine().scenes.pop();
  87660. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87661. this.utilityLayerScene.detachControl();
  87662. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87663. if (!_this.processAllEvents) {
  87664. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87665. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87666. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87667. return;
  87668. }
  87669. }
  87670. var pointerEvent = (prePointerInfo.event);
  87671. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87672. return;
  87673. }
  87674. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87675. if (!prePointerInfo.ray && utilityScenePick) {
  87676. prePointerInfo.ray = utilityScenePick.ray;
  87677. }
  87678. // always fire the prepointer oversvable
  87679. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87680. // allow every non pointer down event to flow to the utility layer
  87681. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87682. if (!prePointerInfo.skipOnPointerObservable) {
  87683. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87684. }
  87685. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87686. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87687. }
  87688. return;
  87689. }
  87690. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87691. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87692. if (utilityScenePick && utilityScenePick.hit) {
  87693. if (!prePointerInfo.skipOnPointerObservable) {
  87694. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87695. }
  87696. prePointerInfo.skipOnPointerObservable = true;
  87697. }
  87698. }
  87699. else {
  87700. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87701. var pointerEvent_1 = (prePointerInfo.event);
  87702. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87703. if (originalScenePick && utilityScenePick) {
  87704. // No pick in utility scene
  87705. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  87706. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87707. // We touched an utility mesh present in the main scene
  87708. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87709. prePointerInfo.skipOnPointerObservable = true;
  87710. }
  87711. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87712. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  87713. }
  87714. }
  87715. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87716. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87717. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  87718. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87719. }
  87720. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87721. // We have a pick in both scenes but main is closer than utility
  87722. // We touched an utility mesh present in the main scene
  87723. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87724. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87725. prePointerInfo.skipOnPointerObservable = true;
  87726. }
  87727. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  87728. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87729. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  87730. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  87731. }
  87732. }
  87733. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  87734. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  87735. }
  87736. }
  87737. }
  87738. });
  87739. // Render directly on top of existing scene without clearing
  87740. this.utilityLayerScene.autoClear = false;
  87741. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87742. if (_this.shouldRender) {
  87743. _this.render();
  87744. }
  87745. });
  87746. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87747. _this.dispose();
  87748. });
  87749. this._updateCamera();
  87750. }
  87751. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87752. if (!prePointerInfo.skipOnPointerObservable) {
  87753. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87754. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87755. }
  87756. };
  87757. /**
  87758. * Renders the utility layers scene on top of the original scene
  87759. */
  87760. UtilityLayerRenderer.prototype.render = function () {
  87761. this._updateCamera();
  87762. this.utilityLayerScene.render(false);
  87763. };
  87764. /**
  87765. * Disposes of the renderer
  87766. */
  87767. UtilityLayerRenderer.prototype.dispose = function () {
  87768. this.onPointerOutObservable.clear();
  87769. if (this._afterRenderObserver) {
  87770. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87771. }
  87772. if (this._sceneDisposeObserver) {
  87773. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87774. }
  87775. if (this._originalPointerObserver) {
  87776. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87777. }
  87778. this.utilityLayerScene.dispose();
  87779. };
  87780. UtilityLayerRenderer.prototype._updateCamera = function () {
  87781. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87782. };
  87783. return UtilityLayerRenderer;
  87784. }());
  87785. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87786. })(BABYLON || (BABYLON = {}));
  87787. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87788. //# sourceMappingURL=babylon.behavior.js.map
  87789. var BABYLON;
  87790. (function (BABYLON) {
  87791. /**
  87792. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87793. */
  87794. var PointerDragBehavior = /** @class */ (function () {
  87795. /**
  87796. * Creates a pointer drag behavior that can be attached to a mesh
  87797. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  87798. */
  87799. function PointerDragBehavior(options) {
  87800. this.options = options;
  87801. /**
  87802. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  87803. */
  87804. this.currentDraggingPointerID = -1;
  87805. /**
  87806. * If the behavior is currently in a dragging state
  87807. */
  87808. this.dragging = false;
  87809. /**
  87810. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  87811. */
  87812. this.dragDeltaRatio = 0.2;
  87813. // Debug mode will display drag planes to help visualize behavior
  87814. this._debugMode = false;
  87815. this._moving = false;
  87816. /**
  87817. * Fires each time the attached mesh is dragged with the pointer
  87818. * * delta between last drag position and current drag position in world space
  87819. * * dragDistance along the drag axis
  87820. * * dragPlaneNormal normal of the current drag plane used during the drag
  87821. * * dragPlanePoint in world space where the drag intersects the drag plane
  87822. */
  87823. this.onDragObservable = new BABYLON.Observable();
  87824. /**
  87825. * Fires each time a drag begins (eg. mouse down on mesh)
  87826. */
  87827. this.onDragStartObservable = new BABYLON.Observable();
  87828. /**
  87829. * Fires each time a drag ends (eg. mouse release after drag)
  87830. */
  87831. this.onDragEndObservable = new BABYLON.Observable();
  87832. /**
  87833. * If the attached mesh should be moved when dragged
  87834. */
  87835. this.moveAttached = true;
  87836. /**
  87837. * If the drag behavior will react to drag events (Default: true)
  87838. */
  87839. this.enabled = true;
  87840. /**
  87841. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  87842. */
  87843. this.useObjectOrienationForDragging = true;
  87844. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  87845. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  87846. // Variables to avoid instantiation in the below method
  87847. this._pointA = new BABYLON.Vector3(0, 0, 0);
  87848. this._pointB = new BABYLON.Vector3(0, 0, 0);
  87849. this._pointC = new BABYLON.Vector3(0, 0, 0);
  87850. this._lineA = new BABYLON.Vector3(0, 0, 0);
  87851. this._lineB = new BABYLON.Vector3(0, 0, 0);
  87852. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  87853. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  87854. var optionCount = 0;
  87855. if (options === undefined) {
  87856. options = {};
  87857. }
  87858. if (options.dragAxis) {
  87859. optionCount++;
  87860. }
  87861. if (options.dragPlaneNormal) {
  87862. optionCount++;
  87863. }
  87864. if (optionCount > 1) {
  87865. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87866. }
  87867. }
  87868. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87869. /**
  87870. * The name of the behavior
  87871. */
  87872. get: function () {
  87873. return "PointerDrag";
  87874. },
  87875. enumerable: true,
  87876. configurable: true
  87877. });
  87878. /**
  87879. * Initializes the behavior
  87880. */
  87881. PointerDragBehavior.prototype.init = function () { };
  87882. /**
  87883. * Attaches the drag behavior the passed in mesh
  87884. * @param ownerNode The mesh that will be dragged around once attached
  87885. */
  87886. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87887. var _this = this;
  87888. this._scene = ownerNode.getScene();
  87889. this._attachedNode = ownerNode;
  87890. // Initialize drag plane to not interfere with existing scene
  87891. if (!PointerDragBehavior._planeScene) {
  87892. if (this._debugMode) {
  87893. PointerDragBehavior._planeScene = this._scene;
  87894. }
  87895. else {
  87896. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87897. this._scene.getEngine().scenes.pop();
  87898. }
  87899. }
  87900. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87901. // State of the drag
  87902. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  87903. var delta = new BABYLON.Vector3(0, 0, 0);
  87904. var dragLength = 0;
  87905. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  87906. var pickPredicate = function (m) {
  87907. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87908. };
  87909. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87910. if (!_this.enabled) {
  87911. return;
  87912. }
  87913. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87914. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87915. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  87916. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87917. if (pickedPoint) {
  87918. _this.dragging = true;
  87919. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  87920. _this.lastDragPosition.copyFrom(pickedPoint);
  87921. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  87922. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  87923. }
  87924. }
  87925. }
  87926. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87927. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  87928. _this.releaseDrag();
  87929. }
  87930. }
  87931. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87932. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87933. _this._moving = true;
  87934. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87935. if (pickedPoint) {
  87936. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  87937. // depending on the drag mode option drag accordingly
  87938. if (_this.options.dragAxis) {
  87939. // Convert local drag axis to world
  87940. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  87941. // Project delta drag from the drag plane onto the drag axis
  87942. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  87943. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  87944. _this._worldDragAxis.scaleToRef(dragLength, delta);
  87945. }
  87946. else {
  87947. dragLength = delta.length();
  87948. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  87949. }
  87950. targetPosition.addInPlace(delta);
  87951. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  87952. _this.lastDragPosition.copyFrom(pickedPoint);
  87953. }
  87954. }
  87955. }
  87956. });
  87957. this._scene.onBeforeRenderObservable.add(function () {
  87958. if (_this._moving && _this.moveAttached) {
  87959. // Slowly move mesh to avoid jitter
  87960. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  87961. _this._tmpVector.scaleInPlace(0.2);
  87962. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  87963. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  87964. }
  87965. });
  87966. };
  87967. PointerDragBehavior.prototype.releaseDrag = function () {
  87968. this.dragging = false;
  87969. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  87970. this.currentDraggingPointerID = -1;
  87971. this._moving = false;
  87972. };
  87973. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87974. var _this = this;
  87975. if (!ray) {
  87976. return null;
  87977. }
  87978. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87979. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87980. return pickResult.pickedPoint;
  87981. }
  87982. else {
  87983. return null;
  87984. }
  87985. };
  87986. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87987. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  87988. this._pointA.copyFrom(dragPlanePosition);
  87989. if (this.options.dragAxis) {
  87990. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  87991. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87992. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  87993. ray.origin.subtractToRef(this._pointA, this._pointC);
  87994. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  87995. // Get perpendicular line from direction to camera and drag axis
  87996. this._pointB.subtractToRef(this._pointA, this._lineA);
  87997. this._pointC.subtractToRef(this._pointA, this._lineB);
  87998. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  87999. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88000. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88001. this._lookAt.normalize();
  88002. this._dragPlane.position.copyFrom(this._pointA);
  88003. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88004. this._dragPlane.lookAt(this._lookAt);
  88005. }
  88006. else if (this.options.dragPlaneNormal) {
  88007. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88008. this._dragPlane.position.copyFrom(this._pointA);
  88009. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88010. this._dragPlane.lookAt(this._lookAt);
  88011. }
  88012. else {
  88013. this._dragPlane.position.copyFrom(this._pointA);
  88014. this._dragPlane.lookAt(ray.origin);
  88015. }
  88016. this._dragPlane.computeWorldMatrix(true);
  88017. };
  88018. /**
  88019. * Detaches the behavior from the mesh
  88020. */
  88021. PointerDragBehavior.prototype.detach = function () {
  88022. if (this._pointerObserver) {
  88023. this._scene.onPointerObservable.remove(this._pointerObserver);
  88024. }
  88025. };
  88026. return PointerDragBehavior;
  88027. }());
  88028. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88029. })(BABYLON || (BABYLON = {}));
  88030. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88031. var BABYLON;
  88032. (function (BABYLON) {
  88033. /**
  88034. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88035. */
  88036. var MultiPointerScaleBehavior = /** @class */ (function () {
  88037. function MultiPointerScaleBehavior() {
  88038. this._startDistance = 0;
  88039. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88040. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88041. this._sceneRenderObserver = null;
  88042. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88043. this._dragBehaviorA.moveAttached = false;
  88044. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88045. this._dragBehaviorB.moveAttached = false;
  88046. }
  88047. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88048. /**
  88049. * The name of the behavior
  88050. */
  88051. get: function () {
  88052. return "MultiPointerScale";
  88053. },
  88054. enumerable: true,
  88055. configurable: true
  88056. });
  88057. /**
  88058. * Initializes the behavior
  88059. */
  88060. MultiPointerScaleBehavior.prototype.init = function () { };
  88061. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88062. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88063. };
  88064. /**
  88065. * Attaches the scale behavior the passed in mesh
  88066. * @param ownerNode The mesh that will be scaled around once attached
  88067. */
  88068. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88069. var _this = this;
  88070. this._ownerNode = ownerNode;
  88071. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88072. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88073. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88074. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88075. _this._dragBehaviorA.releaseDrag();
  88076. }
  88077. else {
  88078. _this._initialScale.copyFrom(ownerNode.scaling);
  88079. _this._startDistance = _this._getCurrentDistance();
  88080. }
  88081. }
  88082. });
  88083. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88084. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88085. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88086. _this._dragBehaviorB.releaseDrag();
  88087. }
  88088. else {
  88089. _this._initialScale.copyFrom(ownerNode.scaling);
  88090. _this._startDistance = _this._getCurrentDistance();
  88091. }
  88092. }
  88093. });
  88094. // Once both drag behaviors are active scale based on the distance between the two pointers
  88095. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88096. behavior.onDragObservable.add(function () {
  88097. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88098. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88099. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88100. }
  88101. });
  88102. });
  88103. ownerNode.addBehavior(this._dragBehaviorA);
  88104. ownerNode.addBehavior(this._dragBehaviorB);
  88105. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88106. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88107. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88108. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88109. if (change.length() > 0.01) {
  88110. ownerNode.scaling.addInPlace(change);
  88111. }
  88112. }
  88113. });
  88114. };
  88115. /**
  88116. * Detaches the behavior from the mesh
  88117. */
  88118. MultiPointerScaleBehavior.prototype.detach = function () {
  88119. var _this = this;
  88120. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88121. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88122. behavior.onDragStartObservable.clear();
  88123. behavior.onDragObservable.clear();
  88124. _this._ownerNode.removeBehavior(behavior);
  88125. });
  88126. };
  88127. return MultiPointerScaleBehavior;
  88128. }());
  88129. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88130. })(BABYLON || (BABYLON = {}));
  88131. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88132. var BABYLON;
  88133. (function (BABYLON) {
  88134. /**
  88135. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  88136. */
  88137. var SixDofDragBehavior = /** @class */ (function () {
  88138. function SixDofDragBehavior() {
  88139. this._sceneRenderObserver = null;
  88140. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88141. /**
  88142. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  88143. */
  88144. this.zDragFactor = 5;
  88145. /**
  88146. * If the behavior is currently in a dragging state
  88147. */
  88148. this.dragging = false;
  88149. /**
  88150. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88151. */
  88152. this.dragDeltaRatio = 0.2;
  88153. /**
  88154. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88155. */
  88156. this.currentDraggingPointerID = -1;
  88157. }
  88158. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88159. /**
  88160. * The name of the behavior
  88161. */
  88162. get: function () {
  88163. return "SixDofDrag";
  88164. },
  88165. enumerable: true,
  88166. configurable: true
  88167. });
  88168. /**
  88169. * Initializes the behavior
  88170. */
  88171. SixDofDragBehavior.prototype.init = function () { };
  88172. /**
  88173. * Attaches the scale behavior the passed in mesh
  88174. * @param ownerNode The mesh that will be scaled around once attached
  88175. */
  88176. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88177. var _this = this;
  88178. this._ownerNode = ownerNode;
  88179. this._scene = this._ownerNode.getScene();
  88180. if (!SixDofDragBehavior._virtualScene) {
  88181. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88182. this._scene.getEngine().scenes.pop();
  88183. }
  88184. var pickedMesh = null;
  88185. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88186. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88187. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88188. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88189. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88190. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88191. var pickPredicate = function (m) {
  88192. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88193. };
  88194. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88195. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88196. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88197. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88198. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88199. // Set position and orientation of the controller
  88200. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88201. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88202. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88203. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88204. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88205. if (!pickedMesh.rotationQuaternion) {
  88206. pickedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88207. }
  88208. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88209. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88210. // Update state
  88211. _this.dragging = true;
  88212. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88213. }
  88214. }
  88215. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88216. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88217. _this.dragging = false;
  88218. _this.currentDraggingPointerID = -1;
  88219. pickedMesh = null;
  88220. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88221. }
  88222. }
  88223. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88224. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88225. // Calculate controller drag distance in controller space
  88226. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88227. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88228. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88229. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88230. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88231. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88232. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88233. if (_this._virtualDragMesh.position.z < 0) {
  88234. _this._virtualDragMesh.position.z = 0;
  88235. }
  88236. // Update the controller position
  88237. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88238. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88239. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88240. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88241. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88242. if (pickedMesh.parent) {
  88243. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88244. }
  88245. }
  88246. }
  88247. });
  88248. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88249. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88250. if (_this.dragging && pickedMesh) {
  88251. // Slowly move mesh to avoid jitter
  88252. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88253. }
  88254. });
  88255. };
  88256. /**
  88257. * Detaches the behavior from the mesh
  88258. */
  88259. SixDofDragBehavior.prototype.detach = function () {
  88260. this._scene.onPointerObservable.remove(this._pointerObserver);
  88261. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88262. this._virtualOriginMesh.dispose();
  88263. this._virtualDragMesh.dispose();
  88264. };
  88265. return SixDofDragBehavior;
  88266. }());
  88267. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88268. })(BABYLON || (BABYLON = {}));
  88269. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88270. var BABYLON;
  88271. (function (BABYLON) {
  88272. /**
  88273. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88274. */
  88275. var Gizmo = /** @class */ (function () {
  88276. /**
  88277. * Creates a gizmo
  88278. * @param gizmoLayer The utility layer the gizmo will be added to
  88279. */
  88280. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88281. var _this = this;
  88282. this.gizmoLayer = gizmoLayer;
  88283. /**
  88284. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88285. */
  88286. this.updateGizmoRotationToMatchAttachedMesh = true;
  88287. /**
  88288. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88289. */
  88290. this.updateGizmoPositionToMatchAttachedMesh = true;
  88291. /**
  88292. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88293. */
  88294. this._updateScale = true;
  88295. this._interactionsEnabled = true;
  88296. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88297. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88298. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88299. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88300. _this._rootMesh.scaling.set(dist, dist, dist);
  88301. }
  88302. if (_this.attachedMesh) {
  88303. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88304. if (!_this._rootMesh.rotationQuaternion) {
  88305. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88306. }
  88307. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88308. }
  88309. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88310. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88311. }
  88312. }
  88313. });
  88314. }
  88315. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88316. };
  88317. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88318. get: function () {
  88319. return this._interactionsEnabled;
  88320. },
  88321. /**
  88322. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88323. */
  88324. set: function (value) {
  88325. this._interactionsEnabled = value;
  88326. this._onInteractionsEnabledChanged(value);
  88327. },
  88328. enumerable: true,
  88329. configurable: true
  88330. });
  88331. /**
  88332. * Disposes of the gizmo
  88333. */
  88334. Gizmo.prototype.dispose = function () {
  88335. this._rootMesh.dispose();
  88336. if (this._beforeRenderObserver) {
  88337. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88338. }
  88339. };
  88340. return Gizmo;
  88341. }());
  88342. BABYLON.Gizmo = Gizmo;
  88343. })(BABYLON || (BABYLON = {}));
  88344. //# sourceMappingURL=babylon.gizmo.js.map
  88345. var BABYLON;
  88346. (function (BABYLON) {
  88347. /**
  88348. * Single axis drag gizmo
  88349. */
  88350. var AxisDragGizmo = /** @class */ (function (_super) {
  88351. __extends(AxisDragGizmo, _super);
  88352. /**
  88353. * Creates an AxisDragGizmo
  88354. * @param gizmoLayer The utility layer the gizmo will be added to
  88355. * @param dragAxis The axis which the gizmo will be able to drag on
  88356. * @param color The color of the gizmo
  88357. */
  88358. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88359. var _this = _super.call(this, gizmoLayer) || this;
  88360. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88361. // Create Material
  88362. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88363. coloredMaterial.disableLighting = true;
  88364. coloredMaterial.emissiveColor = color;
  88365. // Build mesh on root node
  88366. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88367. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88368. _this._rootMesh.addChild(arrowMesh);
  88369. _this._rootMesh.addChild(arrowTail);
  88370. // Position arrow pointing in its drag axis
  88371. arrowMesh.scaling.scaleInPlace(0.1);
  88372. arrowMesh.material = coloredMaterial;
  88373. arrowMesh.rotation.x = Math.PI / 2;
  88374. arrowMesh.position.z += 0.3;
  88375. arrowTail.rotation.x = Math.PI / 2;
  88376. arrowTail.material = coloredMaterial;
  88377. arrowTail.position.z += 0.2;
  88378. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88379. // Add drag behavior to handle events when the gizmo is dragged
  88380. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88381. _this._dragBehavior.moveAttached = false;
  88382. _this._rootMesh.addBehavior(_this._dragBehavior);
  88383. _this._dragBehavior.onDragObservable.add(function (event) {
  88384. if (!_this.interactionsEnabled) {
  88385. return;
  88386. }
  88387. if (_this.attachedMesh) {
  88388. _this.attachedMesh.position.addInPlace(event.delta);
  88389. }
  88390. });
  88391. return _this;
  88392. }
  88393. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88394. this._dragBehavior.enabled = value;
  88395. };
  88396. /**
  88397. * Disposes of the gizmo
  88398. */
  88399. AxisDragGizmo.prototype.dispose = function () {
  88400. this._dragBehavior.detach();
  88401. _super.prototype.dispose.call(this);
  88402. };
  88403. return AxisDragGizmo;
  88404. }(BABYLON.Gizmo));
  88405. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88406. })(BABYLON || (BABYLON = {}));
  88407. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88408. var BABYLON;
  88409. (function (BABYLON) {
  88410. /**
  88411. * Single axis scale gizmo
  88412. */
  88413. var AxisScaleGizmo = /** @class */ (function (_super) {
  88414. __extends(AxisScaleGizmo, _super);
  88415. /**
  88416. * Creates an AxisScaleGizmo
  88417. * @param gizmoLayer The utility layer the gizmo will be added to
  88418. * @param dragAxis The axis which the gizmo will be able to scale on
  88419. * @param color The color of the gizmo
  88420. */
  88421. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88422. var _this = _super.call(this, gizmoLayer) || this;
  88423. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88424. // Create Material
  88425. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88426. coloredMaterial.disableLighting = true;
  88427. coloredMaterial.emissiveColor = color;
  88428. // Build mesh on root node
  88429. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  88430. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88431. _this._rootMesh.addChild(arrowMesh);
  88432. _this._rootMesh.addChild(arrowTail);
  88433. // Position arrow pointing in its drag axis
  88434. arrowMesh.scaling.scaleInPlace(0.1);
  88435. arrowMesh.material = coloredMaterial;
  88436. arrowMesh.rotation.x = Math.PI / 2;
  88437. arrowMesh.position.z += 0.3;
  88438. arrowTail.rotation.x = Math.PI / 2;
  88439. arrowTail.material = coloredMaterial;
  88440. arrowTail.position.z += 0.2;
  88441. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88442. // Add drag behavior to handle events when the gizmo is dragged
  88443. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88444. _this._dragBehavior.moveAttached = false;
  88445. _this._rootMesh.addBehavior(_this._dragBehavior);
  88446. _this._dragBehavior.onDragObservable.add(function (event) {
  88447. if (!_this.interactionsEnabled) {
  88448. return;
  88449. }
  88450. if (_this.attachedMesh) {
  88451. _this.attachedMesh.scaling.addInPlace(event.delta);
  88452. }
  88453. });
  88454. return _this;
  88455. }
  88456. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88457. this._dragBehavior.enabled = value;
  88458. };
  88459. /**
  88460. * Disposes of the gizmo
  88461. */
  88462. AxisScaleGizmo.prototype.dispose = function () {
  88463. this._dragBehavior.detach();
  88464. _super.prototype.dispose.call(this);
  88465. };
  88466. return AxisScaleGizmo;
  88467. }(BABYLON.Gizmo));
  88468. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88469. })(BABYLON || (BABYLON = {}));
  88470. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88471. var BABYLON;
  88472. (function (BABYLON) {
  88473. /**
  88474. * Single plane rotation gizmo
  88475. */
  88476. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88477. __extends(PlaneRotationGizmo, _super);
  88478. /**
  88479. * Creates a PlaneRotationGizmo
  88480. * @param gizmoLayer The utility layer the gizmo will be added to
  88481. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88482. * @param color The color of the gizmo
  88483. */
  88484. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88485. var _this = _super.call(this, gizmoLayer) || this;
  88486. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88487. // Create Material
  88488. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88489. coloredMaterial.disableLighting = true;
  88490. coloredMaterial.emissiveColor = color;
  88491. // Build mesh on root node
  88492. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  88493. _this._rootMesh.addChild(rotationMesh);
  88494. // Position arrow pointing in its drag axis
  88495. rotationMesh.scaling.scaleInPlace(0.1);
  88496. rotationMesh.material = coloredMaterial;
  88497. rotationMesh.rotation.x = Math.PI / 2;
  88498. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88499. // Add drag behavior to handle events when the gizmo is dragged
  88500. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) });
  88501. _this._dragBehavior.moveAttached = false;
  88502. _this._rootMesh.addBehavior(_this._dragBehavior);
  88503. var lastDragPosition = null;
  88504. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88505. if (!_this.interactionsEnabled) {
  88506. return;
  88507. }
  88508. lastDragPosition = e.dragPlanePoint;
  88509. });
  88510. _this._dragBehavior.onDragObservable.add(function (event) {
  88511. if (!_this.interactionsEnabled) {
  88512. return;
  88513. }
  88514. if (_this.attachedMesh && lastDragPosition) {
  88515. if (!_this.attachedMesh.rotationQuaternion) {
  88516. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88517. }
  88518. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88519. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88520. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88521. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88522. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88523. var angle = Math.atan2(cross.length(), dot);
  88524. var up = planeNormal.clone();
  88525. // Flip up vector depending on which side the camera is on
  88526. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88527. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88528. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  88529. up.scaleInPlace(-1);
  88530. }
  88531. }
  88532. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  88533. if (halfCircleSide)
  88534. angle = -angle;
  88535. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88536. var quaternionCoefficient = Math.sin(angle / 2);
  88537. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  88538. // Rotate selected mesh quaternion over fixed axis
  88539. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  88540. lastDragPosition = event.dragPlanePoint;
  88541. }
  88542. });
  88543. return _this;
  88544. }
  88545. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88546. this._dragBehavior.enabled = value;
  88547. };
  88548. /**
  88549. * Disposes of the gizmo
  88550. */
  88551. PlaneRotationGizmo.prototype.dispose = function () {
  88552. this._dragBehavior.detach();
  88553. _super.prototype.dispose.call(this);
  88554. };
  88555. return PlaneRotationGizmo;
  88556. }(BABYLON.Gizmo));
  88557. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88558. })(BABYLON || (BABYLON = {}));
  88559. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88560. var BABYLON;
  88561. (function (BABYLON) {
  88562. /**
  88563. * Gizmo that enables dragging a mesh along 3 axis
  88564. */
  88565. var PositionGizmo = /** @class */ (function (_super) {
  88566. __extends(PositionGizmo, _super);
  88567. /**
  88568. * Creates a PositionGizmo
  88569. * @param gizmoLayer The utility layer the gizmo will be added to
  88570. */
  88571. function PositionGizmo(gizmoLayer) {
  88572. var _this = _super.call(this, gizmoLayer) || this;
  88573. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88574. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88575. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88576. return _this;
  88577. }
  88578. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88579. set: function (mesh) {
  88580. this._xDrag.attachedMesh = mesh;
  88581. this._yDrag.attachedMesh = mesh;
  88582. this._zDrag.attachedMesh = mesh;
  88583. },
  88584. enumerable: true,
  88585. configurable: true
  88586. });
  88587. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88588. this._xDrag.interactionsEnabled = value;
  88589. this._yDrag.interactionsEnabled = value;
  88590. this._zDrag.interactionsEnabled = value;
  88591. };
  88592. /**
  88593. * Disposes of the gizmo
  88594. */
  88595. PositionGizmo.prototype.dispose = function () {
  88596. this._xDrag.dispose();
  88597. this._yDrag.dispose();
  88598. this._zDrag.dispose();
  88599. };
  88600. return PositionGizmo;
  88601. }(BABYLON.Gizmo));
  88602. BABYLON.PositionGizmo = PositionGizmo;
  88603. })(BABYLON || (BABYLON = {}));
  88604. //# sourceMappingURL=babylon.positionGizmo.js.map
  88605. var BABYLON;
  88606. (function (BABYLON) {
  88607. /**
  88608. * Gizmo that enables rotating a mesh along 3 axis
  88609. */
  88610. var RotationGizmo = /** @class */ (function (_super) {
  88611. __extends(RotationGizmo, _super);
  88612. /**
  88613. * Creates a RotationGizmo
  88614. * @param gizmoLayer The utility layer the gizmo will be added to
  88615. */
  88616. function RotationGizmo(gizmoLayer) {
  88617. var _this = _super.call(this, gizmoLayer) || this;
  88618. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88619. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88620. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88621. return _this;
  88622. }
  88623. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88624. set: function (mesh) {
  88625. this._xDrag.attachedMesh = mesh;
  88626. this._yDrag.attachedMesh = mesh;
  88627. this._zDrag.attachedMesh = mesh;
  88628. },
  88629. enumerable: true,
  88630. configurable: true
  88631. });
  88632. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88633. this._xDrag.interactionsEnabled = value;
  88634. this._yDrag.interactionsEnabled = value;
  88635. this._zDrag.interactionsEnabled = value;
  88636. };
  88637. /**
  88638. * Disposes of the gizmo
  88639. */
  88640. RotationGizmo.prototype.dispose = function () {
  88641. this._xDrag.dispose();
  88642. this._yDrag.dispose();
  88643. this._zDrag.dispose();
  88644. };
  88645. return RotationGizmo;
  88646. }(BABYLON.Gizmo));
  88647. BABYLON.RotationGizmo = RotationGizmo;
  88648. })(BABYLON || (BABYLON = {}));
  88649. //# sourceMappingURL=babylon.rotationGizmo.js.map
  88650. var BABYLON;
  88651. (function (BABYLON) {
  88652. /**
  88653. * Gizmo that enables scaling a mesh along 3 axis
  88654. */
  88655. var ScaleGizmo = /** @class */ (function (_super) {
  88656. __extends(ScaleGizmo, _super);
  88657. /**
  88658. * Creates a ScaleGizmo
  88659. * @param gizmoLayer The utility layer the gizmo will be added to
  88660. */
  88661. function ScaleGizmo(gizmoLayer) {
  88662. var _this = _super.call(this, gizmoLayer) || this;
  88663. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88664. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88665. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88666. return _this;
  88667. }
  88668. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  88669. set: function (mesh) {
  88670. this._xDrag.attachedMesh = mesh;
  88671. this._yDrag.attachedMesh = mesh;
  88672. this._zDrag.attachedMesh = mesh;
  88673. },
  88674. enumerable: true,
  88675. configurable: true
  88676. });
  88677. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88678. this._xDrag.interactionsEnabled = value;
  88679. this._yDrag.interactionsEnabled = value;
  88680. this._zDrag.interactionsEnabled = value;
  88681. };
  88682. /**
  88683. * Disposes of the gizmo
  88684. */
  88685. ScaleGizmo.prototype.dispose = function () {
  88686. this._xDrag.dispose();
  88687. this._yDrag.dispose();
  88688. this._zDrag.dispose();
  88689. };
  88690. return ScaleGizmo;
  88691. }(BABYLON.Gizmo));
  88692. BABYLON.ScaleGizmo = ScaleGizmo;
  88693. })(BABYLON || (BABYLON = {}));
  88694. //# sourceMappingURL=babylon.scaleGizmo.js.map
  88695. var BABYLON;
  88696. (function (BABYLON) {
  88697. /**
  88698. * Bounding box gizmo
  88699. */
  88700. var BoundingBoxGizmo = /** @class */ (function (_super) {
  88701. __extends(BoundingBoxGizmo, _super);
  88702. /**
  88703. * Creates an BoundingBoxGizmo
  88704. * @param gizmoLayer The utility layer the gizmo will be added to
  88705. * @param color The color of the gizmo
  88706. */
  88707. function BoundingBoxGizmo(gizmoLayer, color) {
  88708. var _this = _super.call(this, gizmoLayer) || this;
  88709. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  88710. _this._renderObserver = null;
  88711. _this._pointerObserver = null;
  88712. _this._scaleDragSpeed = 0.2;
  88713. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  88714. _this._updateScale = false;
  88715. // Create Materials
  88716. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88717. coloredMaterial.disableLighting = true;
  88718. coloredMaterial.emissiveColor = color;
  88719. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88720. hoverColoredMaterial.disableLighting = true;
  88721. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88722. // Build bounding box out of lines
  88723. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88724. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  88725. var lines = [];
  88726. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  88727. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88728. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88729. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88730. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88731. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88732. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88733. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88734. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88735. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88736. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88737. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88738. lines.forEach(function (l) {
  88739. l.color = color;
  88740. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  88741. l.isPickable = false;
  88742. _this._lineBoundingBox.addChild(l);
  88743. });
  88744. _this._rootMesh.addChild(_this._lineBoundingBox);
  88745. // Create rotation spheres
  88746. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88747. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  88748. var _loop_1 = function (i_1) {
  88749. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  88750. sphere.rotationQuaternion = new BABYLON.Quaternion();
  88751. sphere.material = coloredMaterial;
  88752. // Drag behavior
  88753. _dragBehavior = new BABYLON.PointerDragBehavior({});
  88754. _dragBehavior.moveAttached = false;
  88755. sphere.addBehavior(_dragBehavior);
  88756. _dragBehavior.onDragObservable.add(function (event) {
  88757. if (_this.attachedMesh) {
  88758. var worldDragDirection = sphere.forward;
  88759. // Project the world right on to the drag plane
  88760. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  88761. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  88762. // project drag delta on to the resulting drag axis and rotate based on that
  88763. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  88764. // Rotate based on axis
  88765. if (i_1 >= 8) {
  88766. _this.attachedMesh.rotation.z -= projectDist;
  88767. }
  88768. else if (i_1 >= 4) {
  88769. _this.attachedMesh.rotation.y -= projectDist;
  88770. }
  88771. else {
  88772. _this.attachedMesh.rotation.x -= projectDist;
  88773. }
  88774. }
  88775. });
  88776. // Selection/deselection
  88777. _dragBehavior.onDragStartObservable.add(function () {
  88778. _this._selectNode(sphere);
  88779. });
  88780. _dragBehavior.onDragEndObservable.add(function () {
  88781. _this._selectNode(null);
  88782. });
  88783. this_1._rotateSpheresParent.addChild(sphere);
  88784. };
  88785. var this_1 = this, _dragBehavior;
  88786. for (var i_1 = 0; i_1 < 12; i_1++) {
  88787. _loop_1(i_1);
  88788. }
  88789. _this._rootMesh.addChild(_this._rotateSpheresParent);
  88790. // Create scale cubes
  88791. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88792. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  88793. for (var i = 0; i < 2; i++) {
  88794. for (var j = 0; j < 2; j++) {
  88795. var _loop_2 = function () {
  88796. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  88797. box.material = coloredMaterial;
  88798. // Dragging logic
  88799. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  88800. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88801. _dragBehavior.moveAttached = false;
  88802. box.addBehavior(_dragBehavior);
  88803. _dragBehavior.onDragObservable.add(function (event) {
  88804. if (_this.attachedMesh) {
  88805. // Current boudning box dimensions
  88806. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  88807. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  88808. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  88809. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  88810. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  88811. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  88812. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  88813. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  88814. // Update scale and position
  88815. _this.attachedMesh.scaling.addInPlace(deltaScale);
  88816. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  88817. }
  88818. });
  88819. // Selection/deselection
  88820. _dragBehavior.onDragStartObservable.add(function () {
  88821. _this._selectNode(box);
  88822. });
  88823. _dragBehavior.onDragEndObservable.add(function () {
  88824. _this._selectNode(null);
  88825. });
  88826. this_2._scaleBoxesParent.addChild(box);
  88827. };
  88828. var this_2 = this, _dragBehavior;
  88829. for (var k = 0; k < 2; k++) {
  88830. _loop_2();
  88831. }
  88832. }
  88833. }
  88834. _this._rootMesh.addChild(_this._scaleBoxesParent);
  88835. // Hover color change
  88836. var pointerIds = new Array();
  88837. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88838. if (!pointerIds[pointerInfo.event.pointerId]) {
  88839. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  88840. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  88841. pointerIds[pointerInfo.event.pointerId] = mesh;
  88842. mesh.material = hoverColoredMaterial;
  88843. }
  88844. });
  88845. }
  88846. else {
  88847. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  88848. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  88849. delete pointerIds[pointerInfo.event.pointerId];
  88850. }
  88851. }
  88852. });
  88853. // Update bounding box positions
  88854. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  88855. _this._updateBoundingBox();
  88856. });
  88857. _this._updateBoundingBox();
  88858. return _this;
  88859. }
  88860. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  88861. this._rotateSpheresParent.getChildMeshes()
  88862. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  88863. m.isVisible = (!selectedMesh || m == selectedMesh);
  88864. });
  88865. };
  88866. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  88867. if (this.attachedMesh) {
  88868. // Update bounding dimensions/positions
  88869. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  88870. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  88871. this._boundingDimensions.copyFrom(boundBoxDimensions);
  88872. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  88873. }
  88874. // Update rotation sphere locations
  88875. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  88876. for (var i = 0; i < 3; i++) {
  88877. for (var j = 0; j < 2; j++) {
  88878. for (var k = 0; k < 2; k++) {
  88879. var index = ((i * 4) + (j * 2)) + k;
  88880. if (i == 0) {
  88881. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88882. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88883. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88884. }
  88885. if (i == 1) {
  88886. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  88887. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88888. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88889. }
  88890. if (i == 2) {
  88891. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88892. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88893. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88894. }
  88895. }
  88896. }
  88897. }
  88898. // Update scale box locations
  88899. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88900. for (var i = 0; i < 2; i++) {
  88901. for (var j = 0; j < 2; j++) {
  88902. for (var k = 0; k < 2; k++) {
  88903. var index = ((i * 4) + (j * 2)) + k;
  88904. if (scaleBoxes[index]) {
  88905. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88906. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88907. }
  88908. }
  88909. }
  88910. }
  88911. };
  88912. /**
  88913. * Disposes of the gizmo
  88914. */
  88915. BoundingBoxGizmo.prototype.dispose = function () {
  88916. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88917. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88918. this._lineBoundingBox.dispose();
  88919. this._rotateSpheresParent.dispose();
  88920. this._scaleBoxesParent.dispose();
  88921. _super.prototype.dispose.call(this);
  88922. };
  88923. return BoundingBoxGizmo;
  88924. }(BABYLON.Gizmo));
  88925. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88926. })(BABYLON || (BABYLON = {}));
  88927. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88928. var BABYLON;
  88929. (function (BABYLON) {
  88930. /**
  88931. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88932. */
  88933. var GizmoManager = /** @class */ (function () {
  88934. /**
  88935. * Instatiates a gizmo manager
  88936. * @param scene the scene to overlay the gizmos on top of
  88937. * @param options If only a single gizmo should exist at one time
  88938. */
  88939. function GizmoManager(scene, options) {
  88940. var _this = this;
  88941. this.scene = scene;
  88942. // Set of gizmos that are currently in the scene for each mesh
  88943. this._gizmoSet = {};
  88944. this._pointerObserver = null;
  88945. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88946. // Options parsing
  88947. if (!options) {
  88948. options = {};
  88949. }
  88950. if (options.singleGizmo === undefined) {
  88951. options.singleGizmo = true;
  88952. }
  88953. // Instatiate/dispose gizmos based on pointer actions
  88954. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88955. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88956. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88957. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88958. if (options.singleGizmo) {
  88959. _this._clearGizmos();
  88960. }
  88961. // Enable gizmo when mesh is selected
  88962. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88963. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88964. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88965. }
  88966. else {
  88967. if (!options.singleGizmo) {
  88968. // Disable gizmo when clicked again
  88969. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88970. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88971. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88972. }
  88973. }
  88974. }
  88975. else {
  88976. if (options.singleGizmo) {
  88977. // Disable gizmo when clicked away
  88978. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88979. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88980. if (gizmoPick && !gizmoPick.hit) {
  88981. _this._clearGizmos();
  88982. }
  88983. }
  88984. }
  88985. }
  88986. }
  88987. });
  88988. }
  88989. /**
  88990. * Disposes of the gizmo manager
  88991. */
  88992. GizmoManager.prototype.dispose = function () {
  88993. this.scene.onPointerObservable.remove(this._pointerObserver);
  88994. this._clearGizmos();
  88995. this._gizmoLayer.dispose();
  88996. };
  88997. GizmoManager.prototype._clearGizmos = function () {
  88998. for (var key in this._gizmoSet) {
  88999. if (this._gizmoSet.hasOwnProperty(key)) {
  89000. this._gizmoSet[key].positionGizmo.dispose();
  89001. this._gizmoSet[key].rotationGizmo.dispose();
  89002. delete this._gizmoSet[key];
  89003. }
  89004. }
  89005. };
  89006. return GizmoManager;
  89007. }());
  89008. BABYLON.GizmoManager = GizmoManager;
  89009. })(BABYLON || (BABYLON = {}));
  89010. //# sourceMappingURL=babylon.gizmoManager.js.map
  89011. var BABYLON;
  89012. (function (BABYLON) {
  89013. /**
  89014. * Defines a target to use with MorphTargetManager
  89015. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89016. */
  89017. var MorphTarget = /** @class */ (function () {
  89018. /**
  89019. * Creates a new MorphTarget
  89020. * @param name defines the name of the target
  89021. * @param influence defines the influence to use
  89022. */
  89023. function MorphTarget(
  89024. /** defines the name of the target */
  89025. name, influence, scene) {
  89026. if (influence === void 0) { influence = 0; }
  89027. if (scene === void 0) { scene = null; }
  89028. this.name = name;
  89029. /**
  89030. * Gets or sets the list of animations
  89031. */
  89032. this.animations = new Array();
  89033. this._positions = null;
  89034. this._normals = null;
  89035. this._tangents = null;
  89036. /**
  89037. * Observable raised when the influence changes
  89038. */
  89039. this.onInfluenceChanged = new BABYLON.Observable();
  89040. this._animationPropertiesOverride = null;
  89041. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89042. this.influence = influence;
  89043. }
  89044. Object.defineProperty(MorphTarget.prototype, "influence", {
  89045. /**
  89046. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89047. */
  89048. get: function () {
  89049. return this._influence;
  89050. },
  89051. set: function (influence) {
  89052. if (this._influence === influence) {
  89053. return;
  89054. }
  89055. var previous = this._influence;
  89056. this._influence = influence;
  89057. if (this.onInfluenceChanged.hasObservers) {
  89058. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89059. }
  89060. },
  89061. enumerable: true,
  89062. configurable: true
  89063. });
  89064. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89065. /**
  89066. * Gets or sets the animation properties override
  89067. */
  89068. get: function () {
  89069. if (!this._animationPropertiesOverride && this._scene) {
  89070. return this._scene.animationPropertiesOverride;
  89071. }
  89072. return this._animationPropertiesOverride;
  89073. },
  89074. set: function (value) {
  89075. this._animationPropertiesOverride = value;
  89076. },
  89077. enumerable: true,
  89078. configurable: true
  89079. });
  89080. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89081. /**
  89082. * Gets a boolean defining if the target contains position data
  89083. */
  89084. get: function () {
  89085. return !!this._positions;
  89086. },
  89087. enumerable: true,
  89088. configurable: true
  89089. });
  89090. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89091. /**
  89092. * Gets a boolean defining if the target contains normal data
  89093. */
  89094. get: function () {
  89095. return !!this._normals;
  89096. },
  89097. enumerable: true,
  89098. configurable: true
  89099. });
  89100. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89101. /**
  89102. * Gets a boolean defining if the target contains tangent data
  89103. */
  89104. get: function () {
  89105. return !!this._tangents;
  89106. },
  89107. enumerable: true,
  89108. configurable: true
  89109. });
  89110. /**
  89111. * Affects position data to this target
  89112. * @param data defines the position data to use
  89113. */
  89114. MorphTarget.prototype.setPositions = function (data) {
  89115. this._positions = data;
  89116. };
  89117. /**
  89118. * Gets the position data stored in this target
  89119. * @returns a FloatArray containing the position data (or null if not present)
  89120. */
  89121. MorphTarget.prototype.getPositions = function () {
  89122. return this._positions;
  89123. };
  89124. /**
  89125. * Affects normal data to this target
  89126. * @param data defines the normal data to use
  89127. */
  89128. MorphTarget.prototype.setNormals = function (data) {
  89129. this._normals = data;
  89130. };
  89131. /**
  89132. * Gets the normal data stored in this target
  89133. * @returns a FloatArray containing the normal data (or null if not present)
  89134. */
  89135. MorphTarget.prototype.getNormals = function () {
  89136. return this._normals;
  89137. };
  89138. /**
  89139. * Affects tangent data to this target
  89140. * @param data defines the tangent data to use
  89141. */
  89142. MorphTarget.prototype.setTangents = function (data) {
  89143. this._tangents = data;
  89144. };
  89145. /**
  89146. * Gets the tangent data stored in this target
  89147. * @returns a FloatArray containing the tangent data (or null if not present)
  89148. */
  89149. MorphTarget.prototype.getTangents = function () {
  89150. return this._tangents;
  89151. };
  89152. /**
  89153. * Serializes the current target into a Serialization object
  89154. * @returns the serialized object
  89155. */
  89156. MorphTarget.prototype.serialize = function () {
  89157. var serializationObject = {};
  89158. serializationObject.name = this.name;
  89159. serializationObject.influence = this.influence;
  89160. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89161. if (this.hasNormals) {
  89162. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89163. }
  89164. if (this.hasTangents) {
  89165. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89166. }
  89167. // Animations
  89168. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89169. return serializationObject;
  89170. };
  89171. // Statics
  89172. /**
  89173. * Creates a new target from serialized data
  89174. * @param serializationObject defines the serialized data to use
  89175. * @returns a new MorphTarget
  89176. */
  89177. MorphTarget.Parse = function (serializationObject) {
  89178. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89179. result.setPositions(serializationObject.positions);
  89180. if (serializationObject.normals) {
  89181. result.setNormals(serializationObject.normals);
  89182. }
  89183. if (serializationObject.tangents) {
  89184. result.setTangents(serializationObject.tangents);
  89185. }
  89186. // Animations
  89187. if (serializationObject.animations) {
  89188. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89189. var parsedAnimation = serializationObject.animations[animationIndex];
  89190. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89191. }
  89192. }
  89193. return result;
  89194. };
  89195. /**
  89196. * Creates a MorphTarget from mesh data
  89197. * @param mesh defines the source mesh
  89198. * @param name defines the name to use for the new target
  89199. * @param influence defines the influence to attach to the target
  89200. * @returns a new MorphTarget
  89201. */
  89202. MorphTarget.FromMesh = function (mesh, name, influence) {
  89203. if (!name) {
  89204. name = mesh.name;
  89205. }
  89206. var result = new MorphTarget(name, influence, mesh.getScene());
  89207. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89209. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89210. }
  89211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89212. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89213. }
  89214. return result;
  89215. };
  89216. return MorphTarget;
  89217. }());
  89218. BABYLON.MorphTarget = MorphTarget;
  89219. })(BABYLON || (BABYLON = {}));
  89220. //# sourceMappingURL=babylon.morphTarget.js.map
  89221. var BABYLON;
  89222. (function (BABYLON) {
  89223. /**
  89224. * This class is used to deform meshes using morphing between different targets
  89225. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89226. */
  89227. var MorphTargetManager = /** @class */ (function () {
  89228. /**
  89229. * Creates a new MorphTargetManager
  89230. * @param scene defines the current scene
  89231. */
  89232. function MorphTargetManager(scene) {
  89233. if (scene === void 0) { scene = null; }
  89234. this._targets = new Array();
  89235. this._targetObservable = new Array();
  89236. this._activeTargets = new BABYLON.SmartArray(16);
  89237. this._supportsNormals = false;
  89238. this._supportsTangents = false;
  89239. this._vertexCount = 0;
  89240. this._uniqueId = 0;
  89241. this._tempInfluences = new Array();
  89242. if (!scene) {
  89243. scene = BABYLON.Engine.LastCreatedScene;
  89244. }
  89245. this._scene = scene;
  89246. if (this._scene) {
  89247. this._scene.morphTargetManagers.push(this);
  89248. this._uniqueId = this._scene.getUniqueId();
  89249. }
  89250. }
  89251. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89252. /**
  89253. * Gets the unique ID of this manager
  89254. */
  89255. get: function () {
  89256. return this._uniqueId;
  89257. },
  89258. enumerable: true,
  89259. configurable: true
  89260. });
  89261. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89262. /**
  89263. * Gets the number of vertices handled by this manager
  89264. */
  89265. get: function () {
  89266. return this._vertexCount;
  89267. },
  89268. enumerable: true,
  89269. configurable: true
  89270. });
  89271. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89272. /**
  89273. * Gets a boolean indicating if this manager supports morphing of normals
  89274. */
  89275. get: function () {
  89276. return this._supportsNormals;
  89277. },
  89278. enumerable: true,
  89279. configurable: true
  89280. });
  89281. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89282. /**
  89283. * Gets a boolean indicating if this manager supports morphing of tangents
  89284. */
  89285. get: function () {
  89286. return this._supportsTangents;
  89287. },
  89288. enumerable: true,
  89289. configurable: true
  89290. });
  89291. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89292. /**
  89293. * Gets the number of targets stored in this manager
  89294. */
  89295. get: function () {
  89296. return this._targets.length;
  89297. },
  89298. enumerable: true,
  89299. configurable: true
  89300. });
  89301. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89302. /**
  89303. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89304. */
  89305. get: function () {
  89306. return this._activeTargets.length;
  89307. },
  89308. enumerable: true,
  89309. configurable: true
  89310. });
  89311. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89312. /**
  89313. * Gets the list of influences (one per target)
  89314. */
  89315. get: function () {
  89316. return this._influences;
  89317. },
  89318. enumerable: true,
  89319. configurable: true
  89320. });
  89321. /**
  89322. * Gets the active target at specified index. An active target is a target with an influence > 0
  89323. * @param index defines the index to check
  89324. * @returns the requested target
  89325. */
  89326. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89327. return this._activeTargets.data[index];
  89328. };
  89329. /**
  89330. * Gets the target at specified index
  89331. * @param index defines the index to check
  89332. * @returns the requested target
  89333. */
  89334. MorphTargetManager.prototype.getTarget = function (index) {
  89335. return this._targets[index];
  89336. };
  89337. /**
  89338. * Add a new target to this manager
  89339. * @param target defines the target to add
  89340. */
  89341. MorphTargetManager.prototype.addTarget = function (target) {
  89342. var _this = this;
  89343. this._targets.push(target);
  89344. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89345. _this._syncActiveTargets(needUpdate);
  89346. }));
  89347. this._syncActiveTargets(true);
  89348. };
  89349. /**
  89350. * Removes a target from the manager
  89351. * @param target defines the target to remove
  89352. */
  89353. MorphTargetManager.prototype.removeTarget = function (target) {
  89354. var index = this._targets.indexOf(target);
  89355. if (index >= 0) {
  89356. this._targets.splice(index, 1);
  89357. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89358. this._syncActiveTargets(true);
  89359. }
  89360. };
  89361. /**
  89362. * Serializes the current manager into a Serialization object
  89363. * @returns the serialized object
  89364. */
  89365. MorphTargetManager.prototype.serialize = function () {
  89366. var serializationObject = {};
  89367. serializationObject.id = this.uniqueId;
  89368. serializationObject.targets = [];
  89369. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89370. var target = _a[_i];
  89371. serializationObject.targets.push(target.serialize());
  89372. }
  89373. return serializationObject;
  89374. };
  89375. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89376. var influenceCount = 0;
  89377. this._activeTargets.reset();
  89378. this._supportsNormals = true;
  89379. this._supportsTangents = true;
  89380. this._vertexCount = 0;
  89381. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89382. var target = _a[_i];
  89383. this._activeTargets.push(target);
  89384. this._tempInfluences[influenceCount++] = target.influence;
  89385. var positions = target.getPositions();
  89386. if (positions) {
  89387. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89388. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89389. var vertexCount = positions.length / 3;
  89390. if (this._vertexCount === 0) {
  89391. this._vertexCount = vertexCount;
  89392. }
  89393. else if (this._vertexCount !== vertexCount) {
  89394. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89395. return;
  89396. }
  89397. }
  89398. }
  89399. if (!this._influences || this._influences.length !== influenceCount) {
  89400. this._influences = new Float32Array(influenceCount);
  89401. }
  89402. for (var index = 0; index < influenceCount; index++) {
  89403. this._influences[index] = this._tempInfluences[index];
  89404. }
  89405. if (needUpdate) {
  89406. this.synchronize();
  89407. }
  89408. };
  89409. /**
  89410. * Syncrhonize the targets with all the meshes using this morph target manager
  89411. */
  89412. MorphTargetManager.prototype.synchronize = function () {
  89413. if (!this._scene) {
  89414. return;
  89415. }
  89416. // Flag meshes as dirty to resync with the active targets
  89417. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89418. var mesh = _a[_i];
  89419. if (mesh.morphTargetManager === this) {
  89420. mesh._syncGeometryWithMorphTargetManager();
  89421. }
  89422. }
  89423. };
  89424. // Statics
  89425. /**
  89426. * Creates a new MorphTargetManager from serialized data
  89427. * @param serializationObject defines the serialized data
  89428. * @param scene defines the hosting scene
  89429. * @returns the new MorphTargetManager
  89430. */
  89431. MorphTargetManager.Parse = function (serializationObject, scene) {
  89432. var result = new MorphTargetManager(scene);
  89433. result._uniqueId = serializationObject.id;
  89434. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89435. var targetData = _a[_i];
  89436. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89437. }
  89438. return result;
  89439. };
  89440. return MorphTargetManager;
  89441. }());
  89442. BABYLON.MorphTargetManager = MorphTargetManager;
  89443. })(BABYLON || (BABYLON = {}));
  89444. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89445. var BABYLON;
  89446. (function (BABYLON) {
  89447. var Octree = /** @class */ (function () {
  89448. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89449. if (maxDepth === void 0) { maxDepth = 2; }
  89450. this.maxDepth = maxDepth;
  89451. this.dynamicContent = new Array();
  89452. this._maxBlockCapacity = maxBlockCapacity || 64;
  89453. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89454. this._creationFunc = creationFunc;
  89455. }
  89456. // Methods
  89457. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89458. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89459. };
  89460. Octree.prototype.addMesh = function (entry) {
  89461. for (var index = 0; index < this.blocks.length; index++) {
  89462. var block = this.blocks[index];
  89463. block.addEntry(entry);
  89464. }
  89465. };
  89466. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89467. this._selectionContent.reset();
  89468. for (var index = 0; index < this.blocks.length; index++) {
  89469. var block = this.blocks[index];
  89470. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89471. }
  89472. if (allowDuplicate) {
  89473. this._selectionContent.concat(this.dynamicContent);
  89474. }
  89475. else {
  89476. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89477. }
  89478. return this._selectionContent;
  89479. };
  89480. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89481. this._selectionContent.reset();
  89482. for (var index = 0; index < this.blocks.length; index++) {
  89483. var block = this.blocks[index];
  89484. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89485. }
  89486. if (allowDuplicate) {
  89487. this._selectionContent.concat(this.dynamicContent);
  89488. }
  89489. else {
  89490. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89491. }
  89492. return this._selectionContent;
  89493. };
  89494. Octree.prototype.intersectsRay = function (ray) {
  89495. this._selectionContent.reset();
  89496. for (var index = 0; index < this.blocks.length; index++) {
  89497. var block = this.blocks[index];
  89498. block.intersectsRay(ray, this._selectionContent);
  89499. }
  89500. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89501. return this._selectionContent;
  89502. };
  89503. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89504. target.blocks = new Array();
  89505. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89506. // Segmenting space
  89507. for (var x = 0; x < 2; x++) {
  89508. for (var y = 0; y < 2; y++) {
  89509. for (var z = 0; z < 2; z++) {
  89510. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89511. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89512. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89513. block.addEntries(entries);
  89514. target.blocks.push(block);
  89515. }
  89516. }
  89517. }
  89518. };
  89519. Octree.CreationFuncForMeshes = function (entry, block) {
  89520. var boundingInfo = entry.getBoundingInfo();
  89521. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89522. block.entries.push(entry);
  89523. }
  89524. };
  89525. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89526. var boundingInfo = entry.getBoundingInfo();
  89527. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89528. block.entries.push(entry);
  89529. }
  89530. };
  89531. return Octree;
  89532. }());
  89533. BABYLON.Octree = Octree;
  89534. })(BABYLON || (BABYLON = {}));
  89535. //# sourceMappingURL=babylon.octree.js.map
  89536. var BABYLON;
  89537. (function (BABYLON) {
  89538. var OctreeBlock = /** @class */ (function () {
  89539. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89540. this.entries = new Array();
  89541. this._boundingVectors = new Array();
  89542. this._capacity = capacity;
  89543. this._depth = depth;
  89544. this._maxDepth = maxDepth;
  89545. this._creationFunc = creationFunc;
  89546. this._minPoint = minPoint;
  89547. this._maxPoint = maxPoint;
  89548. this._boundingVectors.push(minPoint.clone());
  89549. this._boundingVectors.push(maxPoint.clone());
  89550. this._boundingVectors.push(minPoint.clone());
  89551. this._boundingVectors[2].x = maxPoint.x;
  89552. this._boundingVectors.push(minPoint.clone());
  89553. this._boundingVectors[3].y = maxPoint.y;
  89554. this._boundingVectors.push(minPoint.clone());
  89555. this._boundingVectors[4].z = maxPoint.z;
  89556. this._boundingVectors.push(maxPoint.clone());
  89557. this._boundingVectors[5].z = minPoint.z;
  89558. this._boundingVectors.push(maxPoint.clone());
  89559. this._boundingVectors[6].x = minPoint.x;
  89560. this._boundingVectors.push(maxPoint.clone());
  89561. this._boundingVectors[7].y = minPoint.y;
  89562. }
  89563. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89564. // Property
  89565. get: function () {
  89566. return this._capacity;
  89567. },
  89568. enumerable: true,
  89569. configurable: true
  89570. });
  89571. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89572. get: function () {
  89573. return this._minPoint;
  89574. },
  89575. enumerable: true,
  89576. configurable: true
  89577. });
  89578. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89579. get: function () {
  89580. return this._maxPoint;
  89581. },
  89582. enumerable: true,
  89583. configurable: true
  89584. });
  89585. // Methods
  89586. OctreeBlock.prototype.addEntry = function (entry) {
  89587. if (this.blocks) {
  89588. for (var index = 0; index < this.blocks.length; index++) {
  89589. var block = this.blocks[index];
  89590. block.addEntry(entry);
  89591. }
  89592. return;
  89593. }
  89594. this._creationFunc(entry, this);
  89595. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  89596. this.createInnerBlocks();
  89597. }
  89598. };
  89599. OctreeBlock.prototype.addEntries = function (entries) {
  89600. for (var index = 0; index < entries.length; index++) {
  89601. var mesh = entries[index];
  89602. this.addEntry(mesh);
  89603. }
  89604. };
  89605. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  89606. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  89607. if (this.blocks) {
  89608. for (var index = 0; index < this.blocks.length; index++) {
  89609. var block = this.blocks[index];
  89610. block.select(frustumPlanes, selection, allowDuplicate);
  89611. }
  89612. return;
  89613. }
  89614. if (allowDuplicate) {
  89615. selection.concat(this.entries);
  89616. }
  89617. else {
  89618. selection.concatWithNoDuplicate(this.entries);
  89619. }
  89620. }
  89621. };
  89622. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  89623. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  89624. if (this.blocks) {
  89625. for (var index = 0; index < this.blocks.length; index++) {
  89626. var block = this.blocks[index];
  89627. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  89628. }
  89629. return;
  89630. }
  89631. if (allowDuplicate) {
  89632. selection.concat(this.entries);
  89633. }
  89634. else {
  89635. selection.concatWithNoDuplicate(this.entries);
  89636. }
  89637. }
  89638. };
  89639. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  89640. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  89641. if (this.blocks) {
  89642. for (var index = 0; index < this.blocks.length; index++) {
  89643. var block = this.blocks[index];
  89644. block.intersectsRay(ray, selection);
  89645. }
  89646. return;
  89647. }
  89648. selection.concatWithNoDuplicate(this.entries);
  89649. }
  89650. };
  89651. OctreeBlock.prototype.createInnerBlocks = function () {
  89652. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  89653. };
  89654. return OctreeBlock;
  89655. }());
  89656. BABYLON.OctreeBlock = OctreeBlock;
  89657. })(BABYLON || (BABYLON = {}));
  89658. //# sourceMappingURL=babylon.octreeBlock.js.map
  89659. var BABYLON;
  89660. (function (BABYLON) {
  89661. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  89662. __extends(VRDistortionCorrectionPostProcess, _super);
  89663. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  89664. var _this = _super.call(this, name, "vrDistortionCorrection", [
  89665. 'LensCenter',
  89666. 'Scale',
  89667. 'ScaleIn',
  89668. 'HmdWarpParam'
  89669. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  89670. _this._isRightEye = isRightEye;
  89671. _this._distortionFactors = vrMetrics.distortionK;
  89672. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  89673. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  89674. _this.adaptScaleToCurrentViewport = true;
  89675. _this.onSizeChangedObservable.add(function () {
  89676. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  89677. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  89678. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  89679. });
  89680. _this.onApplyObservable.add(function (effect) {
  89681. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  89682. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  89683. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  89684. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  89685. });
  89686. return _this;
  89687. }
  89688. return VRDistortionCorrectionPostProcess;
  89689. }(BABYLON.PostProcess));
  89690. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  89691. })(BABYLON || (BABYLON = {}));
  89692. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  89693. var BABYLON;
  89694. (function (BABYLON) {
  89695. /**
  89696. * Postprocess used to generate anaglyphic rendering
  89697. */
  89698. var AnaglyphPostProcess = /** @class */ (function (_super) {
  89699. __extends(AnaglyphPostProcess, _super);
  89700. /**
  89701. * Creates a new AnaglyphPostProcess
  89702. * @param name defines postprocess name
  89703. * @param options defines creation options or target ratio scale
  89704. * @param rigCameras defines cameras using this postprocess
  89705. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  89706. * @param engine defines hosting engine
  89707. * @param reusable defines if the postprocess will be reused multiple times per frame
  89708. */
  89709. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  89710. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  89711. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89712. _this.onApplyObservable.add(function (effect) {
  89713. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  89714. });
  89715. return _this;
  89716. }
  89717. return AnaglyphPostProcess;
  89718. }(BABYLON.PostProcess));
  89719. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  89720. })(BABYLON || (BABYLON = {}));
  89721. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  89722. var BABYLON;
  89723. (function (BABYLON) {
  89724. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  89725. __extends(StereoscopicInterlacePostProcess, _super);
  89726. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  89727. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  89728. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89729. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89730. _this.onSizeChangedObservable.add(function () {
  89731. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89732. });
  89733. _this.onApplyObservable.add(function (effect) {
  89734. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  89735. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  89736. });
  89737. return _this;
  89738. }
  89739. return StereoscopicInterlacePostProcess;
  89740. }(BABYLON.PostProcess));
  89741. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  89742. })(BABYLON || (BABYLON = {}));
  89743. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  89744. var BABYLON;
  89745. (function (BABYLON) {
  89746. /**
  89747. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  89748. * Screen rotation is taken into account.
  89749. */
  89750. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  89751. function FreeCameraDeviceOrientationInput() {
  89752. var _this = this;
  89753. this._screenOrientationAngle = 0;
  89754. this._screenQuaternion = new BABYLON.Quaternion();
  89755. this._alpha = 0;
  89756. this._beta = 0;
  89757. this._gamma = 0;
  89758. this._orientationChanged = function () {
  89759. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  89760. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  89761. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  89762. };
  89763. this._deviceOrientation = function (evt) {
  89764. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  89765. _this._beta = evt.beta !== null ? evt.beta : 0;
  89766. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  89767. };
  89768. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  89769. this._orientationChanged();
  89770. }
  89771. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  89772. get: function () {
  89773. return this._camera;
  89774. },
  89775. set: function (camera) {
  89776. this._camera = camera;
  89777. if (this._camera != null && !this._camera.rotationQuaternion) {
  89778. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  89779. }
  89780. },
  89781. enumerable: true,
  89782. configurable: true
  89783. });
  89784. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89785. window.addEventListener("orientationchange", this._orientationChanged);
  89786. window.addEventListener("deviceorientation", this._deviceOrientation);
  89787. //In certain cases, the attach control is called AFTER orientation was changed,
  89788. //So this is needed.
  89789. this._orientationChanged();
  89790. };
  89791. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  89792. window.removeEventListener("orientationchange", this._orientationChanged);
  89793. window.removeEventListener("deviceorientation", this._deviceOrientation);
  89794. };
  89795. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  89796. //if no device orientation provided, don't update the rotation.
  89797. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  89798. if (!this._alpha)
  89799. return;
  89800. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  89801. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  89802. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  89803. //Mirror on XY Plane
  89804. this._camera.rotationQuaternion.z *= -1;
  89805. this._camera.rotationQuaternion.w *= -1;
  89806. };
  89807. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  89808. return "FreeCameraDeviceOrientationInput";
  89809. };
  89810. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  89811. return "deviceOrientation";
  89812. };
  89813. return FreeCameraDeviceOrientationInput;
  89814. }());
  89815. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  89816. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  89817. })(BABYLON || (BABYLON = {}));
  89818. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  89819. var BABYLON;
  89820. (function (BABYLON) {
  89821. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  89822. function ArcRotateCameraVRDeviceOrientationInput() {
  89823. this.alphaCorrection = 1;
  89824. this.betaCorrection = 1;
  89825. this.gammaCorrection = 1;
  89826. this._alpha = 0;
  89827. this._gamma = 0;
  89828. this._dirty = false;
  89829. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  89830. }
  89831. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89832. this.camera.attachControl(element, noPreventDefault);
  89833. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  89834. };
  89835. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  89836. if (evt.alpha !== null) {
  89837. this._alpha = +evt.alpha | 0;
  89838. }
  89839. if (evt.gamma !== null) {
  89840. this._gamma = +evt.gamma | 0;
  89841. }
  89842. this._dirty = true;
  89843. };
  89844. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  89845. if (this._dirty) {
  89846. this._dirty = false;
  89847. if (this._gamma < 0) {
  89848. this._gamma = 180 + this._gamma;
  89849. }
  89850. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  89851. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  89852. }
  89853. };
  89854. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  89855. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  89856. };
  89857. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  89858. return "ArcRotateCameraVRDeviceOrientationInput";
  89859. };
  89860. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  89861. return "VRDeviceOrientation";
  89862. };
  89863. return ArcRotateCameraVRDeviceOrientationInput;
  89864. }());
  89865. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  89866. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  89867. })(BABYLON || (BABYLON = {}));
  89868. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  89869. var BABYLON;
  89870. (function (BABYLON) {
  89871. var VRCameraMetrics = /** @class */ (function () {
  89872. function VRCameraMetrics() {
  89873. this.compensateDistortion = true;
  89874. }
  89875. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  89876. get: function () {
  89877. return this.hResolution / (2 * this.vResolution);
  89878. },
  89879. enumerable: true,
  89880. configurable: true
  89881. });
  89882. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  89883. get: function () {
  89884. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  89885. },
  89886. enumerable: true,
  89887. configurable: true
  89888. });
  89889. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89890. get: function () {
  89891. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89892. var h = (4 * meters) / this.hScreenSize;
  89893. return BABYLON.Matrix.Translation(h, 0, 0);
  89894. },
  89895. enumerable: true,
  89896. configurable: true
  89897. });
  89898. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89899. get: function () {
  89900. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89901. var h = (4 * meters) / this.hScreenSize;
  89902. return BABYLON.Matrix.Translation(-h, 0, 0);
  89903. },
  89904. enumerable: true,
  89905. configurable: true
  89906. });
  89907. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89908. get: function () {
  89909. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89910. },
  89911. enumerable: true,
  89912. configurable: true
  89913. });
  89914. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89915. get: function () {
  89916. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89917. },
  89918. enumerable: true,
  89919. configurable: true
  89920. });
  89921. VRCameraMetrics.GetDefault = function () {
  89922. var result = new VRCameraMetrics();
  89923. result.hResolution = 1280;
  89924. result.vResolution = 800;
  89925. result.hScreenSize = 0.149759993;
  89926. result.vScreenSize = 0.0935999975;
  89927. result.vScreenCenter = 0.0467999987;
  89928. result.eyeToScreenDistance = 0.0410000011;
  89929. result.lensSeparationDistance = 0.0635000020;
  89930. result.interpupillaryDistance = 0.0640000030;
  89931. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89932. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89933. result.postProcessScaleFactor = 1.714605507808412;
  89934. result.lensCenterOffset = 0.151976421;
  89935. return result;
  89936. };
  89937. return VRCameraMetrics;
  89938. }());
  89939. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89940. })(BABYLON || (BABYLON = {}));
  89941. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89942. var BABYLON;
  89943. (function (BABYLON) {
  89944. /**
  89945. * This represents a WebVR camera.
  89946. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89947. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89948. */
  89949. var WebVRFreeCamera = /** @class */ (function (_super) {
  89950. __extends(WebVRFreeCamera, _super);
  89951. /**
  89952. * Instantiates a WebVRFreeCamera.
  89953. * @param name The name of the WebVRFreeCamera
  89954. * @param position The starting anchor position for the camera
  89955. * @param scene The scene the camera belongs to
  89956. * @param webVROptions a set of customizable options for the webVRCamera
  89957. */
  89958. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89959. if (webVROptions === void 0) { webVROptions = {}; }
  89960. var _this = _super.call(this, name, position, scene) || this;
  89961. _this.webVROptions = webVROptions;
  89962. /**
  89963. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89964. */
  89965. _this._vrDevice = null;
  89966. /**
  89967. * The rawPose of the vrDevice.
  89968. */
  89969. _this.rawPose = null;
  89970. _this._specsVersion = "1.1";
  89971. _this._attached = false;
  89972. _this._descendants = [];
  89973. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89974. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89975. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89976. _this._standingMatrix = null;
  89977. /**
  89978. * Represents device position in babylon space.
  89979. */
  89980. _this.devicePosition = BABYLON.Vector3.Zero();
  89981. /**
  89982. * Represents device rotation in babylon space.
  89983. */
  89984. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89985. /**
  89986. * The scale of the device to be used when translating from device space to babylon space.
  89987. */
  89988. _this.deviceScaleFactor = 1;
  89989. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89990. _this._worldToDevice = BABYLON.Matrix.Identity();
  89991. /**
  89992. * References to the webVR controllers for the vrDevice.
  89993. */
  89994. _this.controllers = [];
  89995. /**
  89996. * Emits an event when a controller is attached.
  89997. */
  89998. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89999. /**
  90000. * Emits an event when a controller's mesh has been loaded;
  90001. */
  90002. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90003. /**
  90004. * If the rig cameras be used as parent instead of this camera.
  90005. */
  90006. _this.rigParenting = true;
  90007. _this._defaultHeight = undefined;
  90008. _this._workingVector = BABYLON.Vector3.Zero();
  90009. _this._oneVector = BABYLON.Vector3.One();
  90010. _this._workingMatrix = BABYLON.Matrix.Identity();
  90011. _this._cache.position = BABYLON.Vector3.Zero();
  90012. if (webVROptions.defaultHeight) {
  90013. _this._defaultHeight = webVROptions.defaultHeight;
  90014. _this.position.y = _this._defaultHeight;
  90015. }
  90016. _this.minZ = 0.1;
  90017. //legacy support - the compensation boolean was removed.
  90018. if (arguments.length === 5) {
  90019. _this.webVROptions = arguments[4];
  90020. }
  90021. // default webVR options
  90022. if (_this.webVROptions.trackPosition == undefined) {
  90023. _this.webVROptions.trackPosition = true;
  90024. }
  90025. if (_this.webVROptions.controllerMeshes == undefined) {
  90026. _this.webVROptions.controllerMeshes = true;
  90027. }
  90028. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90029. _this.webVROptions.defaultLightingOnControllers = true;
  90030. }
  90031. _this.rotationQuaternion = new BABYLON.Quaternion();
  90032. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90033. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90034. }
  90035. //enable VR
  90036. var engine = _this.getEngine();
  90037. _this._onVREnabled = function (success) { if (success) {
  90038. _this.initControllers();
  90039. } };
  90040. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90041. engine.initWebVR().add(function (event) {
  90042. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90043. return;
  90044. }
  90045. _this._vrDevice = event.vrDisplay;
  90046. //reset the rig parameters.
  90047. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90048. if (_this._attached) {
  90049. _this.getEngine().enableVR();
  90050. }
  90051. });
  90052. if (typeof (VRFrameData) !== "undefined")
  90053. _this._frameData = new VRFrameData();
  90054. /**
  90055. * The idea behind the following lines:
  90056. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90057. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90058. * the second will not show it correctly.
  90059. *
  90060. * To solve this - each object that has the camera as parent will be added to a protected array.
  90061. * When the rig camera renders, it will take this array and set all of those to be its children.
  90062. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90063. * Amazing!
  90064. */
  90065. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90066. if (camera.parent === _this && _this.rigParenting) {
  90067. _this._descendants = _this.getDescendants(true, function (n) {
  90068. // don't take the cameras or the controllers!
  90069. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90070. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90071. return !isController && !isRigCamera;
  90072. });
  90073. _this._descendants.forEach(function (node) {
  90074. node.parent = camera;
  90075. });
  90076. }
  90077. });
  90078. scene.onAfterCameraRenderObservable.add(function (camera) {
  90079. if (camera.parent === _this && _this.rigParenting) {
  90080. _this._descendants.forEach(function (node) {
  90081. node.parent = _this;
  90082. });
  90083. }
  90084. });
  90085. return _this;
  90086. }
  90087. /**
  90088. * Gets the device distance from the ground in meters.
  90089. * @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.
  90090. */
  90091. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90092. if (this._standingMatrix) {
  90093. // Add standing matrix offset to get real offset from ground in room
  90094. this._standingMatrix.getTranslationToRef(this._workingVector);
  90095. return this._deviceRoomPosition.y + this._workingVector.y;
  90096. }
  90097. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90098. return this._defaultHeight || 0;
  90099. };
  90100. /**
  90101. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90102. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90103. */
  90104. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90105. var _this = this;
  90106. if (callback === void 0) { callback = function (bool) { }; }
  90107. // Use standing matrix if available
  90108. this.getEngine().initWebVRAsync().then(function (result) {
  90109. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90110. callback(false);
  90111. }
  90112. else {
  90113. _this._standingMatrix = new BABYLON.Matrix();
  90114. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90115. if (!_this.getScene().useRightHandedSystem) {
  90116. [2, 6, 8, 9, 14].forEach(function (num) {
  90117. if (_this._standingMatrix) {
  90118. _this._standingMatrix.m[num] *= -1;
  90119. }
  90120. });
  90121. }
  90122. callback(true);
  90123. }
  90124. });
  90125. };
  90126. /**
  90127. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90128. * @returns A promise with a boolean set to if the standing matrix is supported.
  90129. */
  90130. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90131. var _this = this;
  90132. return new Promise(function (res, rej) {
  90133. _this.useStandingMatrix(function (supported) {
  90134. res(supported);
  90135. });
  90136. });
  90137. };
  90138. /**
  90139. * Disposes the camera
  90140. */
  90141. WebVRFreeCamera.prototype.dispose = function () {
  90142. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90143. _super.prototype.dispose.call(this);
  90144. };
  90145. /**
  90146. * Gets a vrController by name.
  90147. * @param name The name of the controller to retreive
  90148. * @returns the controller matching the name specified or null if not found
  90149. */
  90150. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90151. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90152. var gp = _a[_i];
  90153. if (gp.hand === name) {
  90154. return gp;
  90155. }
  90156. }
  90157. return null;
  90158. };
  90159. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90160. /**
  90161. * The controller corrisponding to the users left hand.
  90162. */
  90163. get: function () {
  90164. if (!this._leftController) {
  90165. this._leftController = this.getControllerByName("left");
  90166. }
  90167. return this._leftController;
  90168. },
  90169. enumerable: true,
  90170. configurable: true
  90171. });
  90172. ;
  90173. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90174. /**
  90175. * The controller corrisponding to the users right hand.
  90176. */
  90177. get: function () {
  90178. if (!this._rightController) {
  90179. this._rightController = this.getControllerByName("right");
  90180. }
  90181. return this._rightController;
  90182. },
  90183. enumerable: true,
  90184. configurable: true
  90185. });
  90186. ;
  90187. /**
  90188. * Casts a ray forward from the vrCamera's gaze.
  90189. * @param length Length of the ray (default: 100)
  90190. * @returns the ray corrisponding to the gaze
  90191. */
  90192. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90193. if (length === void 0) { length = 100; }
  90194. if (this.leftCamera) {
  90195. // Use left eye to avoid computation to compute center on every call
  90196. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90197. }
  90198. else {
  90199. return _super.prototype.getForwardRay.call(this, length);
  90200. }
  90201. };
  90202. /**
  90203. * Updates the camera based on device's frame data
  90204. */
  90205. WebVRFreeCamera.prototype._checkInputs = function () {
  90206. if (this._vrDevice && this._vrDevice.isPresenting) {
  90207. this._vrDevice.getFrameData(this._frameData);
  90208. this.updateFromDevice(this._frameData.pose);
  90209. }
  90210. _super.prototype._checkInputs.call(this);
  90211. };
  90212. /**
  90213. * Updates the poseControlled values based on the input device pose.
  90214. * @param poseData Pose coming from the device
  90215. */
  90216. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90217. if (poseData && poseData.orientation) {
  90218. this.rawPose = poseData;
  90219. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90220. if (this.getScene().useRightHandedSystem) {
  90221. this._deviceRoomRotationQuaternion.z *= -1;
  90222. this._deviceRoomRotationQuaternion.w *= -1;
  90223. }
  90224. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90225. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90226. if (this.getScene().useRightHandedSystem) {
  90227. this._deviceRoomPosition.z *= -1;
  90228. }
  90229. }
  90230. }
  90231. };
  90232. /**
  90233. * WebVR's attach control will start broadcasting frames to the device.
  90234. * Note that in certain browsers (chrome for example) this function must be called
  90235. * within a user-interaction callback. Example:
  90236. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90237. *
  90238. * @param element html element to attach the vrDevice to
  90239. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90240. */
  90241. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90242. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90243. this._attached = true;
  90244. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90245. if (this._vrDevice) {
  90246. this.getEngine().enableVR();
  90247. }
  90248. };
  90249. /**
  90250. * Detaches the camera from the html element and disables VR
  90251. *
  90252. * @param element html element to detach from
  90253. */
  90254. WebVRFreeCamera.prototype.detachControl = function (element) {
  90255. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90256. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90257. _super.prototype.detachControl.call(this, element);
  90258. this._attached = false;
  90259. this.getEngine().disableVR();
  90260. };
  90261. /**
  90262. * @returns the name of this class
  90263. */
  90264. WebVRFreeCamera.prototype.getClassName = function () {
  90265. return "WebVRFreeCamera";
  90266. };
  90267. /**
  90268. * Calls resetPose on the vrDisplay
  90269. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90270. */
  90271. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90272. //uses the vrDisplay's "resetPose()".
  90273. //pitch and roll won't be affected.
  90274. this._vrDevice.resetPose();
  90275. };
  90276. /**
  90277. * Updates the rig cameras (left and right eye)
  90278. */
  90279. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90280. var camLeft = this._rigCameras[0];
  90281. var camRight = this._rigCameras[1];
  90282. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90283. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90284. camLeft.position.copyFrom(this._deviceRoomPosition);
  90285. camRight.position.copyFrom(this._deviceRoomPosition);
  90286. };
  90287. /**
  90288. * Updates the cached values of the camera
  90289. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90290. */
  90291. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90292. var _this = this;
  90293. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90294. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90295. if (!this.updateCacheCalled) {
  90296. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90297. this.updateCacheCalled = true;
  90298. this.update();
  90299. }
  90300. // Set working vector to the device position in room space rotated by the new rotation
  90301. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90302. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90303. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90304. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90305. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90306. // Add translation from anchor position
  90307. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90308. this._workingVector.addInPlace(this.position);
  90309. this._workingVector.subtractInPlace(this._cache.position);
  90310. this._deviceToWorld.setTranslation(this._workingVector);
  90311. // Set an inverted matrix to be used when updating the camera
  90312. this._deviceToWorld.invertToRef(this._worldToDevice);
  90313. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90314. this.controllers.forEach(function (controller) {
  90315. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90316. controller.update();
  90317. });
  90318. }
  90319. if (!ignoreParentClass) {
  90320. _super.prototype._updateCache.call(this);
  90321. }
  90322. this.updateCacheCalled = false;
  90323. };
  90324. /**
  90325. * Updates the current device position and rotation in the babylon world
  90326. */
  90327. WebVRFreeCamera.prototype.update = function () {
  90328. // Get current device position in babylon world
  90329. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90330. // Get current device rotation in babylon world
  90331. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90332. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90333. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90334. _super.prototype.update.call(this);
  90335. };
  90336. /**
  90337. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90338. * @returns an identity matrix
  90339. */
  90340. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90341. return BABYLON.Matrix.Identity();
  90342. };
  90343. /**
  90344. * This function is called by the two RIG cameras.
  90345. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90346. */
  90347. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90348. var _this = this;
  90349. // Update the parent camera prior to using a child camera to avoid desynchronization
  90350. var parentCamera = this._cameraRigParams["parentCamera"];
  90351. parentCamera._updateCache();
  90352. //WebVR 1.1
  90353. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90354. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90355. if (!this.getScene().useRightHandedSystem) {
  90356. [2, 6, 8, 9, 14].forEach(function (num) {
  90357. _this._webvrViewMatrix.m[num] *= -1;
  90358. });
  90359. }
  90360. // update the camera rotation matrix
  90361. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90362. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90363. // Computing target and final matrix
  90364. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90365. // should the view matrix be updated with scale and position offset?
  90366. if (parentCamera.deviceScaleFactor !== 1) {
  90367. this._webvrViewMatrix.invert();
  90368. // scale the position, if set
  90369. if (parentCamera.deviceScaleFactor) {
  90370. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90371. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90372. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90373. }
  90374. this._webvrViewMatrix.invert();
  90375. }
  90376. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90377. // Compute global position
  90378. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90379. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90380. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90381. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90382. this._markSyncedWithParent();
  90383. return this._webvrViewMatrix;
  90384. };
  90385. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90386. var _this = this;
  90387. var parentCamera = this.parent;
  90388. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90389. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90390. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90391. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90392. //babylon compatible matrix
  90393. if (!this.getScene().useRightHandedSystem) {
  90394. [8, 9, 10, 11].forEach(function (num) {
  90395. _this._projectionMatrix.m[num] *= -1;
  90396. });
  90397. }
  90398. return this._projectionMatrix;
  90399. };
  90400. /**
  90401. * Initializes the controllers and their meshes
  90402. */
  90403. WebVRFreeCamera.prototype.initControllers = function () {
  90404. var _this = this;
  90405. this.controllers = [];
  90406. var manager = this.getScene().gamepadManager;
  90407. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90408. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90409. var webVrController = gamepad;
  90410. if (webVrController.defaultModel) {
  90411. webVrController.defaultModel.setEnabled(false);
  90412. }
  90413. if (webVrController.hand === "right") {
  90414. _this._rightController = null;
  90415. }
  90416. if (webVrController.hand === "left") {
  90417. _this._leftController = null;
  90418. }
  90419. var controllerIndex = _this.controllers.indexOf(webVrController);
  90420. if (controllerIndex !== -1) {
  90421. _this.controllers.splice(controllerIndex, 1);
  90422. }
  90423. }
  90424. });
  90425. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90426. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90427. var webVrController_1 = gamepad;
  90428. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90429. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90430. if (_this.webVROptions.controllerMeshes) {
  90431. if (webVrController_1.defaultModel) {
  90432. webVrController_1.defaultModel.setEnabled(true);
  90433. }
  90434. else {
  90435. // Load the meshes
  90436. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90437. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90438. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90439. if (_this.webVROptions.defaultLightingOnControllers) {
  90440. if (!_this._lightOnControllers) {
  90441. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90442. }
  90443. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90444. var children = mesh.getChildren();
  90445. if (children.length !== 0) {
  90446. children.forEach(function (mesh) {
  90447. light.includedOnlyMeshes.push(mesh);
  90448. activateLightOnSubMeshes_1(mesh, light);
  90449. });
  90450. }
  90451. };
  90452. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90453. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90454. }
  90455. });
  90456. }
  90457. }
  90458. webVrController_1.attachToPoseControlledCamera(_this);
  90459. // since this is async - sanity check. Is the controller already stored?
  90460. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90461. //add to the controllers array
  90462. _this.controllers.push(webVrController_1);
  90463. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90464. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90465. // So we're overriding setting left & right manually to be sure
  90466. var firstViveWandDetected = false;
  90467. for (var i = 0; i < _this.controllers.length; i++) {
  90468. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90469. if (!firstViveWandDetected) {
  90470. firstViveWandDetected = true;
  90471. _this.controllers[i].hand = "left";
  90472. }
  90473. else {
  90474. _this.controllers[i].hand = "right";
  90475. }
  90476. }
  90477. }
  90478. //did we find enough controllers? Great! let the developer know.
  90479. if (_this.controllers.length >= 2) {
  90480. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90481. }
  90482. }
  90483. }
  90484. });
  90485. };
  90486. return WebVRFreeCamera;
  90487. }(BABYLON.FreeCamera));
  90488. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90489. })(BABYLON || (BABYLON = {}));
  90490. //# sourceMappingURL=babylon.webVRCamera.js.map
  90491. var BABYLON;
  90492. (function (BABYLON) {
  90493. // We're mainly based on the logic defined into the FreeCamera code
  90494. /**
  90495. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90496. * being tilted forward or back and left or right.
  90497. */
  90498. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90499. __extends(DeviceOrientationCamera, _super);
  90500. /**
  90501. * Creates a new device orientation camera
  90502. * @param name The name of the camera
  90503. * @param position The start position camera
  90504. * @param scene The scene the camera belongs to
  90505. */
  90506. function DeviceOrientationCamera(name, position, scene) {
  90507. var _this = _super.call(this, name, position, scene) || this;
  90508. _this._quaternionCache = new BABYLON.Quaternion();
  90509. _this.inputs.addDeviceOrientation();
  90510. return _this;
  90511. }
  90512. /**
  90513. * Gets the current instance class name ("DeviceOrientationCamera").
  90514. * This helps avoiding instanceof at run time.
  90515. * @returns the class name
  90516. */
  90517. DeviceOrientationCamera.prototype.getClassName = function () {
  90518. return "DeviceOrientationCamera";
  90519. };
  90520. /**
  90521. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90522. */
  90523. DeviceOrientationCamera.prototype._checkInputs = function () {
  90524. _super.prototype._checkInputs.call(this);
  90525. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90526. if (this._initialQuaternion) {
  90527. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90528. }
  90529. };
  90530. /**
  90531. * Reset the camera to its default orientation on the specified axis only.
  90532. * @param axis The axis to reset
  90533. */
  90534. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90535. var _this = this;
  90536. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90537. //can only work if this camera has a rotation quaternion already.
  90538. if (!this.rotationQuaternion)
  90539. return;
  90540. if (!this._initialQuaternion) {
  90541. this._initialQuaternion = new BABYLON.Quaternion();
  90542. }
  90543. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90544. ['x', 'y', 'z'].forEach(function (axisName) {
  90545. if (!axis[axisName]) {
  90546. _this._initialQuaternion[axisName] = 0;
  90547. }
  90548. else {
  90549. _this._initialQuaternion[axisName] *= -1;
  90550. }
  90551. });
  90552. this._initialQuaternion.normalize();
  90553. //force rotation update
  90554. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90555. };
  90556. return DeviceOrientationCamera;
  90557. }(BABYLON.FreeCamera));
  90558. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90559. })(BABYLON || (BABYLON = {}));
  90560. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90561. var BABYLON;
  90562. (function (BABYLON) {
  90563. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90564. __extends(VRDeviceOrientationFreeCamera, _super);
  90565. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90566. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90567. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90568. var _this = _super.call(this, name, position, scene) || this;
  90569. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90570. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90571. return _this;
  90572. }
  90573. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90574. return "VRDeviceOrientationFreeCamera";
  90575. };
  90576. return VRDeviceOrientationFreeCamera;
  90577. }(BABYLON.DeviceOrientationCamera));
  90578. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90579. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90580. __extends(VRDeviceOrientationGamepadCamera, _super);
  90581. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90582. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90583. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90584. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90585. _this.inputs.addGamepad();
  90586. return _this;
  90587. }
  90588. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90589. return "VRDeviceOrientationGamepadCamera";
  90590. };
  90591. return VRDeviceOrientationGamepadCamera;
  90592. }(VRDeviceOrientationFreeCamera));
  90593. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  90594. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  90595. __extends(VRDeviceOrientationArcRotateCamera, _super);
  90596. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  90597. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90598. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90599. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90600. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90601. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90602. _this.inputs.addVRDeviceOrientation();
  90603. return _this;
  90604. }
  90605. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  90606. return "VRDeviceOrientationArcRotateCamera";
  90607. };
  90608. return VRDeviceOrientationArcRotateCamera;
  90609. }(BABYLON.ArcRotateCamera));
  90610. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  90611. })(BABYLON || (BABYLON = {}));
  90612. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  90613. var BABYLON;
  90614. (function (BABYLON) {
  90615. /**
  90616. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  90617. */
  90618. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  90619. __extends(AnaglyphFreeCamera, _super);
  90620. /**
  90621. * Creates a new AnaglyphFreeCamera
  90622. * @param name defines camera name
  90623. * @param position defines initial position
  90624. * @param interaxialDistance defines distance between each color axis
  90625. * @param scene defines the hosting scene
  90626. */
  90627. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  90628. var _this = _super.call(this, name, position, scene) || this;
  90629. _this.interaxialDistance = interaxialDistance;
  90630. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90631. return _this;
  90632. }
  90633. /**
  90634. * Gets camera class name
  90635. * @returns AnaglyphFreeCamera
  90636. */
  90637. AnaglyphFreeCamera.prototype.getClassName = function () {
  90638. return "AnaglyphFreeCamera";
  90639. };
  90640. return AnaglyphFreeCamera;
  90641. }(BABYLON.FreeCamera));
  90642. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  90643. /**
  90644. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  90645. */
  90646. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  90647. __extends(AnaglyphArcRotateCamera, _super);
  90648. /**
  90649. * Creates a new AnaglyphArcRotateCamera
  90650. * @param name defines camera name
  90651. * @param alpha defines alpha angle (in radians)
  90652. * @param beta defines beta angle (in radians)
  90653. * @param radius defines radius
  90654. * @param target defines camera target
  90655. * @param interaxialDistance defines distance between each color axis
  90656. * @param scene defines the hosting scene
  90657. */
  90658. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  90659. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90660. _this.interaxialDistance = interaxialDistance;
  90661. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90662. return _this;
  90663. }
  90664. /**
  90665. * Gets camera class name
  90666. * @returns AnaglyphArcRotateCamera
  90667. */
  90668. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  90669. return "AnaglyphArcRotateCamera";
  90670. };
  90671. return AnaglyphArcRotateCamera;
  90672. }(BABYLON.ArcRotateCamera));
  90673. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  90674. /**
  90675. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  90676. */
  90677. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  90678. __extends(AnaglyphGamepadCamera, _super);
  90679. /**
  90680. * Creates a new AnaglyphGamepadCamera
  90681. * @param name defines camera name
  90682. * @param position defines initial position
  90683. * @param interaxialDistance defines distance between each color axis
  90684. * @param scene defines the hosting scene
  90685. */
  90686. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  90687. var _this = _super.call(this, name, position, scene) || this;
  90688. _this.interaxialDistance = interaxialDistance;
  90689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90690. return _this;
  90691. }
  90692. /**
  90693. * Gets camera class name
  90694. * @returns AnaglyphGamepadCamera
  90695. */
  90696. AnaglyphGamepadCamera.prototype.getClassName = function () {
  90697. return "AnaglyphGamepadCamera";
  90698. };
  90699. return AnaglyphGamepadCamera;
  90700. }(BABYLON.GamepadCamera));
  90701. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  90702. /**
  90703. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  90704. */
  90705. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  90706. __extends(AnaglyphUniversalCamera, _super);
  90707. /**
  90708. * Creates a new AnaglyphUniversalCamera
  90709. * @param name defines camera name
  90710. * @param position defines initial position
  90711. * @param interaxialDistance defines distance between each color axis
  90712. * @param scene defines the hosting scene
  90713. */
  90714. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  90715. var _this = _super.call(this, name, position, scene) || this;
  90716. _this.interaxialDistance = interaxialDistance;
  90717. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90718. return _this;
  90719. }
  90720. /**
  90721. * Gets camera class name
  90722. * @returns AnaglyphUniversalCamera
  90723. */
  90724. AnaglyphUniversalCamera.prototype.getClassName = function () {
  90725. return "AnaglyphUniversalCamera";
  90726. };
  90727. return AnaglyphUniversalCamera;
  90728. }(BABYLON.UniversalCamera));
  90729. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  90730. /**
  90731. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  90732. */
  90733. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  90734. __extends(StereoscopicFreeCamera, _super);
  90735. /**
  90736. * Creates a new StereoscopicFreeCamera
  90737. * @param name defines camera name
  90738. * @param position defines initial position
  90739. * @param interaxialDistance defines distance between each color axis
  90740. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90741. * @param scene defines the hosting scene
  90742. */
  90743. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90744. var _this = _super.call(this, name, position, scene) || this;
  90745. _this.interaxialDistance = interaxialDistance;
  90746. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90747. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90748. return _this;
  90749. }
  90750. /**
  90751. * Gets camera class name
  90752. * @returns StereoscopicFreeCamera
  90753. */
  90754. StereoscopicFreeCamera.prototype.getClassName = function () {
  90755. return "StereoscopicFreeCamera";
  90756. };
  90757. return StereoscopicFreeCamera;
  90758. }(BABYLON.FreeCamera));
  90759. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  90760. /**
  90761. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  90762. */
  90763. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  90764. __extends(StereoscopicArcRotateCamera, _super);
  90765. /**
  90766. * Creates a new StereoscopicArcRotateCamera
  90767. * @param name defines camera name
  90768. * @param alpha defines alpha angle (in radians)
  90769. * @param beta defines beta angle (in radians)
  90770. * @param radius defines radius
  90771. * @param target defines camera target
  90772. * @param interaxialDistance defines distance between each color axis
  90773. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90774. * @param scene defines the hosting scene
  90775. */
  90776. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  90777. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90778. _this.interaxialDistance = interaxialDistance;
  90779. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90780. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90781. return _this;
  90782. }
  90783. /**
  90784. * Gets camera class name
  90785. * @returns StereoscopicArcRotateCamera
  90786. */
  90787. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  90788. return "StereoscopicArcRotateCamera";
  90789. };
  90790. return StereoscopicArcRotateCamera;
  90791. }(BABYLON.ArcRotateCamera));
  90792. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  90793. /**
  90794. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  90795. */
  90796. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  90797. __extends(StereoscopicGamepadCamera, _super);
  90798. /**
  90799. * Creates a new StereoscopicGamepadCamera
  90800. * @param name defines camera name
  90801. * @param position defines initial position
  90802. * @param interaxialDistance defines distance between each color axis
  90803. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90804. * @param scene defines the hosting scene
  90805. */
  90806. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90807. var _this = _super.call(this, name, position, scene) || this;
  90808. _this.interaxialDistance = interaxialDistance;
  90809. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90810. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90811. return _this;
  90812. }
  90813. /**
  90814. * Gets camera class name
  90815. * @returns StereoscopicGamepadCamera
  90816. */
  90817. StereoscopicGamepadCamera.prototype.getClassName = function () {
  90818. return "StereoscopicGamepadCamera";
  90819. };
  90820. return StereoscopicGamepadCamera;
  90821. }(BABYLON.GamepadCamera));
  90822. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  90823. /**
  90824. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  90825. */
  90826. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  90827. __extends(StereoscopicUniversalCamera, _super);
  90828. /**
  90829. * Creates a new StereoscopicUniversalCamera
  90830. * @param name defines camera name
  90831. * @param position defines initial position
  90832. * @param interaxialDistance defines distance between each color axis
  90833. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90834. * @param scene defines the hosting scene
  90835. */
  90836. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90837. var _this = _super.call(this, name, position, scene) || this;
  90838. _this.interaxialDistance = interaxialDistance;
  90839. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90840. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90841. return _this;
  90842. }
  90843. /**
  90844. * Gets camera class name
  90845. * @returns StereoscopicUniversalCamera
  90846. */
  90847. StereoscopicUniversalCamera.prototype.getClassName = function () {
  90848. return "StereoscopicUniversalCamera";
  90849. };
  90850. return StereoscopicUniversalCamera;
  90851. }(BABYLON.UniversalCamera));
  90852. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  90853. })(BABYLON || (BABYLON = {}));
  90854. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  90855. var BABYLON;
  90856. (function (BABYLON) {
  90857. var VRExperienceHelperGazer = /** @class */ (function () {
  90858. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  90859. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  90860. this.scene = scene;
  90861. this._pointerDownOnMeshAsked = false;
  90862. this._isActionableMesh = false;
  90863. this._teleportationRequestInitiated = false;
  90864. this._teleportationBackRequestInitiated = false;
  90865. this._rotationRightAsked = false;
  90866. this._rotationLeftAsked = false;
  90867. this._dpadPressed = true;
  90868. this._activePointer = false;
  90869. this._id = VRExperienceHelperGazer._idCounter++;
  90870. // Gaze tracker
  90871. if (!gazeTrackerToClone) {
  90872. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  90873. this._gazeTracker.bakeCurrentTransformIntoVertices();
  90874. this._gazeTracker.isPickable = false;
  90875. this._gazeTracker.isVisible = false;
  90876. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  90877. targetMat.specularColor = BABYLON.Color3.Black();
  90878. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90879. targetMat.backFaceCulling = false;
  90880. this._gazeTracker.material = targetMat;
  90881. }
  90882. else {
  90883. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  90884. }
  90885. }
  90886. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  90887. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  90888. };
  90889. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90890. this._pointerDownOnMeshAsked = true;
  90891. if (this._currentHit) {
  90892. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90893. }
  90894. };
  90895. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90896. if (this._currentHit) {
  90897. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90898. }
  90899. this._pointerDownOnMeshAsked = false;
  90900. };
  90901. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90902. this._activePointer = true;
  90903. };
  90904. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90905. this._activePointer = false;
  90906. };
  90907. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90908. if (distance === void 0) { distance = 100; }
  90909. };
  90910. VRExperienceHelperGazer.prototype.dispose = function () {
  90911. this._interactionsEnabled = false;
  90912. this._teleportationEnabled = false;
  90913. if (this._gazeTracker) {
  90914. this._gazeTracker.dispose();
  90915. }
  90916. };
  90917. VRExperienceHelperGazer._idCounter = 0;
  90918. return VRExperienceHelperGazer;
  90919. }());
  90920. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90921. __extends(VRExperienceHelperControllerGazer, _super);
  90922. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90923. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90924. _this.webVRController = webVRController;
  90925. // Laser pointer
  90926. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90927. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90928. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90929. laserPointerMaterial.alpha = 0.6;
  90930. _this._laserPointer.material = laserPointerMaterial;
  90931. _this._laserPointer.rotation.x = Math.PI / 2;
  90932. _this._laserPointer.position.z = -0.5;
  90933. _this._laserPointer.isVisible = false;
  90934. _this._laserPointer.isPickable = false;
  90935. if (!webVRController.mesh) {
  90936. // Create an empty mesh that is used prior to loading the high quality model
  90937. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90938. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90939. preloadPointerPose.rotation.x = -0.7;
  90940. preloadMesh.addChild(preloadPointerPose);
  90941. webVRController.attachToMesh(preloadMesh);
  90942. }
  90943. _this._setLaserPointerParent(webVRController.mesh);
  90944. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90945. _this._setLaserPointerParent(mesh);
  90946. });
  90947. return _this;
  90948. }
  90949. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90950. return this.webVRController.getForwardRay(length);
  90951. };
  90952. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90953. _super.prototype._activatePointer.call(this);
  90954. this._laserPointer.isVisible = true;
  90955. };
  90956. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90957. _super.prototype._deactivatePointer.call(this);
  90958. this._laserPointer.isVisible = false;
  90959. };
  90960. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90961. this._laserPointer.material.emissiveColor = color;
  90962. };
  90963. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90964. var makeNotPick = function (root) {
  90965. root.name += " laserPointer";
  90966. root.isPickable = false;
  90967. root.getChildMeshes().forEach(function (c) {
  90968. makeNotPick(c);
  90969. });
  90970. };
  90971. makeNotPick(mesh);
  90972. var childMeshes = mesh.getChildMeshes();
  90973. this.webVRController._pointingPoseNode = null;
  90974. for (var i = 0; i < childMeshes.length; i++) {
  90975. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90976. mesh = childMeshes[i];
  90977. this.webVRController._pointingPoseNode = mesh;
  90978. break;
  90979. }
  90980. }
  90981. this._laserPointer.parent = mesh;
  90982. };
  90983. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90984. if (distance === void 0) { distance = 100; }
  90985. this._laserPointer.scaling.y = distance;
  90986. this._laserPointer.position.z = -distance / 2;
  90987. };
  90988. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90989. _super.prototype.dispose.call(this);
  90990. this._laserPointer.dispose();
  90991. if (this._meshAttachedObserver) {
  90992. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90993. }
  90994. };
  90995. return VRExperienceHelperControllerGazer;
  90996. }(VRExperienceHelperGazer));
  90997. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90998. __extends(VRExperienceHelperCameraGazer, _super);
  90999. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91000. var _this = _super.call(this, scene) || this;
  91001. _this.getCamera = getCamera;
  91002. return _this;
  91003. }
  91004. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91005. var camera = this.getCamera();
  91006. if (camera) {
  91007. return camera.getForwardRay(length);
  91008. }
  91009. else {
  91010. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91011. }
  91012. };
  91013. return VRExperienceHelperCameraGazer;
  91014. }(VRExperienceHelperGazer));
  91015. /**
  91016. * Helps to quickly add VR support to an existing scene.
  91017. * See http://doc.babylonjs.com/how_to/webvr_helper
  91018. */
  91019. var VRExperienceHelper = /** @class */ (function () {
  91020. /**
  91021. * Instantiates a VRExperienceHelper.
  91022. * Helps to quickly add VR support to an existing scene.
  91023. * @param scene The scene the VRExperienceHelper belongs to.
  91024. * @param webVROptions Options to modify the vr experience helper's behavior.
  91025. */
  91026. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91027. if (webVROptions === void 0) { webVROptions = {}; }
  91028. var _this = this;
  91029. this.webVROptions = webVROptions;
  91030. // Can the system support WebVR, even if a headset isn't plugged in?
  91031. this._webVRsupported = false;
  91032. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91033. this._webVRready = false;
  91034. // Are we waiting for the requestPresent callback to complete?
  91035. this._webVRrequesting = false;
  91036. // Are we presenting to the headset right now?
  91037. this._webVRpresenting = false;
  91038. // Are we presenting in the fullscreen fallback?
  91039. this._fullscreenVRpresenting = false;
  91040. /**
  91041. * Observable raised when entering VR.
  91042. */
  91043. this.onEnteringVRObservable = new BABYLON.Observable();
  91044. /**
  91045. * Observable raised when exiting VR.
  91046. */
  91047. this.onExitingVRObservable = new BABYLON.Observable();
  91048. /**
  91049. * Observable raised when controller mesh is loaded.
  91050. */
  91051. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91052. this._useCustomVRButton = false;
  91053. this._teleportationRequested = false;
  91054. this._teleportActive = false;
  91055. this._floorMeshesCollection = [];
  91056. this._rotationAllowed = true;
  91057. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91058. this._isDefaultTeleportationTarget = true;
  91059. this._teleportationFillColor = "#444444";
  91060. this._teleportationBorderColor = "#FFFFFF";
  91061. this._rotationAngle = 0;
  91062. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91063. this._padSensibilityUp = 0.65;
  91064. this._padSensibilityDown = 0.35;
  91065. this.leftController = null;
  91066. this.rightController = null;
  91067. /**
  91068. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91069. */
  91070. this.onNewMeshSelected = new BABYLON.Observable();
  91071. /**
  91072. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91073. */
  91074. this.onNewMeshPicked = new BABYLON.Observable();
  91075. /**
  91076. * Observable raised before camera teleportation
  91077. */
  91078. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91079. /**
  91080. * Observable raised after camera teleportation
  91081. */
  91082. this.onAfterCameraTeleport = new BABYLON.Observable();
  91083. /**
  91084. * Observable raised when current selected mesh gets unselected
  91085. */
  91086. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91087. /**
  91088. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91089. */
  91090. this.teleportationEnabled = true;
  91091. this._teleportationInitialized = false;
  91092. this._interactionsEnabled = false;
  91093. this._interactionsRequested = false;
  91094. this._displayGaze = true;
  91095. this._displayLaserPointer = true;
  91096. this._onResize = function () {
  91097. _this.moveButtonToBottomRight();
  91098. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91099. _this.exitVR();
  91100. }
  91101. };
  91102. this._onFullscreenChange = function () {
  91103. if (document.fullscreen !== undefined) {
  91104. _this._fullscreenVRpresenting = document.fullscreen;
  91105. }
  91106. else if (document.mozFullScreen !== undefined) {
  91107. _this._fullscreenVRpresenting = document.mozFullScreen;
  91108. }
  91109. else if (document.webkitIsFullScreen !== undefined) {
  91110. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91111. }
  91112. else if (document.msIsFullScreen !== undefined) {
  91113. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91114. }
  91115. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91116. _this.exitVR();
  91117. if (!_this._useCustomVRButton) {
  91118. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91119. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91120. }
  91121. }
  91122. };
  91123. this.beforeRender = function () {
  91124. if (_this.leftController && _this.leftController._activePointer) {
  91125. _this._castRayAndSelectObject(_this.leftController);
  91126. }
  91127. if (_this.rightController && _this.rightController._activePointer) {
  91128. _this._castRayAndSelectObject(_this.rightController);
  91129. }
  91130. if (_this._noControllerIsActive) {
  91131. _this._castRayAndSelectObject(_this._cameraGazer);
  91132. }
  91133. else {
  91134. _this._cameraGazer._gazeTracker.isVisible = false;
  91135. }
  91136. };
  91137. this._onNewGamepadConnected = function (gamepad) {
  91138. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91139. if (gamepad.leftStick) {
  91140. gamepad.onleftstickchanged(function (stickValues) {
  91141. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91142. // Listening to classic/xbox gamepad only if no VR controller is active
  91143. if ((!_this.leftController && !_this.rightController) ||
  91144. ((_this.leftController && !_this.leftController._activePointer) &&
  91145. (_this.rightController && !_this.rightController._activePointer))) {
  91146. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91147. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91148. }
  91149. }
  91150. });
  91151. }
  91152. if (gamepad.rightStick) {
  91153. gamepad.onrightstickchanged(function (stickValues) {
  91154. if (_this._teleportationInitialized) {
  91155. _this._checkRotate(stickValues, _this._cameraGazer);
  91156. }
  91157. });
  91158. }
  91159. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91160. gamepad.onbuttondown(function (buttonPressed) {
  91161. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91162. _this._cameraGazer._selectionPointerDown();
  91163. }
  91164. });
  91165. gamepad.onbuttonup(function (buttonPressed) {
  91166. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91167. _this._cameraGazer._selectionPointerUp();
  91168. }
  91169. });
  91170. }
  91171. }
  91172. else {
  91173. var webVRController = gamepad;
  91174. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91175. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91176. _this.rightController = controller;
  91177. }
  91178. else {
  91179. _this.leftController = controller;
  91180. }
  91181. _this._tryEnableInteractionOnController(controller);
  91182. }
  91183. };
  91184. // 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
  91185. this._tryEnableInteractionOnController = function (controller) {
  91186. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91187. _this._enableInteractionOnController(controller);
  91188. }
  91189. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91190. _this._enableTeleportationOnController(controller);
  91191. }
  91192. };
  91193. this._onNewGamepadDisconnected = function (gamepad) {
  91194. if (gamepad instanceof BABYLON.WebVRController) {
  91195. if (gamepad.hand === "left" && _this.leftController != null) {
  91196. _this.leftController.dispose();
  91197. _this.leftController = null;
  91198. }
  91199. if (gamepad.hand === "right" && _this.rightController != null) {
  91200. _this.rightController.dispose();
  91201. _this.rightController = null;
  91202. }
  91203. }
  91204. };
  91205. this._workingVector = BABYLON.Vector3.Zero();
  91206. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91207. this._workingMatrix = BABYLON.Matrix.Identity();
  91208. this._scene = scene;
  91209. this._canvas = scene.getEngine().getRenderingCanvas();
  91210. // Parse options
  91211. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91212. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91213. }
  91214. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91215. webVROptions.createDeviceOrientationCamera = true;
  91216. }
  91217. if (webVROptions.laserToggle === undefined) {
  91218. webVROptions.laserToggle = true;
  91219. }
  91220. if (webVROptions.defaultHeight === undefined) {
  91221. webVROptions.defaultHeight = 1.7;
  91222. }
  91223. if (webVROptions.useCustomVRButton) {
  91224. this._useCustomVRButton = true;
  91225. if (webVROptions.customVRButton) {
  91226. this._btnVR = webVROptions.customVRButton;
  91227. }
  91228. }
  91229. if (webVROptions.rayLength) {
  91230. this._rayLength = webVROptions.rayLength;
  91231. }
  91232. this._defaultHeight = webVROptions.defaultHeight;
  91233. if (webVROptions.positionScale) {
  91234. this._rayLength *= webVROptions.positionScale;
  91235. this._defaultHeight *= webVROptions.positionScale;
  91236. }
  91237. // Set position
  91238. if (this._scene.activeCamera) {
  91239. this._position = this._scene.activeCamera.position.clone();
  91240. }
  91241. else {
  91242. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91243. }
  91244. // Set non-vr camera
  91245. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91246. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91247. // Copy data from existing camera
  91248. if (this._scene.activeCamera) {
  91249. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91250. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91251. // Set rotation from previous camera
  91252. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91253. var targetCamera = this._scene.activeCamera;
  91254. if (targetCamera.rotationQuaternion) {
  91255. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91256. }
  91257. else {
  91258. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91259. }
  91260. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91261. }
  91262. }
  91263. this._scene.activeCamera = this._deviceOrientationCamera;
  91264. if (this._canvas) {
  91265. this._scene.activeCamera.attachControl(this._canvas);
  91266. }
  91267. }
  91268. else {
  91269. this._existingCamera = this._scene.activeCamera;
  91270. }
  91271. // Create VR cameras
  91272. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91273. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91274. }
  91275. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91276. this._webVRCamera.useStandingMatrix();
  91277. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91278. // Create default button
  91279. if (!this._useCustomVRButton) {
  91280. this._btnVR = document.createElement("BUTTON");
  91281. this._btnVR.className = "babylonVRicon";
  91282. this._btnVR.id = "babylonVRiconbtn";
  91283. this._btnVR.title = "Click to switch to VR";
  91284. 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) }";
  91285. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91286. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91287. // css += ".babylonVRicon.vrdisplaysupported { }";
  91288. // css += ".babylonVRicon.vrdisplayready { }";
  91289. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91290. var style = document.createElement('style');
  91291. style.appendChild(document.createTextNode(css));
  91292. document.getElementsByTagName('head')[0].appendChild(style);
  91293. this.moveButtonToBottomRight();
  91294. }
  91295. // VR button click event
  91296. if (this._btnVR) {
  91297. this._btnVR.addEventListener("click", function () {
  91298. if (!_this.isInVRMode) {
  91299. _this.enterVR();
  91300. }
  91301. else {
  91302. _this.exitVR();
  91303. }
  91304. });
  91305. }
  91306. // Window events
  91307. window.addEventListener("resize", this._onResize);
  91308. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91309. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91310. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91311. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91312. // Display vr button when headset is connected
  91313. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91314. this.displayVRButton();
  91315. }
  91316. else {
  91317. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91318. if (e.vrDisplay) {
  91319. _this.displayVRButton();
  91320. }
  91321. });
  91322. }
  91323. // Exiting VR mode using 'ESC' key on desktop
  91324. this._onKeyDown = function (event) {
  91325. if (event.keyCode === 27 && _this.isInVRMode) {
  91326. _this.exitVR();
  91327. }
  91328. };
  91329. document.addEventListener("keydown", this._onKeyDown);
  91330. // Exiting VR mode double tapping the touch screen
  91331. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91332. if (_this.isInVRMode) {
  91333. _this.exitVR();
  91334. if (_this._fullscreenVRpresenting) {
  91335. _this._scene.getEngine().switchFullscreen(true);
  91336. }
  91337. }
  91338. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91339. // Listen for WebVR display changes
  91340. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91341. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91342. this._onVRRequestPresentStart = function () {
  91343. _this._webVRrequesting = true;
  91344. _this.updateButtonVisibility();
  91345. };
  91346. this._onVRRequestPresentComplete = function (success) {
  91347. _this._webVRrequesting = false;
  91348. _this.updateButtonVisibility();
  91349. };
  91350. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91351. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91352. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91353. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91354. scene.onDisposeObservable.add(function () {
  91355. _this.dispose();
  91356. });
  91357. // Gamepad connection events
  91358. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91359. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91360. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91361. this.updateButtonVisibility();
  91362. //create easing functions
  91363. this._circleEase = new BABYLON.CircleEase();
  91364. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91365. if (this.webVROptions.floorMeshes) {
  91366. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91367. }
  91368. }
  91369. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91370. /** Return this.onEnteringVRObservable
  91371. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91372. */
  91373. get: function () {
  91374. return this.onEnteringVRObservable;
  91375. },
  91376. enumerable: true,
  91377. configurable: true
  91378. });
  91379. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91380. /** Return this.onExitingVRObservable
  91381. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91382. */
  91383. get: function () {
  91384. return this.onExitingVRObservable;
  91385. },
  91386. enumerable: true,
  91387. configurable: true
  91388. });
  91389. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91390. /** Return this.onControllerMeshLoadedObservable
  91391. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91392. */
  91393. get: function () {
  91394. return this.onControllerMeshLoadedObservable;
  91395. },
  91396. enumerable: true,
  91397. configurable: true
  91398. });
  91399. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91400. /**
  91401. * The mesh used to display where the user is going to teleport.
  91402. */
  91403. get: function () {
  91404. return this._teleportationTarget;
  91405. },
  91406. /**
  91407. * Sets the mesh to be used to display where the user is going to teleport.
  91408. */
  91409. set: function (value) {
  91410. if (value) {
  91411. value.name = "teleportationTarget";
  91412. this._isDefaultTeleportationTarget = false;
  91413. this._teleportationTarget = value;
  91414. }
  91415. },
  91416. enumerable: true,
  91417. configurable: true
  91418. });
  91419. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91420. /**
  91421. * The mesh used to display where the user is selecting,
  91422. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91423. * See http://doc.babylonjs.com/resources/baking_transformations
  91424. */
  91425. get: function () {
  91426. return this._cameraGazer._gazeTracker;
  91427. },
  91428. set: function (value) {
  91429. if (value) {
  91430. this._cameraGazer._gazeTracker = value;
  91431. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91432. this._cameraGazer._gazeTracker.isPickable = false;
  91433. this._cameraGazer._gazeTracker.isVisible = false;
  91434. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91435. if (this.leftController) {
  91436. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91437. }
  91438. if (this.rightController) {
  91439. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91440. }
  91441. }
  91442. },
  91443. enumerable: true,
  91444. configurable: true
  91445. });
  91446. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91447. /**
  91448. * If the ray of the gaze should be displayed.
  91449. */
  91450. get: function () {
  91451. return this._displayGaze;
  91452. },
  91453. /**
  91454. * Sets if the ray of the gaze should be displayed.
  91455. */
  91456. set: function (value) {
  91457. this._displayGaze = value;
  91458. if (!value) {
  91459. this._cameraGazer._gazeTracker.isVisible = false;
  91460. if (this.leftController) {
  91461. this.leftController._gazeTracker.isVisible = false;
  91462. }
  91463. if (this.rightController) {
  91464. this.rightController._gazeTracker.isVisible = false;
  91465. }
  91466. }
  91467. },
  91468. enumerable: true,
  91469. configurable: true
  91470. });
  91471. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91472. /**
  91473. * If the ray of the LaserPointer should be displayed.
  91474. */
  91475. get: function () {
  91476. return this._displayLaserPointer;
  91477. },
  91478. /**
  91479. * Sets if the ray of the LaserPointer should be displayed.
  91480. */
  91481. set: function (value) {
  91482. this._displayLaserPointer = value;
  91483. if (!value) {
  91484. if (this.rightController) {
  91485. this.rightController._deactivatePointer();
  91486. this.rightController._gazeTracker.isVisible = false;
  91487. }
  91488. if (this.leftController) {
  91489. this.leftController._deactivatePointer();
  91490. this.leftController._gazeTracker.isVisible = false;
  91491. }
  91492. }
  91493. else {
  91494. if (this.rightController) {
  91495. this.rightController._activatePointer();
  91496. }
  91497. if (this.leftController) {
  91498. this.leftController._activatePointer();
  91499. }
  91500. }
  91501. },
  91502. enumerable: true,
  91503. configurable: true
  91504. });
  91505. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91506. /**
  91507. * The deviceOrientationCamera used as the camera when not in VR.
  91508. */
  91509. get: function () {
  91510. return this._deviceOrientationCamera;
  91511. },
  91512. enumerable: true,
  91513. configurable: true
  91514. });
  91515. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91516. /**
  91517. * Based on the current WebVR support, returns the current VR camera used.
  91518. */
  91519. get: function () {
  91520. if (this._webVRready) {
  91521. return this._webVRCamera;
  91522. }
  91523. else {
  91524. return this._scene.activeCamera;
  91525. }
  91526. },
  91527. enumerable: true,
  91528. configurable: true
  91529. });
  91530. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91531. /**
  91532. * The webVRCamera which is used when in VR.
  91533. */
  91534. get: function () {
  91535. return this._webVRCamera;
  91536. },
  91537. enumerable: true,
  91538. configurable: true
  91539. });
  91540. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91541. /**
  91542. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91543. */
  91544. get: function () {
  91545. return this._vrDeviceOrientationCamera;
  91546. },
  91547. enumerable: true,
  91548. configurable: true
  91549. });
  91550. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91551. get: function () {
  91552. var result = this._cameraGazer._teleportationRequestInitiated
  91553. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91554. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91555. return result;
  91556. },
  91557. enumerable: true,
  91558. configurable: true
  91559. });
  91560. // Raised when one of the controller has loaded successfully its associated default mesh
  91561. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91562. if (this.leftController && this.leftController.webVRController == webVRController) {
  91563. if (webVRController.mesh) {
  91564. this.leftController._setLaserPointerParent(webVRController.mesh);
  91565. }
  91566. }
  91567. if (this.rightController && this.rightController.webVRController == webVRController) {
  91568. if (webVRController.mesh) {
  91569. this.rightController._setLaserPointerParent(webVRController.mesh);
  91570. }
  91571. }
  91572. try {
  91573. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91574. }
  91575. catch (err) {
  91576. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91577. }
  91578. };
  91579. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91580. /**
  91581. * Gets a value indicating if we are currently in VR mode.
  91582. */
  91583. get: function () {
  91584. return this._webVRpresenting || this._fullscreenVRpresenting;
  91585. },
  91586. enumerable: true,
  91587. configurable: true
  91588. });
  91589. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  91590. var vrDisplay = this._scene.getEngine().getVRDevice();
  91591. if (vrDisplay) {
  91592. var wasPresenting = this._webVRpresenting;
  91593. // A VR display is connected
  91594. this._webVRpresenting = vrDisplay.isPresenting;
  91595. if (wasPresenting && !this._webVRpresenting)
  91596. this.exitVR();
  91597. }
  91598. else {
  91599. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  91600. }
  91601. this.updateButtonVisibility();
  91602. };
  91603. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  91604. this._webVRsupported = eventArgs.vrSupported;
  91605. this._webVRready = !!eventArgs.vrDisplay;
  91606. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  91607. this.updateButtonVisibility();
  91608. };
  91609. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  91610. if (this._canvas && !this._useCustomVRButton) {
  91611. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  91612. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  91613. }
  91614. };
  91615. VRExperienceHelper.prototype.displayVRButton = function () {
  91616. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  91617. document.body.appendChild(this._btnVR);
  91618. this._btnVRDisplayed = true;
  91619. }
  91620. };
  91621. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  91622. if (!this._btnVR || this._useCustomVRButton) {
  91623. return;
  91624. }
  91625. this._btnVR.className = "babylonVRicon";
  91626. if (this.isInVRMode) {
  91627. this._btnVR.className += " vrdisplaypresenting";
  91628. }
  91629. else {
  91630. if (this._webVRready)
  91631. this._btnVR.className += " vrdisplayready";
  91632. if (this._webVRsupported)
  91633. this._btnVR.className += " vrdisplaysupported";
  91634. if (this._webVRrequesting)
  91635. this._btnVR.className += " vrdisplayrequesting";
  91636. }
  91637. };
  91638. /**
  91639. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  91640. * Otherwise, will use the fullscreen API.
  91641. */
  91642. VRExperienceHelper.prototype.enterVR = function () {
  91643. if (this.onEnteringVRObservable) {
  91644. try {
  91645. this.onEnteringVRObservable.notifyObservers(this);
  91646. }
  91647. catch (err) {
  91648. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  91649. }
  91650. }
  91651. if (this._scene.activeCamera) {
  91652. this._position = this._scene.activeCamera.position.clone();
  91653. // make sure that we return to the last active camera
  91654. this._existingCamera = this._scene.activeCamera;
  91655. }
  91656. if (this._webVRrequesting)
  91657. return;
  91658. // If WebVR is supported and a headset is connected
  91659. if (this._webVRready) {
  91660. if (!this._webVRpresenting) {
  91661. this._webVRCamera.position = this._position;
  91662. this._scene.activeCamera = this._webVRCamera;
  91663. }
  91664. }
  91665. else if (this._vrDeviceOrientationCamera) {
  91666. this._vrDeviceOrientationCamera.position = this._position;
  91667. if (this._scene.activeCamera) {
  91668. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91669. }
  91670. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  91671. this._scene.getEngine().switchFullscreen(true);
  91672. this.updateButtonVisibility();
  91673. }
  91674. if (this._scene.activeCamera && this._canvas) {
  91675. this._scene.activeCamera.attachControl(this._canvas);
  91676. }
  91677. if (this._interactionsEnabled) {
  91678. this._scene.registerBeforeRender(this.beforeRender);
  91679. }
  91680. };
  91681. /**
  91682. * Attempt to exit VR, or fullscreen.
  91683. */
  91684. VRExperienceHelper.prototype.exitVR = function () {
  91685. if (this.onExitingVRObservable) {
  91686. try {
  91687. this.onExitingVRObservable.notifyObservers(this);
  91688. }
  91689. catch (err) {
  91690. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  91691. }
  91692. }
  91693. if (this._webVRpresenting) {
  91694. this._scene.getEngine().disableVR();
  91695. }
  91696. if (this._scene.activeCamera) {
  91697. this._position = this._scene.activeCamera.position.clone();
  91698. }
  91699. if (this._deviceOrientationCamera) {
  91700. this._deviceOrientationCamera.position = this._position;
  91701. this._scene.activeCamera = this._deviceOrientationCamera;
  91702. if (this._canvas) {
  91703. this._scene.activeCamera.attachControl(this._canvas);
  91704. }
  91705. }
  91706. else if (this._existingCamera) {
  91707. this._existingCamera.position = this._position;
  91708. this._scene.activeCamera = this._existingCamera;
  91709. }
  91710. this.updateButtonVisibility();
  91711. if (this._interactionsEnabled) {
  91712. this._scene.unregisterBeforeRender(this.beforeRender);
  91713. }
  91714. // resize to update width and height when exiting vr exits fullscreen
  91715. this._scene.getEngine().resize();
  91716. };
  91717. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  91718. /**
  91719. * The position of the vr experience helper.
  91720. */
  91721. get: function () {
  91722. return this._position;
  91723. },
  91724. /**
  91725. * Sets the position of the vr experience helper.
  91726. */
  91727. set: function (value) {
  91728. this._position = value;
  91729. if (this._scene.activeCamera) {
  91730. this._scene.activeCamera.position = value;
  91731. }
  91732. },
  91733. enumerable: true,
  91734. configurable: true
  91735. });
  91736. /**
  91737. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  91738. */
  91739. VRExperienceHelper.prototype.enableInteractions = function () {
  91740. var _this = this;
  91741. if (!this._interactionsEnabled) {
  91742. this._interactionsRequested = true;
  91743. if (this.leftController) {
  91744. this._enableInteractionOnController(this.leftController);
  91745. }
  91746. if (this.rightController) {
  91747. this._enableInteractionOnController(this.rightController);
  91748. }
  91749. this.raySelectionPredicate = function (mesh) {
  91750. return mesh.isVisible;
  91751. };
  91752. this.meshSelectionPredicate = function (mesh) {
  91753. return true;
  91754. };
  91755. this._raySelectionPredicate = function (mesh) {
  91756. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  91757. && mesh.name.indexOf("teleportationTarget") === -1
  91758. && mesh.name.indexOf("torusTeleportation") === -1
  91759. && mesh.name.indexOf("laserPointer") === -1)) {
  91760. return _this.raySelectionPredicate(mesh);
  91761. }
  91762. return false;
  91763. };
  91764. this._interactionsEnabled = true;
  91765. }
  91766. };
  91767. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  91768. get: function () {
  91769. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  91770. },
  91771. enumerable: true,
  91772. configurable: true
  91773. });
  91774. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  91775. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  91776. if (this._floorMeshesCollection[i].id === mesh.id) {
  91777. return true;
  91778. }
  91779. }
  91780. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  91781. return true;
  91782. }
  91783. return false;
  91784. };
  91785. /**
  91786. * Adds a floor mesh to be used for teleportation.
  91787. * @param floorMesh the mesh to be used for teleportation.
  91788. */
  91789. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  91790. if (!this._floorMeshesCollection) {
  91791. return;
  91792. }
  91793. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  91794. return;
  91795. }
  91796. this._floorMeshesCollection.push(floorMesh);
  91797. };
  91798. /**
  91799. * Removes a floor mesh from being used for teleportation.
  91800. * @param floorMesh the mesh to be removed.
  91801. */
  91802. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  91803. if (!this._floorMeshesCollection) {
  91804. return;
  91805. }
  91806. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  91807. if (meshIndex !== -1) {
  91808. this._floorMeshesCollection.splice(meshIndex, 1);
  91809. }
  91810. };
  91811. /**
  91812. * Enables interactions and teleportation using the VR controllers and gaze.
  91813. * @param vrTeleportationOptions options to modify teleportation behavior.
  91814. */
  91815. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  91816. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  91817. if (!this._teleportationInitialized) {
  91818. this._teleportationRequested = true;
  91819. this.enableInteractions();
  91820. if (vrTeleportationOptions.floorMeshName) {
  91821. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  91822. }
  91823. if (vrTeleportationOptions.floorMeshes) {
  91824. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  91825. }
  91826. if (this.leftController != null) {
  91827. this._enableTeleportationOnController(this.leftController);
  91828. }
  91829. if (this.rightController != null) {
  91830. this._enableTeleportationOnController(this.rightController);
  91831. }
  91832. // Creates an image processing post process for the vignette not relying
  91833. // on the main scene configuration for image processing to reduce setup and spaces
  91834. // (gamma/linear) conflicts.
  91835. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  91836. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  91837. imageProcessingConfiguration.vignetteEnabled = true;
  91838. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  91839. this._webVRCamera.detachPostProcess(this._postProcessMove);
  91840. this._teleportationInitialized = true;
  91841. if (this._isDefaultTeleportationTarget) {
  91842. this._createTeleportationCircles();
  91843. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  91844. }
  91845. }
  91846. };
  91847. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  91848. var _this = this;
  91849. var controllerMesh = controller.webVRController.mesh;
  91850. if (controllerMesh) {
  91851. controller._interactionsEnabled = true;
  91852. controller._activatePointer();
  91853. if (this.webVROptions.laserToggle) {
  91854. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  91855. // Enabling / disabling laserPointer
  91856. if (_this._displayLaserPointer && stateObject.value === 1) {
  91857. if (controller._activePointer) {
  91858. controller._deactivatePointer();
  91859. }
  91860. else {
  91861. controller._activatePointer();
  91862. }
  91863. if (_this.displayGaze) {
  91864. controller._gazeTracker.isVisible = controller._activePointer;
  91865. }
  91866. }
  91867. });
  91868. }
  91869. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  91870. var gazer = controller;
  91871. if (_this._noControllerIsActive) {
  91872. gazer = _this._cameraGazer;
  91873. }
  91874. if (!gazer._pointerDownOnMeshAsked) {
  91875. if (stateObject.value > _this._padSensibilityUp) {
  91876. gazer._selectionPointerDown();
  91877. }
  91878. }
  91879. else if (stateObject.value < _this._padSensibilityDown) {
  91880. gazer._selectionPointerUp();
  91881. }
  91882. });
  91883. }
  91884. };
  91885. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  91886. // Dont teleport if another gaze already requested teleportation
  91887. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  91888. return;
  91889. }
  91890. if (!gazer._teleportationRequestInitiated) {
  91891. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  91892. gazer._activatePointer();
  91893. gazer._teleportationRequestInitiated = true;
  91894. }
  91895. }
  91896. else {
  91897. // Listening to the proper controller values changes to confirm teleportation
  91898. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  91899. if (this._teleportActive) {
  91900. this._teleportCamera(this._haloCenter);
  91901. }
  91902. gazer._teleportationRequestInitiated = false;
  91903. }
  91904. }
  91905. };
  91906. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91907. // Only rotate when user is not currently selecting a teleportation location
  91908. if (gazer._teleportationRequestInitiated) {
  91909. return;
  91910. }
  91911. if (!gazer._rotationLeftAsked) {
  91912. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91913. gazer._rotationLeftAsked = true;
  91914. if (this._rotationAllowed) {
  91915. this._rotateCamera(false);
  91916. }
  91917. }
  91918. }
  91919. else {
  91920. if (stateObject.x > -this._padSensibilityDown) {
  91921. gazer._rotationLeftAsked = false;
  91922. }
  91923. }
  91924. if (!gazer._rotationRightAsked) {
  91925. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91926. gazer._rotationRightAsked = true;
  91927. if (this._rotationAllowed) {
  91928. this._rotateCamera(true);
  91929. }
  91930. }
  91931. }
  91932. else {
  91933. if (stateObject.x < this._padSensibilityDown) {
  91934. gazer._rotationRightAsked = false;
  91935. }
  91936. }
  91937. };
  91938. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91939. // Only teleport backwards when user is not currently selecting a teleportation location
  91940. if (gazer._teleportationRequestInitiated) {
  91941. return;
  91942. }
  91943. // Teleport backwards
  91944. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91945. if (!gazer._teleportationBackRequestInitiated) {
  91946. if (!this.currentVRCamera) {
  91947. return;
  91948. }
  91949. // Get rotation and position of the current camera
  91950. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91951. var position = this.currentVRCamera.position;
  91952. // If the camera has device position, use that instead
  91953. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91954. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91955. position = this.currentVRCamera.devicePosition;
  91956. }
  91957. // Get matrix with only the y rotation of the device rotation
  91958. rotation.toEulerAnglesToRef(this._workingVector);
  91959. this._workingVector.z = 0;
  91960. this._workingVector.x = 0;
  91961. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91962. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91963. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91964. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91965. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91966. var ray = new BABYLON.Ray(position, this._workingVector);
  91967. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91968. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91969. this._teleportCamera(hit.pickedPoint);
  91970. }
  91971. gazer._teleportationBackRequestInitiated = true;
  91972. }
  91973. }
  91974. else {
  91975. gazer._teleportationBackRequestInitiated = false;
  91976. }
  91977. };
  91978. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91979. var _this = this;
  91980. var controllerMesh = controller.webVRController.mesh;
  91981. if (controllerMesh) {
  91982. if (!controller._interactionsEnabled) {
  91983. this._enableInteractionOnController(controller);
  91984. }
  91985. controller._interactionsEnabled = true;
  91986. controller._teleportationEnabled = true;
  91987. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91988. controller._dpadPressed = false;
  91989. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91990. controller._dpadPressed = stateObject.pressed;
  91991. if (!controller._dpadPressed) {
  91992. controller._rotationLeftAsked = false;
  91993. controller._rotationRightAsked = false;
  91994. controller._teleportationBackRequestInitiated = false;
  91995. }
  91996. });
  91997. }
  91998. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91999. if (_this.teleportationEnabled) {
  92000. _this._checkTeleportBackwards(stateObject, controller);
  92001. _this._checkTeleportWithRay(stateObject, controller);
  92002. }
  92003. _this._checkRotate(stateObject, controller);
  92004. });
  92005. }
  92006. };
  92007. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92008. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92009. this._teleportationTarget.isPickable = false;
  92010. var length = 512;
  92011. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92012. dynamicTexture.hasAlpha = true;
  92013. var context = dynamicTexture.getContext();
  92014. var centerX = length / 2;
  92015. var centerY = length / 2;
  92016. var radius = 200;
  92017. context.beginPath();
  92018. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92019. context.fillStyle = this._teleportationFillColor;
  92020. context.fill();
  92021. context.lineWidth = 10;
  92022. context.strokeStyle = this._teleportationBorderColor;
  92023. context.stroke();
  92024. context.closePath();
  92025. dynamicTexture.update();
  92026. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92027. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92028. this._teleportationTarget.material = teleportationCircleMaterial;
  92029. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92030. torus.isPickable = false;
  92031. torus.parent = this._teleportationTarget;
  92032. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92033. var keys = [];
  92034. keys.push({
  92035. frame: 0,
  92036. value: 0
  92037. });
  92038. keys.push({
  92039. frame: 30,
  92040. value: 0.4
  92041. });
  92042. keys.push({
  92043. frame: 60,
  92044. value: 0
  92045. });
  92046. animationInnerCircle.setKeys(keys);
  92047. var easingFunction = new BABYLON.SineEase();
  92048. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92049. animationInnerCircle.setEasingFunction(easingFunction);
  92050. torus.animations = [];
  92051. torus.animations.push(animationInnerCircle);
  92052. this._scene.beginAnimation(torus, 0, 60, true);
  92053. this._hideTeleportationTarget();
  92054. };
  92055. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92056. this._teleportActive = true;
  92057. if (this._teleportationInitialized) {
  92058. this._teleportationTarget.isVisible = true;
  92059. if (this._isDefaultTeleportationTarget) {
  92060. this._teleportationTarget.getChildren()[0].isVisible = true;
  92061. }
  92062. }
  92063. };
  92064. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92065. this._teleportActive = false;
  92066. if (this._teleportationInitialized) {
  92067. this._teleportationTarget.isVisible = false;
  92068. if (this._isDefaultTeleportationTarget) {
  92069. this._teleportationTarget.getChildren()[0].isVisible = false;
  92070. }
  92071. }
  92072. };
  92073. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92074. var _this = this;
  92075. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92076. return;
  92077. }
  92078. if (right) {
  92079. this._rotationAngle++;
  92080. }
  92081. else {
  92082. this._rotationAngle--;
  92083. }
  92084. this.currentVRCamera.animations = [];
  92085. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92086. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92087. var animationRotationKeys = [];
  92088. animationRotationKeys.push({
  92089. frame: 0,
  92090. value: this.currentVRCamera.rotationQuaternion
  92091. });
  92092. animationRotationKeys.push({
  92093. frame: 6,
  92094. value: target
  92095. });
  92096. animationRotation.setKeys(animationRotationKeys);
  92097. animationRotation.setEasingFunction(this._circleEase);
  92098. this.currentVRCamera.animations.push(animationRotation);
  92099. this._postProcessMove.animations = [];
  92100. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92101. var vignetteWeightKeys = [];
  92102. vignetteWeightKeys.push({
  92103. frame: 0,
  92104. value: 0
  92105. });
  92106. vignetteWeightKeys.push({
  92107. frame: 3,
  92108. value: 4
  92109. });
  92110. vignetteWeightKeys.push({
  92111. frame: 6,
  92112. value: 0
  92113. });
  92114. animationPP.setKeys(vignetteWeightKeys);
  92115. animationPP.setEasingFunction(this._circleEase);
  92116. this._postProcessMove.animations.push(animationPP);
  92117. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92118. var vignetteStretchKeys = [];
  92119. vignetteStretchKeys.push({
  92120. frame: 0,
  92121. value: 0
  92122. });
  92123. vignetteStretchKeys.push({
  92124. frame: 3,
  92125. value: 10
  92126. });
  92127. vignetteStretchKeys.push({
  92128. frame: 6,
  92129. value: 0
  92130. });
  92131. animationPP2.setKeys(vignetteStretchKeys);
  92132. animationPP2.setEasingFunction(this._circleEase);
  92133. this._postProcessMove.animations.push(animationPP2);
  92134. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92135. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92136. this._postProcessMove.samples = 4;
  92137. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92138. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92139. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92140. });
  92141. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92142. };
  92143. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92144. if (hit.pickedPoint) {
  92145. if (gazer._teleportationRequestInitiated) {
  92146. this._displayTeleportationTarget();
  92147. this._haloCenter.copyFrom(hit.pickedPoint);
  92148. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92149. }
  92150. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92151. if (pickNormal) {
  92152. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92153. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92154. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92155. }
  92156. this._teleportationTarget.position.y += 0.1;
  92157. }
  92158. };
  92159. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92160. var _this = this;
  92161. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92162. return;
  92163. }
  92164. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92165. // offset of the headset from the anchor.
  92166. if (this.webVRCamera.leftCamera) {
  92167. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92168. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92169. location.subtractToRef(this._workingVector, this._workingVector);
  92170. }
  92171. else {
  92172. this._workingVector.copyFrom(location);
  92173. }
  92174. // Add height to account for user's height offset
  92175. if (this.isInVRMode) {
  92176. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92177. }
  92178. else {
  92179. this._workingVector.y += this._defaultHeight;
  92180. }
  92181. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92182. // Create animation from the camera's position to the new location
  92183. this.currentVRCamera.animations = [];
  92184. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92185. var animationCameraTeleportationKeys = [{
  92186. frame: 0,
  92187. value: this.currentVRCamera.position
  92188. },
  92189. {
  92190. frame: 11,
  92191. value: this._workingVector
  92192. }
  92193. ];
  92194. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92195. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92196. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92197. this._postProcessMove.animations = [];
  92198. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92199. var vignetteWeightKeys = [];
  92200. vignetteWeightKeys.push({
  92201. frame: 0,
  92202. value: 0
  92203. });
  92204. vignetteWeightKeys.push({
  92205. frame: 5,
  92206. value: 8
  92207. });
  92208. vignetteWeightKeys.push({
  92209. frame: 11,
  92210. value: 0
  92211. });
  92212. animationPP.setKeys(vignetteWeightKeys);
  92213. this._postProcessMove.animations.push(animationPP);
  92214. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92215. var vignetteStretchKeys = [];
  92216. vignetteStretchKeys.push({
  92217. frame: 0,
  92218. value: 0
  92219. });
  92220. vignetteStretchKeys.push({
  92221. frame: 5,
  92222. value: 10
  92223. });
  92224. vignetteStretchKeys.push({
  92225. frame: 11,
  92226. value: 0
  92227. });
  92228. animationPP2.setKeys(vignetteStretchKeys);
  92229. this._postProcessMove.animations.push(animationPP2);
  92230. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92231. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92232. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92233. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92234. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92235. });
  92236. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92237. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92238. });
  92239. this._hideTeleportationTarget();
  92240. };
  92241. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92242. if (normal) {
  92243. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92244. if (angle < Math.PI / 2) {
  92245. normal.scaleInPlace(-1);
  92246. }
  92247. }
  92248. return normal;
  92249. };
  92250. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92251. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92252. return;
  92253. }
  92254. var ray = gazer._getForwardRay(this._rayLength);
  92255. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92256. if (hit) {
  92257. // Populate the contrllers mesh that can be used for drag/drop
  92258. if (gazer._laserPointer) {
  92259. hit.originMesh = gazer._laserPointer.parent;
  92260. }
  92261. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92262. }
  92263. gazer._currentHit = hit;
  92264. // Moving the gazeTracker on the mesh face targetted
  92265. if (hit && hit.pickedPoint) {
  92266. if (this._displayGaze) {
  92267. var multiplier = 1;
  92268. gazer._gazeTracker.isVisible = true;
  92269. if (gazer._isActionableMesh) {
  92270. multiplier = 3;
  92271. }
  92272. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92273. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92274. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92275. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92276. // To avoid z-fighting
  92277. var deltaFighting = 0.002;
  92278. if (pickNormal) {
  92279. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92280. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92281. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92282. }
  92283. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92284. if (gazer._gazeTracker.position.x < 0) {
  92285. gazer._gazeTracker.position.x += deltaFighting;
  92286. }
  92287. else {
  92288. gazer._gazeTracker.position.x -= deltaFighting;
  92289. }
  92290. if (gazer._gazeTracker.position.y < 0) {
  92291. gazer._gazeTracker.position.y += deltaFighting;
  92292. }
  92293. else {
  92294. gazer._gazeTracker.position.y -= deltaFighting;
  92295. }
  92296. if (gazer._gazeTracker.position.z < 0) {
  92297. gazer._gazeTracker.position.z += deltaFighting;
  92298. }
  92299. else {
  92300. gazer._gazeTracker.position.z -= deltaFighting;
  92301. }
  92302. }
  92303. // Changing the size of the laser pointer based on the distance from the targetted point
  92304. gazer._updatePointerDistance(hit.distance);
  92305. }
  92306. else {
  92307. gazer._updatePointerDistance();
  92308. gazer._gazeTracker.isVisible = false;
  92309. }
  92310. if (hit && hit.pickedMesh) {
  92311. // The object selected is the floor, we're in a teleportation scenario
  92312. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92313. // Moving the teleportation area to this targetted point
  92314. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92315. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92316. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92317. }
  92318. gazer._currentMeshSelected = null;
  92319. if (gazer._teleportationRequestInitiated) {
  92320. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92321. }
  92322. return;
  92323. }
  92324. // If not, we're in a selection scenario
  92325. //this._teleportationAllowed = false;
  92326. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92327. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92328. this.onNewMeshPicked.notifyObservers(hit);
  92329. gazer._currentMeshSelected = hit.pickedMesh;
  92330. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92331. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92332. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92333. gazer._isActionableMesh = true;
  92334. }
  92335. else {
  92336. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92337. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92338. gazer._isActionableMesh = false;
  92339. }
  92340. try {
  92341. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92342. }
  92343. catch (err) {
  92344. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92345. }
  92346. }
  92347. else {
  92348. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92349. gazer._currentMeshSelected = null;
  92350. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92351. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92352. }
  92353. }
  92354. }
  92355. else {
  92356. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92357. gazer._currentMeshSelected = null;
  92358. //this._teleportationAllowed = false;
  92359. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92360. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92361. }
  92362. };
  92363. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92364. if (mesh) {
  92365. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92366. }
  92367. };
  92368. /**
  92369. * Sets the color of the laser ray from the vr controllers.
  92370. * @param color new color for the ray.
  92371. */
  92372. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92373. if (this.leftController) {
  92374. this.leftController._setLaserPointerColor(color);
  92375. }
  92376. if (this.rightController) {
  92377. this.rightController._setLaserPointerColor(color);
  92378. }
  92379. };
  92380. /**
  92381. * Sets the color of the ray from the vr headsets gaze.
  92382. * @param color new color for the ray.
  92383. */
  92384. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92385. if (!this._cameraGazer._gazeTracker.material) {
  92386. return;
  92387. }
  92388. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92389. if (this.leftController) {
  92390. this.leftController._gazeTracker.material.emissiveColor = color;
  92391. }
  92392. if (this.rightController) {
  92393. this.rightController._gazeTracker.material.emissiveColor = color;
  92394. }
  92395. };
  92396. /**
  92397. * Exits VR and disposes of the vr experience helper
  92398. */
  92399. VRExperienceHelper.prototype.dispose = function () {
  92400. if (this.isInVRMode) {
  92401. this.exitVR();
  92402. }
  92403. if (this._postProcessMove) {
  92404. this._postProcessMove.dispose();
  92405. }
  92406. if (this._webVRCamera) {
  92407. this._webVRCamera.dispose();
  92408. }
  92409. if (this._vrDeviceOrientationCamera) {
  92410. this._vrDeviceOrientationCamera.dispose();
  92411. }
  92412. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92413. document.body.removeChild(this._btnVR);
  92414. }
  92415. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92416. this._deviceOrientationCamera.dispose();
  92417. }
  92418. if (this._cameraGazer) {
  92419. this._cameraGazer.dispose();
  92420. }
  92421. if (this.leftController) {
  92422. this.leftController.dispose();
  92423. }
  92424. if (this.rightController) {
  92425. this.rightController.dispose();
  92426. }
  92427. if (this._teleportationTarget) {
  92428. this._teleportationTarget.dispose();
  92429. }
  92430. this._floorMeshesCollection = [];
  92431. document.removeEventListener("keydown", this._onKeyDown);
  92432. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92433. window.removeEventListener("resize", this._onResize);
  92434. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92435. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92436. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92437. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92438. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92439. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92440. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92441. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92442. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92443. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92444. this._scene.unregisterBeforeRender(this.beforeRender);
  92445. };
  92446. /**
  92447. * Gets the name of the VRExperienceHelper class
  92448. * @returns "VRExperienceHelper"
  92449. */
  92450. VRExperienceHelper.prototype.getClassName = function () {
  92451. return "VRExperienceHelper";
  92452. };
  92453. return VRExperienceHelper;
  92454. }());
  92455. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92456. })(BABYLON || (BABYLON = {}));
  92457. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92458. // Mainly based on these 2 articles :
  92459. // 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
  92460. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92461. var BABYLON;
  92462. (function (BABYLON) {
  92463. /**
  92464. * Defines the potential axis of a Joystick
  92465. */
  92466. var JoystickAxis;
  92467. (function (JoystickAxis) {
  92468. /** X axis */
  92469. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92470. /** Y axis */
  92471. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92472. /** Z axis */
  92473. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92474. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92475. /**
  92476. * Class used to define virtual joystick (used in touch mode)
  92477. */
  92478. var VirtualJoystick = /** @class */ (function () {
  92479. /**
  92480. * Creates a new virtual joystick
  92481. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92482. */
  92483. function VirtualJoystick(leftJoystick) {
  92484. var _this = this;
  92485. if (leftJoystick) {
  92486. this._leftJoystick = true;
  92487. }
  92488. else {
  92489. this._leftJoystick = false;
  92490. }
  92491. VirtualJoystick._globalJoystickIndex++;
  92492. // By default left & right arrow keys are moving the X
  92493. // and up & down keys are moving the Y
  92494. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92495. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92496. this.reverseLeftRight = false;
  92497. this.reverseUpDown = false;
  92498. // collections of pointers
  92499. this._touches = new BABYLON.StringDictionary();
  92500. this.deltaPosition = BABYLON.Vector3.Zero();
  92501. this._joystickSensibility = 25;
  92502. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92503. this._onResize = function (evt) {
  92504. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92505. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92506. if (VirtualJoystick.vjCanvas) {
  92507. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92508. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92509. }
  92510. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92511. };
  92512. // injecting a canvas element on top of the canvas 3D game
  92513. if (!VirtualJoystick.vjCanvas) {
  92514. window.addEventListener("resize", this._onResize, false);
  92515. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92516. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92517. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92518. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92519. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92520. VirtualJoystick.vjCanvas.style.width = "100%";
  92521. VirtualJoystick.vjCanvas.style.height = "100%";
  92522. VirtualJoystick.vjCanvas.style.position = "absolute";
  92523. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92524. VirtualJoystick.vjCanvas.style.top = "0px";
  92525. VirtualJoystick.vjCanvas.style.left = "0px";
  92526. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92527. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92528. // Support for jQuery PEP polyfill
  92529. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92530. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92531. if (!context) {
  92532. throw new Error("Unable to create canvas for virtual joystick");
  92533. }
  92534. VirtualJoystick.vjCanvasContext = context;
  92535. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92536. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92537. document.body.appendChild(VirtualJoystick.vjCanvas);
  92538. }
  92539. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92540. this.pressed = false;
  92541. // default joystick color
  92542. this._joystickColor = "cyan";
  92543. this._joystickPointerID = -1;
  92544. // current joystick position
  92545. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92546. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92547. // origin joystick position
  92548. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92549. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92550. this._onPointerDownHandlerRef = function (evt) {
  92551. _this._onPointerDown(evt);
  92552. };
  92553. this._onPointerMoveHandlerRef = function (evt) {
  92554. _this._onPointerMove(evt);
  92555. };
  92556. this._onPointerUpHandlerRef = function (evt) {
  92557. _this._onPointerUp(evt);
  92558. };
  92559. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92560. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92561. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92562. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92563. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92564. evt.preventDefault(); // Disables system menu
  92565. }, false);
  92566. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92567. }
  92568. /**
  92569. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92570. * @param newJoystickSensibility defines the new sensibility
  92571. */
  92572. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92573. this._joystickSensibility = newJoystickSensibility;
  92574. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92575. };
  92576. VirtualJoystick.prototype._onPointerDown = function (e) {
  92577. var positionOnScreenCondition;
  92578. e.preventDefault();
  92579. if (this._leftJoystick === true) {
  92580. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92581. }
  92582. else {
  92583. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92584. }
  92585. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  92586. // First contact will be dedicated to the virtual joystick
  92587. this._joystickPointerID = e.pointerId;
  92588. this._joystickPointerStartPos.x = e.clientX;
  92589. this._joystickPointerStartPos.y = e.clientY;
  92590. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  92591. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  92592. this._deltaJoystickVector.x = 0;
  92593. this._deltaJoystickVector.y = 0;
  92594. this.pressed = true;
  92595. this._touches.add(e.pointerId.toString(), e);
  92596. }
  92597. else {
  92598. // You can only trigger the action buttons with a joystick declared
  92599. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  92600. this._action();
  92601. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  92602. }
  92603. }
  92604. };
  92605. VirtualJoystick.prototype._onPointerMove = function (e) {
  92606. // If the current pointer is the one associated to the joystick (first touch contact)
  92607. if (this._joystickPointerID == e.pointerId) {
  92608. this._joystickPointerPos.x = e.clientX;
  92609. this._joystickPointerPos.y = e.clientY;
  92610. this._deltaJoystickVector = this._joystickPointerPos.clone();
  92611. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  92612. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  92613. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  92614. switch (this._axisTargetedByLeftAndRight) {
  92615. case JoystickAxis.X:
  92616. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  92617. break;
  92618. case JoystickAxis.Y:
  92619. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  92620. break;
  92621. case JoystickAxis.Z:
  92622. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  92623. break;
  92624. }
  92625. var directionUpDown = this.reverseUpDown ? 1 : -1;
  92626. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  92627. switch (this._axisTargetedByUpAndDown) {
  92628. case JoystickAxis.X:
  92629. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  92630. break;
  92631. case JoystickAxis.Y:
  92632. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  92633. break;
  92634. case JoystickAxis.Z:
  92635. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  92636. break;
  92637. }
  92638. }
  92639. else {
  92640. var data = this._touches.get(e.pointerId.toString());
  92641. if (data) {
  92642. data.x = e.clientX;
  92643. data.y = e.clientY;
  92644. }
  92645. }
  92646. };
  92647. VirtualJoystick.prototype._onPointerUp = function (e) {
  92648. if (this._joystickPointerID == e.pointerId) {
  92649. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  92650. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  92651. this._joystickPointerID = -1;
  92652. this.pressed = false;
  92653. }
  92654. else {
  92655. var touch = this._touches.get(e.pointerId.toString());
  92656. if (touch) {
  92657. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92658. }
  92659. }
  92660. this._deltaJoystickVector.x = 0;
  92661. this._deltaJoystickVector.y = 0;
  92662. this._touches.remove(e.pointerId.toString());
  92663. };
  92664. /**
  92665. * Change the color of the virtual joystick
  92666. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  92667. */
  92668. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  92669. this._joystickColor = newColor;
  92670. };
  92671. /**
  92672. * Defines a callback to call when the joystick is touched
  92673. * @param action defines the callback
  92674. */
  92675. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  92676. this._action = action;
  92677. };
  92678. /**
  92679. * Defines which axis you'd like to control for left & right
  92680. * @param axis defines the axis to use
  92681. */
  92682. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  92683. switch (axis) {
  92684. case JoystickAxis.X:
  92685. case JoystickAxis.Y:
  92686. case JoystickAxis.Z:
  92687. this._axisTargetedByLeftAndRight = axis;
  92688. break;
  92689. default:
  92690. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92691. break;
  92692. }
  92693. };
  92694. /**
  92695. * Defines which axis you'd like to control for up & down
  92696. * @param axis defines the axis to use
  92697. */
  92698. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  92699. switch (axis) {
  92700. case JoystickAxis.X:
  92701. case JoystickAxis.Y:
  92702. case JoystickAxis.Z:
  92703. this._axisTargetedByUpAndDown = axis;
  92704. break;
  92705. default:
  92706. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92707. break;
  92708. }
  92709. };
  92710. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  92711. var _this = this;
  92712. if (this.pressed) {
  92713. this._touches.forEach(function (key, touch) {
  92714. if (touch.pointerId === _this._joystickPointerID) {
  92715. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  92716. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  92717. VirtualJoystick.vjCanvasContext.beginPath();
  92718. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92719. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92720. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  92721. VirtualJoystick.vjCanvasContext.stroke();
  92722. VirtualJoystick.vjCanvasContext.closePath();
  92723. VirtualJoystick.vjCanvasContext.beginPath();
  92724. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92725. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92726. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  92727. VirtualJoystick.vjCanvasContext.stroke();
  92728. VirtualJoystick.vjCanvasContext.closePath();
  92729. VirtualJoystick.vjCanvasContext.beginPath();
  92730. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92731. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  92732. VirtualJoystick.vjCanvasContext.stroke();
  92733. VirtualJoystick.vjCanvasContext.closePath();
  92734. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  92735. }
  92736. else {
  92737. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92738. VirtualJoystick.vjCanvasContext.beginPath();
  92739. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  92740. VirtualJoystick.vjCanvasContext.beginPath();
  92741. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  92742. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92743. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  92744. VirtualJoystick.vjCanvasContext.stroke();
  92745. VirtualJoystick.vjCanvasContext.closePath();
  92746. touch.prevX = touch.x;
  92747. touch.prevY = touch.y;
  92748. }
  92749. ;
  92750. });
  92751. }
  92752. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92753. };
  92754. /**
  92755. * Release internal HTML canvas
  92756. */
  92757. VirtualJoystick.prototype.releaseCanvas = function () {
  92758. if (VirtualJoystick.vjCanvas) {
  92759. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  92760. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  92761. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  92762. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  92763. window.removeEventListener("resize", this._onResize);
  92764. document.body.removeChild(VirtualJoystick.vjCanvas);
  92765. VirtualJoystick.vjCanvas = null;
  92766. }
  92767. };
  92768. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  92769. VirtualJoystick._globalJoystickIndex = 0;
  92770. return VirtualJoystick;
  92771. }());
  92772. BABYLON.VirtualJoystick = VirtualJoystick;
  92773. })(BABYLON || (BABYLON = {}));
  92774. //# sourceMappingURL=babylon.virtualJoystick.js.map
  92775. var BABYLON;
  92776. (function (BABYLON) {
  92777. // We're mainly based on the logic defined into the FreeCamera code
  92778. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  92779. __extends(VirtualJoysticksCamera, _super);
  92780. function VirtualJoysticksCamera(name, position, scene) {
  92781. var _this = _super.call(this, name, position, scene) || this;
  92782. _this.inputs.addVirtualJoystick();
  92783. return _this;
  92784. }
  92785. VirtualJoysticksCamera.prototype.getClassName = function () {
  92786. return "VirtualJoysticksCamera";
  92787. };
  92788. return VirtualJoysticksCamera;
  92789. }(BABYLON.FreeCamera));
  92790. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  92791. })(BABYLON || (BABYLON = {}));
  92792. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  92793. var BABYLON;
  92794. (function (BABYLON) {
  92795. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  92796. function FreeCameraVirtualJoystickInput() {
  92797. }
  92798. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  92799. return this._leftjoystick;
  92800. };
  92801. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  92802. return this._rightjoystick;
  92803. };
  92804. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  92805. if (this._leftjoystick) {
  92806. var camera = this.camera;
  92807. var speed = camera._computeLocalCameraSpeed() * 50;
  92808. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  92809. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  92810. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  92811. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  92812. if (!this._leftjoystick.pressed) {
  92813. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  92814. }
  92815. if (!this._rightjoystick.pressed) {
  92816. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  92817. }
  92818. }
  92819. };
  92820. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  92821. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  92822. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  92823. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  92824. this._leftjoystick.setJoystickSensibility(0.15);
  92825. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  92826. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  92827. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  92828. this._rightjoystick.reverseUpDown = true;
  92829. this._rightjoystick.setJoystickSensibility(0.05);
  92830. this._rightjoystick.setJoystickColor("yellow");
  92831. };
  92832. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  92833. this._leftjoystick.releaseCanvas();
  92834. this._rightjoystick.releaseCanvas();
  92835. };
  92836. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  92837. return "FreeCameraVirtualJoystickInput";
  92838. };
  92839. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  92840. return "virtualJoystick";
  92841. };
  92842. return FreeCameraVirtualJoystickInput;
  92843. }());
  92844. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  92845. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  92846. })(BABYLON || (BABYLON = {}));
  92847. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  92848. var BABYLON;
  92849. (function (BABYLON) {
  92850. var SimplificationSettings = /** @class */ (function () {
  92851. function SimplificationSettings(quality, distance, optimizeMesh) {
  92852. this.quality = quality;
  92853. this.distance = distance;
  92854. this.optimizeMesh = optimizeMesh;
  92855. }
  92856. return SimplificationSettings;
  92857. }());
  92858. BABYLON.SimplificationSettings = SimplificationSettings;
  92859. var SimplificationQueue = /** @class */ (function () {
  92860. function SimplificationQueue() {
  92861. this.running = false;
  92862. this._simplificationArray = [];
  92863. }
  92864. SimplificationQueue.prototype.addTask = function (task) {
  92865. this._simplificationArray.push(task);
  92866. };
  92867. SimplificationQueue.prototype.executeNext = function () {
  92868. var task = this._simplificationArray.pop();
  92869. if (task) {
  92870. this.running = true;
  92871. this.runSimplification(task);
  92872. }
  92873. else {
  92874. this.running = false;
  92875. }
  92876. };
  92877. SimplificationQueue.prototype.runSimplification = function (task) {
  92878. var _this = this;
  92879. if (task.parallelProcessing) {
  92880. //parallel simplifier
  92881. task.settings.forEach(function (setting) {
  92882. var simplifier = _this.getSimplifier(task);
  92883. simplifier.simplify(setting, function (newMesh) {
  92884. task.mesh.addLODLevel(setting.distance, newMesh);
  92885. newMesh.isVisible = true;
  92886. //check if it is the last
  92887. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  92888. //all done, run the success callback.
  92889. task.successCallback();
  92890. }
  92891. _this.executeNext();
  92892. });
  92893. });
  92894. }
  92895. else {
  92896. //single simplifier.
  92897. var simplifier = this.getSimplifier(task);
  92898. var runDecimation = function (setting, callback) {
  92899. simplifier.simplify(setting, function (newMesh) {
  92900. task.mesh.addLODLevel(setting.distance, newMesh);
  92901. newMesh.isVisible = true;
  92902. //run the next quality level
  92903. callback();
  92904. });
  92905. };
  92906. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92907. runDecimation(task.settings[loop.index], function () {
  92908. loop.executeNext();
  92909. });
  92910. }, function () {
  92911. //execution ended, run the success callback.
  92912. if (task.successCallback) {
  92913. task.successCallback();
  92914. }
  92915. _this.executeNext();
  92916. });
  92917. }
  92918. };
  92919. SimplificationQueue.prototype.getSimplifier = function (task) {
  92920. switch (task.simplificationType) {
  92921. case SimplificationType.QUADRATIC:
  92922. default:
  92923. return new QuadraticErrorSimplification(task.mesh);
  92924. }
  92925. };
  92926. return SimplificationQueue;
  92927. }());
  92928. BABYLON.SimplificationQueue = SimplificationQueue;
  92929. /**
  92930. * The implemented types of simplification
  92931. * At the moment only Quadratic Error Decimation is implemented
  92932. */
  92933. var SimplificationType;
  92934. (function (SimplificationType) {
  92935. /** Quadratic error decimation */
  92936. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92937. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92938. var DecimationTriangle = /** @class */ (function () {
  92939. function DecimationTriangle(vertices) {
  92940. this.vertices = vertices;
  92941. this.error = new Array(4);
  92942. this.deleted = false;
  92943. this.isDirty = false;
  92944. this.deletePending = false;
  92945. this.borderFactor = 0;
  92946. }
  92947. return DecimationTriangle;
  92948. }());
  92949. BABYLON.DecimationTriangle = DecimationTriangle;
  92950. var DecimationVertex = /** @class */ (function () {
  92951. function DecimationVertex(position, id) {
  92952. this.position = position;
  92953. this.id = id;
  92954. this.isBorder = true;
  92955. this.q = new QuadraticMatrix();
  92956. this.triangleCount = 0;
  92957. this.triangleStart = 0;
  92958. this.originalOffsets = [];
  92959. }
  92960. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92961. this.position.copyFrom(newPosition);
  92962. };
  92963. return DecimationVertex;
  92964. }());
  92965. BABYLON.DecimationVertex = DecimationVertex;
  92966. var QuadraticMatrix = /** @class */ (function () {
  92967. function QuadraticMatrix(data) {
  92968. this.data = new Array(10);
  92969. for (var i = 0; i < 10; ++i) {
  92970. if (data && data[i]) {
  92971. this.data[i] = data[i];
  92972. }
  92973. else {
  92974. this.data[i] = 0;
  92975. }
  92976. }
  92977. }
  92978. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92979. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92980. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92981. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92982. return det;
  92983. };
  92984. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92985. for (var i = 0; i < 10; ++i) {
  92986. this.data[i] += matrix.data[i];
  92987. }
  92988. };
  92989. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92990. for (var i = 0; i < 10; ++i) {
  92991. this.data[i] += data[i];
  92992. }
  92993. };
  92994. QuadraticMatrix.prototype.add = function (matrix) {
  92995. var m = new QuadraticMatrix();
  92996. for (var i = 0; i < 10; ++i) {
  92997. m.data[i] = this.data[i] + matrix.data[i];
  92998. }
  92999. return m;
  93000. };
  93001. QuadraticMatrix.FromData = function (a, b, c, d) {
  93002. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93003. };
  93004. //returning an array to avoid garbage collection
  93005. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93006. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93007. };
  93008. return QuadraticMatrix;
  93009. }());
  93010. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93011. var Reference = /** @class */ (function () {
  93012. function Reference(vertexId, triangleId) {
  93013. this.vertexId = vertexId;
  93014. this.triangleId = triangleId;
  93015. }
  93016. return Reference;
  93017. }());
  93018. BABYLON.Reference = Reference;
  93019. /**
  93020. * An implementation of the Quadratic Error simplification algorithm.
  93021. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93022. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93023. * @author RaananW
  93024. */
  93025. var QuadraticErrorSimplification = /** @class */ (function () {
  93026. function QuadraticErrorSimplification(_mesh) {
  93027. this._mesh = _mesh;
  93028. this.syncIterations = 5000;
  93029. this.aggressiveness = 7;
  93030. this.decimationIterations = 100;
  93031. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93032. }
  93033. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93034. var _this = this;
  93035. this.initDecimatedMesh();
  93036. //iterating through the submeshes array, one after the other.
  93037. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93038. _this.initWithMesh(loop.index, function () {
  93039. _this.runDecimation(settings, loop.index, function () {
  93040. loop.executeNext();
  93041. });
  93042. }, settings.optimizeMesh);
  93043. }, function () {
  93044. setTimeout(function () {
  93045. successCallback(_this._reconstructedMesh);
  93046. }, 0);
  93047. });
  93048. };
  93049. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93050. var _this = this;
  93051. var targetCount = ~~(this.triangles.length * settings.quality);
  93052. var deletedTriangles = 0;
  93053. var triangleCount = this.triangles.length;
  93054. var iterationFunction = function (iteration, callback) {
  93055. setTimeout(function () {
  93056. if (iteration % 5 === 0) {
  93057. _this.updateMesh(iteration === 0);
  93058. }
  93059. for (var i = 0; i < _this.triangles.length; ++i) {
  93060. _this.triangles[i].isDirty = false;
  93061. }
  93062. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93063. var trianglesIterator = function (i) {
  93064. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93065. var t = _this.triangles[tIdx];
  93066. if (!t)
  93067. return;
  93068. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93069. return;
  93070. }
  93071. for (var j = 0; j < 3; ++j) {
  93072. if (t.error[j] < threshold) {
  93073. var deleted0 = [];
  93074. var deleted1 = [];
  93075. var v0 = t.vertices[j];
  93076. var v1 = t.vertices[(j + 1) % 3];
  93077. if (v0.isBorder || v1.isBorder)
  93078. continue;
  93079. var p = BABYLON.Vector3.Zero();
  93080. var n = BABYLON.Vector3.Zero();
  93081. var uv = BABYLON.Vector2.Zero();
  93082. var color = new BABYLON.Color4(0, 0, 0, 1);
  93083. _this.calculateError(v0, v1, p, n, uv, color);
  93084. var delTr = new Array();
  93085. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93086. continue;
  93087. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93088. continue;
  93089. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93090. continue;
  93091. var uniqueArray = new Array();
  93092. delTr.forEach(function (deletedT) {
  93093. if (uniqueArray.indexOf(deletedT) === -1) {
  93094. deletedT.deletePending = true;
  93095. uniqueArray.push(deletedT);
  93096. }
  93097. });
  93098. if (uniqueArray.length % 2 !== 0) {
  93099. continue;
  93100. }
  93101. v0.q = v1.q.add(v0.q);
  93102. v0.updatePosition(p);
  93103. var tStart = _this.references.length;
  93104. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93105. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93106. var tCount = _this.references.length - tStart;
  93107. if (tCount <= v0.triangleCount) {
  93108. if (tCount) {
  93109. for (var c = 0; c < tCount; c++) {
  93110. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93111. }
  93112. }
  93113. }
  93114. else {
  93115. v0.triangleStart = tStart;
  93116. }
  93117. v0.triangleCount = tCount;
  93118. break;
  93119. }
  93120. }
  93121. };
  93122. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93123. }, 0);
  93124. };
  93125. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93126. if (triangleCount - deletedTriangles <= targetCount)
  93127. loop.breakLoop();
  93128. else {
  93129. iterationFunction(loop.index, function () {
  93130. loop.executeNext();
  93131. });
  93132. }
  93133. }, function () {
  93134. setTimeout(function () {
  93135. //reconstruct this part of the mesh
  93136. _this.reconstructMesh(submeshIndex);
  93137. successCallback();
  93138. }, 0);
  93139. });
  93140. };
  93141. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93142. var _this = this;
  93143. this.vertices = [];
  93144. this.triangles = [];
  93145. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93146. var indices = this._mesh.getIndices();
  93147. var submesh = this._mesh.subMeshes[submeshIndex];
  93148. var findInVertices = function (positionToSearch) {
  93149. if (optimizeMesh) {
  93150. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93151. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93152. return _this.vertices[ii];
  93153. }
  93154. }
  93155. }
  93156. return null;
  93157. };
  93158. var vertexReferences = [];
  93159. var vertexInit = function (i) {
  93160. if (!positionData) {
  93161. return;
  93162. }
  93163. var offset = i + submesh.verticesStart;
  93164. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93165. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93166. vertex.originalOffsets.push(offset);
  93167. if (vertex.id === _this.vertices.length) {
  93168. _this.vertices.push(vertex);
  93169. }
  93170. vertexReferences.push(vertex.id);
  93171. };
  93172. //var totalVertices = mesh.getTotalVertices();
  93173. var totalVertices = submesh.verticesCount;
  93174. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93175. var indicesInit = function (i) {
  93176. if (!indices) {
  93177. return;
  93178. }
  93179. var offset = (submesh.indexStart / 3) + i;
  93180. var pos = (offset * 3);
  93181. var i0 = indices[pos + 0];
  93182. var i1 = indices[pos + 1];
  93183. var i2 = indices[pos + 2];
  93184. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93185. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93186. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93187. var triangle = new DecimationTriangle([v0, v1, v2]);
  93188. triangle.originalOffset = pos;
  93189. _this.triangles.push(triangle);
  93190. };
  93191. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93192. _this.init(callback);
  93193. });
  93194. });
  93195. };
  93196. QuadraticErrorSimplification.prototype.init = function (callback) {
  93197. var _this = this;
  93198. var triangleInit1 = function (i) {
  93199. var t = _this.triangles[i];
  93200. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93201. for (var j = 0; j < 3; j++) {
  93202. 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))));
  93203. }
  93204. };
  93205. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93206. var triangleInit2 = function (i) {
  93207. var t = _this.triangles[i];
  93208. for (var j = 0; j < 3; ++j) {
  93209. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93210. }
  93211. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93212. };
  93213. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93214. callback();
  93215. });
  93216. });
  93217. };
  93218. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93219. var newTriangles = [];
  93220. var i;
  93221. for (i = 0; i < this.vertices.length; ++i) {
  93222. this.vertices[i].triangleCount = 0;
  93223. }
  93224. var t;
  93225. var j;
  93226. for (i = 0; i < this.triangles.length; ++i) {
  93227. if (!this.triangles[i].deleted) {
  93228. t = this.triangles[i];
  93229. for (j = 0; j < 3; ++j) {
  93230. t.vertices[j].triangleCount = 1;
  93231. }
  93232. newTriangles.push(t);
  93233. }
  93234. }
  93235. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93236. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93237. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93238. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93239. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93240. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93241. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93242. var vertexCount = 0;
  93243. for (i = 0; i < this.vertices.length; ++i) {
  93244. var vertex = this.vertices[i];
  93245. vertex.id = vertexCount;
  93246. if (vertex.triangleCount) {
  93247. vertex.originalOffsets.forEach(function (originalOffset) {
  93248. if (!normalData) {
  93249. return;
  93250. }
  93251. newPositionData.push(vertex.position.x);
  93252. newPositionData.push(vertex.position.y);
  93253. newPositionData.push(vertex.position.z);
  93254. newNormalData.push(normalData[originalOffset * 3]);
  93255. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93256. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93257. if (uvs && uvs.length) {
  93258. newUVsData.push(uvs[(originalOffset * 2)]);
  93259. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93260. }
  93261. else if (colorsData && colorsData.length) {
  93262. newColorsData.push(colorsData[(originalOffset * 4)]);
  93263. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93264. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93265. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93266. }
  93267. ++vertexCount;
  93268. });
  93269. }
  93270. }
  93271. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93272. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93273. var submeshesArray = this._reconstructedMesh.subMeshes;
  93274. this._reconstructedMesh.subMeshes = [];
  93275. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93276. var originalIndices = this._mesh.getIndices();
  93277. for (i = 0; i < newTriangles.length; ++i) {
  93278. t = newTriangles[i]; //now get the new referencing point for each vertex
  93279. [0, 1, 2].forEach(function (idx) {
  93280. var id = originalIndices[t.originalOffset + idx];
  93281. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93282. if (offset < 0)
  93283. offset = 0;
  93284. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93285. });
  93286. }
  93287. //overwriting the old vertex buffers and indices.
  93288. this._reconstructedMesh.setIndices(newIndicesArray);
  93289. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93290. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93291. if (newUVsData.length > 0)
  93292. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93293. if (newColorsData.length > 0)
  93294. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93295. //create submesh
  93296. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93297. if (submeshIndex > 0) {
  93298. this._reconstructedMesh.subMeshes = [];
  93299. submeshesArray.forEach(function (submesh) {
  93300. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93301. });
  93302. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93303. }
  93304. };
  93305. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93306. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93307. this._reconstructedMesh.material = this._mesh.material;
  93308. this._reconstructedMesh.parent = this._mesh.parent;
  93309. this._reconstructedMesh.isVisible = false;
  93310. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93311. };
  93312. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93313. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93314. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93315. if (t.deleted)
  93316. continue;
  93317. var s = this.references[vertex1.triangleStart + i].vertexId;
  93318. var v1 = t.vertices[(s + 1) % 3];
  93319. var v2 = t.vertices[(s + 2) % 3];
  93320. if ((v1 === vertex2 || v2 === vertex2)) {
  93321. deletedArray[i] = true;
  93322. delTr.push(t);
  93323. continue;
  93324. }
  93325. var d1 = v1.position.subtract(point);
  93326. d1 = d1.normalize();
  93327. var d2 = v2.position.subtract(point);
  93328. d2 = d2.normalize();
  93329. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93330. return true;
  93331. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93332. deletedArray[i] = false;
  93333. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93334. return true;
  93335. }
  93336. return false;
  93337. };
  93338. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93339. var newDeleted = deletedTriangles;
  93340. for (var i = 0; i < vertex.triangleCount; ++i) {
  93341. var ref = this.references[vertex.triangleStart + i];
  93342. var t = this.triangles[ref.triangleId];
  93343. if (t.deleted)
  93344. continue;
  93345. if (deletedArray[i] && t.deletePending) {
  93346. t.deleted = true;
  93347. newDeleted++;
  93348. continue;
  93349. }
  93350. t.vertices[ref.vertexId] = origVertex;
  93351. t.isDirty = true;
  93352. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93353. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93354. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93355. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93356. this.references.push(ref);
  93357. }
  93358. return newDeleted;
  93359. };
  93360. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93361. for (var i = 0; i < this.vertices.length; ++i) {
  93362. var vCount = [];
  93363. var vId = [];
  93364. var v = this.vertices[i];
  93365. var j;
  93366. for (j = 0; j < v.triangleCount; ++j) {
  93367. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93368. for (var ii = 0; ii < 3; ii++) {
  93369. var ofs = 0;
  93370. var vv = triangle.vertices[ii];
  93371. while (ofs < vCount.length) {
  93372. if (vId[ofs] === vv.id)
  93373. break;
  93374. ++ofs;
  93375. }
  93376. if (ofs === vCount.length) {
  93377. vCount.push(1);
  93378. vId.push(vv.id);
  93379. }
  93380. else {
  93381. vCount[ofs]++;
  93382. }
  93383. }
  93384. }
  93385. for (j = 0; j < vCount.length; ++j) {
  93386. if (vCount[j] === 1) {
  93387. this.vertices[vId[j]].isBorder = true;
  93388. }
  93389. else {
  93390. this.vertices[vId[j]].isBorder = false;
  93391. }
  93392. }
  93393. }
  93394. };
  93395. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93396. if (identifyBorders === void 0) { identifyBorders = false; }
  93397. var i;
  93398. if (!identifyBorders) {
  93399. var newTrianglesVector = [];
  93400. for (i = 0; i < this.triangles.length; ++i) {
  93401. if (!this.triangles[i].deleted) {
  93402. newTrianglesVector.push(this.triangles[i]);
  93403. }
  93404. }
  93405. this.triangles = newTrianglesVector;
  93406. }
  93407. for (i = 0; i < this.vertices.length; ++i) {
  93408. this.vertices[i].triangleCount = 0;
  93409. this.vertices[i].triangleStart = 0;
  93410. }
  93411. var t;
  93412. var j;
  93413. var v;
  93414. for (i = 0; i < this.triangles.length; ++i) {
  93415. t = this.triangles[i];
  93416. for (j = 0; j < 3; ++j) {
  93417. v = t.vertices[j];
  93418. v.triangleCount++;
  93419. }
  93420. }
  93421. var tStart = 0;
  93422. for (i = 0; i < this.vertices.length; ++i) {
  93423. this.vertices[i].triangleStart = tStart;
  93424. tStart += this.vertices[i].triangleCount;
  93425. this.vertices[i].triangleCount = 0;
  93426. }
  93427. var newReferences = new Array(this.triangles.length * 3);
  93428. for (i = 0; i < this.triangles.length; ++i) {
  93429. t = this.triangles[i];
  93430. for (j = 0; j < 3; ++j) {
  93431. v = t.vertices[j];
  93432. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93433. v.triangleCount++;
  93434. }
  93435. }
  93436. this.references = newReferences;
  93437. if (identifyBorders) {
  93438. this.identifyBorder();
  93439. }
  93440. };
  93441. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93442. var x = point.x;
  93443. var y = point.y;
  93444. var z = point.z;
  93445. 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
  93446. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93447. };
  93448. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93449. var q = vertex1.q.add(vertex2.q);
  93450. var border = vertex1.isBorder && vertex2.isBorder;
  93451. var error = 0;
  93452. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93453. if (qDet !== 0 && !border) {
  93454. if (!pointResult) {
  93455. pointResult = BABYLON.Vector3.Zero();
  93456. }
  93457. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93458. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93459. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93460. error = this.vertexError(q, pointResult);
  93461. }
  93462. else {
  93463. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93464. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93465. var error1 = this.vertexError(q, vertex1.position);
  93466. var error2 = this.vertexError(q, vertex2.position);
  93467. var error3 = this.vertexError(q, p3);
  93468. error = Math.min(error1, error2, error3);
  93469. if (error === error1) {
  93470. if (pointResult) {
  93471. pointResult.copyFrom(vertex1.position);
  93472. }
  93473. }
  93474. else if (error === error2) {
  93475. if (pointResult) {
  93476. pointResult.copyFrom(vertex2.position);
  93477. }
  93478. }
  93479. else {
  93480. if (pointResult) {
  93481. pointResult.copyFrom(p3);
  93482. }
  93483. }
  93484. }
  93485. return error;
  93486. };
  93487. return QuadraticErrorSimplification;
  93488. }());
  93489. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93490. })(BABYLON || (BABYLON = {}));
  93491. //# sourceMappingURL=babylon.meshSimplification.js.map
  93492. var BABYLON;
  93493. (function (BABYLON) {
  93494. var MeshLODLevel = /** @class */ (function () {
  93495. function MeshLODLevel(distance, mesh) {
  93496. this.distance = distance;
  93497. this.mesh = mesh;
  93498. }
  93499. return MeshLODLevel;
  93500. }());
  93501. BABYLON.MeshLODLevel = MeshLODLevel;
  93502. })(BABYLON || (BABYLON = {}));
  93503. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93504. var BABYLON;
  93505. (function (BABYLON) {
  93506. /**
  93507. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93508. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93509. */
  93510. var SceneOptimization = /** @class */ (function () {
  93511. /**
  93512. * Creates the SceneOptimization object
  93513. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93514. * @param desc defines the description associated with the optimization
  93515. */
  93516. function SceneOptimization(
  93517. /**
  93518. * Defines the priority of this optimization (0 by default which means first in the list)
  93519. */
  93520. priority) {
  93521. if (priority === void 0) { priority = 0; }
  93522. this.priority = priority;
  93523. }
  93524. /**
  93525. * Gets a string describing the action executed by the current optimization
  93526. * @returns description string
  93527. */
  93528. SceneOptimization.prototype.getDescription = function () {
  93529. return "";
  93530. };
  93531. /**
  93532. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93533. * @param scene defines the current scene where to apply this optimization
  93534. * @param optimizer defines the current optimizer
  93535. * @returns true if everything that can be done was applied
  93536. */
  93537. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93538. return true;
  93539. };
  93540. ;
  93541. return SceneOptimization;
  93542. }());
  93543. BABYLON.SceneOptimization = SceneOptimization;
  93544. /**
  93545. * Defines an optimization used to reduce the size of render target textures
  93546. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93547. */
  93548. var TextureOptimization = /** @class */ (function (_super) {
  93549. __extends(TextureOptimization, _super);
  93550. /**
  93551. * Creates the TextureOptimization object
  93552. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93553. * @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
  93554. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93555. */
  93556. function TextureOptimization(
  93557. /**
  93558. * Defines the priority of this optimization (0 by default which means first in the list)
  93559. */
  93560. priority,
  93561. /**
  93562. * 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
  93563. */
  93564. maximumSize,
  93565. /**
  93566. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93567. */
  93568. step) {
  93569. if (priority === void 0) { priority = 0; }
  93570. if (maximumSize === void 0) { maximumSize = 1024; }
  93571. if (step === void 0) { step = 0.5; }
  93572. var _this = _super.call(this, priority) || this;
  93573. _this.priority = priority;
  93574. _this.maximumSize = maximumSize;
  93575. _this.step = step;
  93576. return _this;
  93577. }
  93578. /**
  93579. * Gets a string describing the action executed by the current optimization
  93580. * @returns description string
  93581. */
  93582. TextureOptimization.prototype.getDescription = function () {
  93583. return "Reducing render target texture size to " + this.maximumSize;
  93584. };
  93585. /**
  93586. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93587. * @param scene defines the current scene where to apply this optimization
  93588. * @param optimizer defines the current optimizer
  93589. * @returns true if everything that can be done was applied
  93590. */
  93591. TextureOptimization.prototype.apply = function (scene, optimizer) {
  93592. var allDone = true;
  93593. for (var index = 0; index < scene.textures.length; index++) {
  93594. var texture = scene.textures[index];
  93595. if (!texture.canRescale || texture.getContext) {
  93596. continue;
  93597. }
  93598. var currentSize = texture.getSize();
  93599. var maxDimension = Math.max(currentSize.width, currentSize.height);
  93600. if (maxDimension > this.maximumSize) {
  93601. texture.scale(this.step);
  93602. allDone = false;
  93603. }
  93604. }
  93605. return allDone;
  93606. };
  93607. return TextureOptimization;
  93608. }(SceneOptimization));
  93609. BABYLON.TextureOptimization = TextureOptimization;
  93610. /**
  93611. * Defines an optimization used to increase or decrease the rendering resolution
  93612. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93613. */
  93614. var HardwareScalingOptimization = /** @class */ (function (_super) {
  93615. __extends(HardwareScalingOptimization, _super);
  93616. /**
  93617. * Creates the HardwareScalingOptimization object
  93618. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93619. * @param maximumScale defines the maximum scale to use (2 by default)
  93620. * @param step defines the step to use between two passes (0.5 by default)
  93621. */
  93622. function HardwareScalingOptimization(
  93623. /**
  93624. * Defines the priority of this optimization (0 by default which means first in the list)
  93625. */
  93626. priority,
  93627. /**
  93628. * Defines the maximum scale to use (2 by default)
  93629. */
  93630. maximumScale,
  93631. /**
  93632. * Defines the step to use between two passes (0.5 by default)
  93633. */
  93634. step) {
  93635. if (priority === void 0) { priority = 0; }
  93636. if (maximumScale === void 0) { maximumScale = 2; }
  93637. if (step === void 0) { step = 0.25; }
  93638. var _this = _super.call(this, priority) || this;
  93639. _this.priority = priority;
  93640. _this.maximumScale = maximumScale;
  93641. _this.step = step;
  93642. _this._currentScale = -1;
  93643. _this._directionOffset = 1;
  93644. return _this;
  93645. }
  93646. /**
  93647. * Gets a string describing the action executed by the current optimization
  93648. * @return description string
  93649. */
  93650. HardwareScalingOptimization.prototype.getDescription = function () {
  93651. return "Setting hardware scaling level to " + this._currentScale;
  93652. };
  93653. /**
  93654. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93655. * @param scene defines the current scene where to apply this optimization
  93656. * @param optimizer defines the current optimizer
  93657. * @returns true if everything that can be done was applied
  93658. */
  93659. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  93660. if (this._currentScale === -1) {
  93661. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  93662. if (this._currentScale > this.maximumScale) {
  93663. this._directionOffset = -1;
  93664. }
  93665. }
  93666. this._currentScale += this._directionOffset * this.step;
  93667. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  93668. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  93669. };
  93670. ;
  93671. return HardwareScalingOptimization;
  93672. }(SceneOptimization));
  93673. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  93674. /**
  93675. * Defines an optimization used to remove shadows
  93676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93677. */
  93678. var ShadowsOptimization = /** @class */ (function (_super) {
  93679. __extends(ShadowsOptimization, _super);
  93680. function ShadowsOptimization() {
  93681. return _super !== null && _super.apply(this, arguments) || this;
  93682. }
  93683. /**
  93684. * Gets a string describing the action executed by the current optimization
  93685. * @return description string
  93686. */
  93687. ShadowsOptimization.prototype.getDescription = function () {
  93688. return "Turning shadows on/off";
  93689. };
  93690. /**
  93691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93692. * @param scene defines the current scene where to apply this optimization
  93693. * @param optimizer defines the current optimizer
  93694. * @returns true if everything that can be done was applied
  93695. */
  93696. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  93697. scene.shadowsEnabled = optimizer.isInImprovementMode;
  93698. return true;
  93699. };
  93700. ;
  93701. return ShadowsOptimization;
  93702. }(SceneOptimization));
  93703. BABYLON.ShadowsOptimization = ShadowsOptimization;
  93704. /**
  93705. * Defines an optimization used to turn post-processes off
  93706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93707. */
  93708. var PostProcessesOptimization = /** @class */ (function (_super) {
  93709. __extends(PostProcessesOptimization, _super);
  93710. function PostProcessesOptimization() {
  93711. return _super !== null && _super.apply(this, arguments) || this;
  93712. }
  93713. /**
  93714. * Gets a string describing the action executed by the current optimization
  93715. * @return description string
  93716. */
  93717. PostProcessesOptimization.prototype.getDescription = function () {
  93718. return "Turning post-processes on/off";
  93719. };
  93720. /**
  93721. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93722. * @param scene defines the current scene where to apply this optimization
  93723. * @param optimizer defines the current optimizer
  93724. * @returns true if everything that can be done was applied
  93725. */
  93726. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  93727. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  93728. return true;
  93729. };
  93730. ;
  93731. return PostProcessesOptimization;
  93732. }(SceneOptimization));
  93733. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  93734. /**
  93735. * Defines an optimization used to turn lens flares off
  93736. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93737. */
  93738. var LensFlaresOptimization = /** @class */ (function (_super) {
  93739. __extends(LensFlaresOptimization, _super);
  93740. function LensFlaresOptimization() {
  93741. return _super !== null && _super.apply(this, arguments) || this;
  93742. }
  93743. /**
  93744. * Gets a string describing the action executed by the current optimization
  93745. * @return description string
  93746. */
  93747. LensFlaresOptimization.prototype.getDescription = function () {
  93748. return "Turning lens flares on/off";
  93749. };
  93750. /**
  93751. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93752. * @param scene defines the current scene where to apply this optimization
  93753. * @param optimizer defines the current optimizer
  93754. * @returns true if everything that can be done was applied
  93755. */
  93756. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  93757. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  93758. return true;
  93759. };
  93760. ;
  93761. return LensFlaresOptimization;
  93762. }(SceneOptimization));
  93763. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  93764. /**
  93765. * Defines an optimization based on user defined callback.
  93766. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93767. */
  93768. var CustomOptimization = /** @class */ (function (_super) {
  93769. __extends(CustomOptimization, _super);
  93770. function CustomOptimization() {
  93771. return _super !== null && _super.apply(this, arguments) || this;
  93772. }
  93773. /**
  93774. * Gets a string describing the action executed by the current optimization
  93775. * @returns description string
  93776. */
  93777. CustomOptimization.prototype.getDescription = function () {
  93778. if (this.onGetDescription) {
  93779. return this.onGetDescription();
  93780. }
  93781. return "Running user defined callback";
  93782. };
  93783. /**
  93784. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93785. * @param scene defines the current scene where to apply this optimization
  93786. * @param optimizer defines the current optimizer
  93787. * @returns true if everything that can be done was applied
  93788. */
  93789. CustomOptimization.prototype.apply = function (scene, optimizer) {
  93790. if (this.onApply) {
  93791. return this.onApply(scene, optimizer);
  93792. }
  93793. return true;
  93794. };
  93795. ;
  93796. return CustomOptimization;
  93797. }(SceneOptimization));
  93798. BABYLON.CustomOptimization = CustomOptimization;
  93799. /**
  93800. * Defines an optimization used to turn particles off
  93801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93802. */
  93803. var ParticlesOptimization = /** @class */ (function (_super) {
  93804. __extends(ParticlesOptimization, _super);
  93805. function ParticlesOptimization() {
  93806. return _super !== null && _super.apply(this, arguments) || this;
  93807. }
  93808. /**
  93809. * Gets a string describing the action executed by the current optimization
  93810. * @return description string
  93811. */
  93812. ParticlesOptimization.prototype.getDescription = function () {
  93813. return "Turning particles on/off";
  93814. };
  93815. /**
  93816. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93817. * @param scene defines the current scene where to apply this optimization
  93818. * @param optimizer defines the current optimizer
  93819. * @returns true if everything that can be done was applied
  93820. */
  93821. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  93822. scene.particlesEnabled = optimizer.isInImprovementMode;
  93823. return true;
  93824. };
  93825. ;
  93826. return ParticlesOptimization;
  93827. }(SceneOptimization));
  93828. BABYLON.ParticlesOptimization = ParticlesOptimization;
  93829. /**
  93830. * Defines an optimization used to turn render targets off
  93831. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93832. */
  93833. var RenderTargetsOptimization = /** @class */ (function (_super) {
  93834. __extends(RenderTargetsOptimization, _super);
  93835. function RenderTargetsOptimization() {
  93836. return _super !== null && _super.apply(this, arguments) || this;
  93837. }
  93838. /**
  93839. * Gets a string describing the action executed by the current optimization
  93840. * @return description string
  93841. */
  93842. RenderTargetsOptimization.prototype.getDescription = function () {
  93843. return "Turning render targets off";
  93844. };
  93845. /**
  93846. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93847. * @param scene defines the current scene where to apply this optimization
  93848. * @param optimizer defines the current optimizer
  93849. * @returns true if everything that can be done was applied
  93850. */
  93851. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  93852. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  93853. return true;
  93854. };
  93855. ;
  93856. return RenderTargetsOptimization;
  93857. }(SceneOptimization));
  93858. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  93859. /**
  93860. * Defines an optimization used to merge meshes with compatible materials
  93861. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93862. */
  93863. var MergeMeshesOptimization = /** @class */ (function (_super) {
  93864. __extends(MergeMeshesOptimization, _super);
  93865. function MergeMeshesOptimization() {
  93866. var _this = _super !== null && _super.apply(this, arguments) || this;
  93867. _this._canBeMerged = function (abstractMesh) {
  93868. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  93869. return false;
  93870. }
  93871. var mesh = abstractMesh;
  93872. if (!mesh.isVisible || !mesh.isEnabled()) {
  93873. return false;
  93874. }
  93875. if (mesh.instances.length > 0) {
  93876. return false;
  93877. }
  93878. if (mesh.skeleton || mesh.hasLODLevels) {
  93879. return false;
  93880. }
  93881. if (mesh.parent) {
  93882. return false;
  93883. }
  93884. return true;
  93885. };
  93886. return _this;
  93887. }
  93888. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  93889. /**
  93890. * Gets or sets a boolean which defines if optimization octree has to be updated
  93891. */
  93892. get: function () {
  93893. return MergeMeshesOptimization._UpdateSelectionTree;
  93894. },
  93895. /**
  93896. * Gets or sets a boolean which defines if optimization octree has to be updated
  93897. */
  93898. set: function (value) {
  93899. MergeMeshesOptimization._UpdateSelectionTree = value;
  93900. },
  93901. enumerable: true,
  93902. configurable: true
  93903. });
  93904. /**
  93905. * Gets a string describing the action executed by the current optimization
  93906. * @return description string
  93907. */
  93908. MergeMeshesOptimization.prototype.getDescription = function () {
  93909. return "Merging similar meshes together";
  93910. };
  93911. /**
  93912. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93913. * @param scene defines the current scene where to apply this optimization
  93914. * @param optimizer defines the current optimizer
  93915. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93916. * @returns true if everything that can be done was applied
  93917. */
  93918. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93919. var globalPool = scene.meshes.slice(0);
  93920. var globalLength = globalPool.length;
  93921. for (var index = 0; index < globalLength; index++) {
  93922. var currentPool = new Array();
  93923. var current = globalPool[index];
  93924. // Checks
  93925. if (!this._canBeMerged(current)) {
  93926. continue;
  93927. }
  93928. currentPool.push(current);
  93929. // Find compatible meshes
  93930. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93931. var otherMesh = globalPool[subIndex];
  93932. if (!this._canBeMerged(otherMesh)) {
  93933. continue;
  93934. }
  93935. if (otherMesh.material !== current.material) {
  93936. continue;
  93937. }
  93938. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93939. continue;
  93940. }
  93941. currentPool.push(otherMesh);
  93942. globalLength--;
  93943. globalPool.splice(subIndex, 1);
  93944. subIndex--;
  93945. }
  93946. if (currentPool.length < 2) {
  93947. continue;
  93948. }
  93949. // Merge meshes
  93950. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93951. }
  93952. if (updateSelectionTree != undefined) {
  93953. if (updateSelectionTree) {
  93954. scene.createOrUpdateSelectionOctree();
  93955. }
  93956. }
  93957. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93958. scene.createOrUpdateSelectionOctree();
  93959. }
  93960. return true;
  93961. };
  93962. ;
  93963. MergeMeshesOptimization._UpdateSelectionTree = false;
  93964. return MergeMeshesOptimization;
  93965. }(SceneOptimization));
  93966. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93967. /**
  93968. * Defines a list of options used by SceneOptimizer
  93969. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93970. */
  93971. var SceneOptimizerOptions = /** @class */ (function () {
  93972. /**
  93973. * Creates a new list of options used by SceneOptimizer
  93974. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93975. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93976. */
  93977. function SceneOptimizerOptions(
  93978. /**
  93979. * Defines the target frame rate to reach (60 by default)
  93980. */
  93981. targetFrameRate,
  93982. /**
  93983. * Defines the interval between two checkes (2000ms by default)
  93984. */
  93985. trackerDuration) {
  93986. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93987. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93988. this.targetFrameRate = targetFrameRate;
  93989. this.trackerDuration = trackerDuration;
  93990. /**
  93991. * Gets the list of optimizations to apply
  93992. */
  93993. this.optimizations = new Array();
  93994. }
  93995. /**
  93996. * Add a new optimization
  93997. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93998. * @returns the current SceneOptimizerOptions
  93999. */
  94000. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94001. this.optimizations.push(optimization);
  94002. return this;
  94003. };
  94004. /**
  94005. * Add a new custom optimization
  94006. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94007. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94008. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94009. * @returns the current SceneOptimizerOptions
  94010. */
  94011. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94012. if (priority === void 0) { priority = 0; }
  94013. var optimization = new CustomOptimization(priority);
  94014. optimization.onApply = onApply;
  94015. optimization.onGetDescription = onGetDescription;
  94016. this.optimizations.push(optimization);
  94017. return this;
  94018. };
  94019. /**
  94020. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94021. * @param targetFrameRate defines the target frame rate (60 by default)
  94022. * @returns a SceneOptimizerOptions object
  94023. */
  94024. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94025. var result = new SceneOptimizerOptions(targetFrameRate);
  94026. var priority = 0;
  94027. result.addOptimization(new MergeMeshesOptimization(priority));
  94028. result.addOptimization(new ShadowsOptimization(priority));
  94029. result.addOptimization(new LensFlaresOptimization(priority));
  94030. // Next priority
  94031. priority++;
  94032. result.addOptimization(new PostProcessesOptimization(priority));
  94033. result.addOptimization(new ParticlesOptimization(priority));
  94034. // Next priority
  94035. priority++;
  94036. result.addOptimization(new TextureOptimization(priority, 1024));
  94037. return result;
  94038. };
  94039. /**
  94040. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94041. * @param targetFrameRate defines the target frame rate (60 by default)
  94042. * @returns a SceneOptimizerOptions object
  94043. */
  94044. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94045. var result = new SceneOptimizerOptions(targetFrameRate);
  94046. var priority = 0;
  94047. result.addOptimization(new MergeMeshesOptimization(priority));
  94048. result.addOptimization(new ShadowsOptimization(priority));
  94049. result.addOptimization(new LensFlaresOptimization(priority));
  94050. // Next priority
  94051. priority++;
  94052. result.addOptimization(new PostProcessesOptimization(priority));
  94053. result.addOptimization(new ParticlesOptimization(priority));
  94054. // Next priority
  94055. priority++;
  94056. result.addOptimization(new TextureOptimization(priority, 512));
  94057. // Next priority
  94058. priority++;
  94059. result.addOptimization(new RenderTargetsOptimization(priority));
  94060. // Next priority
  94061. priority++;
  94062. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94063. return result;
  94064. };
  94065. /**
  94066. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94067. * @param targetFrameRate defines the target frame rate (60 by default)
  94068. * @returns a SceneOptimizerOptions object
  94069. */
  94070. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94071. var result = new SceneOptimizerOptions(targetFrameRate);
  94072. var priority = 0;
  94073. result.addOptimization(new MergeMeshesOptimization(priority));
  94074. result.addOptimization(new ShadowsOptimization(priority));
  94075. result.addOptimization(new LensFlaresOptimization(priority));
  94076. // Next priority
  94077. priority++;
  94078. result.addOptimization(new PostProcessesOptimization(priority));
  94079. result.addOptimization(new ParticlesOptimization(priority));
  94080. // Next priority
  94081. priority++;
  94082. result.addOptimization(new TextureOptimization(priority, 256));
  94083. // Next priority
  94084. priority++;
  94085. result.addOptimization(new RenderTargetsOptimization(priority));
  94086. // Next priority
  94087. priority++;
  94088. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94089. return result;
  94090. };
  94091. return SceneOptimizerOptions;
  94092. }());
  94093. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94094. /**
  94095. * Class used to run optimizations in order to reach a target frame rate
  94096. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94097. */
  94098. var SceneOptimizer = /** @class */ (function () {
  94099. /**
  94100. * Creates a new SceneOptimizer
  94101. * @param scene defines the scene to work on
  94102. * @param options defines the options to use with the SceneOptimizer
  94103. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94104. * @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)
  94105. */
  94106. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94107. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94108. if (improvementMode === void 0) { improvementMode = false; }
  94109. var _this = this;
  94110. this._isRunning = false;
  94111. this._currentPriorityLevel = 0;
  94112. this._targetFrameRate = 60;
  94113. this._trackerDuration = 2000;
  94114. this._currentFrameRate = 0;
  94115. this._improvementMode = false;
  94116. /**
  94117. * Defines an observable called when the optimizer reaches the target frame rate
  94118. */
  94119. this.onSuccessObservable = new BABYLON.Observable();
  94120. /**
  94121. * Defines an observable called when the optimizer enables an optimization
  94122. */
  94123. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94124. /**
  94125. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94126. */
  94127. this.onFailureObservable = new BABYLON.Observable();
  94128. if (!options) {
  94129. this._options = new SceneOptimizerOptions();
  94130. }
  94131. else {
  94132. this._options = options;
  94133. }
  94134. if (this._options.targetFrameRate) {
  94135. this._targetFrameRate = this._options.targetFrameRate;
  94136. }
  94137. if (this._options.trackerDuration) {
  94138. this._trackerDuration = this._options.trackerDuration;
  94139. }
  94140. if (autoGeneratePriorities) {
  94141. var priority = 0;
  94142. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94143. var optim = _a[_i];
  94144. optim.priority = priority++;
  94145. }
  94146. }
  94147. this._improvementMode = improvementMode;
  94148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94149. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94150. _this._sceneDisposeObserver = null;
  94151. _this.dispose();
  94152. });
  94153. }
  94154. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94155. /**
  94156. * Gets a boolean indicating if the optimizer is in improvement mode
  94157. */
  94158. get: function () {
  94159. return this._improvementMode;
  94160. },
  94161. enumerable: true,
  94162. configurable: true
  94163. });
  94164. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94165. /**
  94166. * Gets the current priority level (0 at start)
  94167. */
  94168. get: function () {
  94169. return this._currentPriorityLevel;
  94170. },
  94171. enumerable: true,
  94172. configurable: true
  94173. });
  94174. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94175. /**
  94176. * Gets the current frame rate checked by the SceneOptimizer
  94177. */
  94178. get: function () {
  94179. return this._currentFrameRate;
  94180. },
  94181. enumerable: true,
  94182. configurable: true
  94183. });
  94184. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94185. /**
  94186. * Gets or sets the current target frame rate (60 by default)
  94187. */
  94188. get: function () {
  94189. return this._targetFrameRate;
  94190. },
  94191. /**
  94192. * Gets or sets the current target frame rate (60 by default)
  94193. */
  94194. set: function (value) {
  94195. this._targetFrameRate = value;
  94196. },
  94197. enumerable: true,
  94198. configurable: true
  94199. });
  94200. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94201. /**
  94202. * Gets or sets the current interval between two checks (every 2000ms by default)
  94203. */
  94204. get: function () {
  94205. return this._trackerDuration;
  94206. },
  94207. /**
  94208. * Gets or sets the current interval between two checks (every 2000ms by default)
  94209. */
  94210. set: function (value) {
  94211. this._trackerDuration = value;
  94212. },
  94213. enumerable: true,
  94214. configurable: true
  94215. });
  94216. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94217. /**
  94218. * Gets the list of active optimizations
  94219. */
  94220. get: function () {
  94221. return this._options.optimizations;
  94222. },
  94223. enumerable: true,
  94224. configurable: true
  94225. });
  94226. /**
  94227. * Stops the current optimizer
  94228. */
  94229. SceneOptimizer.prototype.stop = function () {
  94230. this._isRunning = false;
  94231. };
  94232. /**
  94233. * Reset the optimizer to initial step (current priority level = 0)
  94234. */
  94235. SceneOptimizer.prototype.reset = function () {
  94236. this._currentPriorityLevel = 0;
  94237. };
  94238. /**
  94239. * Start the optimizer. By default it will try to reach a specific framerate
  94240. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94241. */
  94242. SceneOptimizer.prototype.start = function () {
  94243. var _this = this;
  94244. if (this._isRunning) {
  94245. return;
  94246. }
  94247. this._isRunning = true;
  94248. // Let's wait for the scene to be ready before running our check
  94249. this._scene.executeWhenReady(function () {
  94250. setTimeout(function () {
  94251. _this._checkCurrentState();
  94252. }, _this._trackerDuration);
  94253. });
  94254. };
  94255. SceneOptimizer.prototype._checkCurrentState = function () {
  94256. var _this = this;
  94257. if (!this._isRunning) {
  94258. return;
  94259. }
  94260. var scene = this._scene;
  94261. var options = this._options;
  94262. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94263. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94264. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94265. this._isRunning = false;
  94266. this.onSuccessObservable.notifyObservers(this);
  94267. return;
  94268. }
  94269. // Apply current level of optimizations
  94270. var allDone = true;
  94271. var noOptimizationApplied = true;
  94272. for (var index = 0; index < options.optimizations.length; index++) {
  94273. var optimization = options.optimizations[index];
  94274. if (optimization.priority === this._currentPriorityLevel) {
  94275. noOptimizationApplied = false;
  94276. allDone = allDone && optimization.apply(scene, this);
  94277. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94278. }
  94279. }
  94280. // If no optimization was applied, this is a failure :(
  94281. if (noOptimizationApplied) {
  94282. this._isRunning = false;
  94283. this.onFailureObservable.notifyObservers(this);
  94284. return;
  94285. }
  94286. // If all optimizations were done, move to next level
  94287. if (allDone) {
  94288. this._currentPriorityLevel++;
  94289. }
  94290. // Let's the system running for a specific amount of time before checking FPS
  94291. scene.executeWhenReady(function () {
  94292. setTimeout(function () {
  94293. _this._checkCurrentState();
  94294. }, _this._trackerDuration);
  94295. });
  94296. };
  94297. /**
  94298. * Release all resources
  94299. */
  94300. SceneOptimizer.prototype.dispose = function () {
  94301. this.stop();
  94302. this.onSuccessObservable.clear();
  94303. this.onFailureObservable.clear();
  94304. this.onNewOptimizationAppliedObservable.clear();
  94305. if (this._sceneDisposeObserver) {
  94306. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94307. }
  94308. };
  94309. /**
  94310. * Helper function to create a SceneOptimizer with one single line of code
  94311. * @param scene defines the scene to work on
  94312. * @param options defines the options to use with the SceneOptimizer
  94313. * @param onSuccess defines a callback to call on success
  94314. * @param onFailure defines a callback to call on failure
  94315. * @returns the new SceneOptimizer object
  94316. */
  94317. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94318. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94319. if (onSuccess) {
  94320. optimizer.onSuccessObservable.add(function () {
  94321. onSuccess();
  94322. });
  94323. }
  94324. if (onFailure) {
  94325. optimizer.onFailureObservable.add(function () {
  94326. onFailure();
  94327. });
  94328. }
  94329. optimizer.start();
  94330. return optimizer;
  94331. };
  94332. return SceneOptimizer;
  94333. }());
  94334. BABYLON.SceneOptimizer = SceneOptimizer;
  94335. })(BABYLON || (BABYLON = {}));
  94336. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94337. var BABYLON;
  94338. (function (BABYLON) {
  94339. var OutlineRenderer = /** @class */ (function () {
  94340. function OutlineRenderer(scene) {
  94341. this.zOffset = 1;
  94342. this._scene = scene;
  94343. }
  94344. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94345. var _this = this;
  94346. if (useOverlay === void 0) { useOverlay = false; }
  94347. var scene = this._scene;
  94348. var engine = this._scene.getEngine();
  94349. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94350. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94351. return;
  94352. }
  94353. var mesh = subMesh.getRenderingMesh();
  94354. var material = subMesh.getMaterial();
  94355. if (!material || !scene.activeCamera) {
  94356. return;
  94357. }
  94358. engine.enableEffect(this._effect);
  94359. // Logarithmic depth
  94360. if (material.useLogarithmicDepth) {
  94361. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94362. }
  94363. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94364. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94365. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94366. // Bones
  94367. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94368. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94369. }
  94370. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94371. // Alpha test
  94372. if (material && material.needAlphaTesting()) {
  94373. var alphaTexture = material.getAlphaTestTexture();
  94374. if (alphaTexture) {
  94375. this._effect.setTexture("diffuseSampler", alphaTexture);
  94376. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94377. }
  94378. }
  94379. engine.setZOffset(-this.zOffset);
  94380. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94381. engine.setZOffset(0);
  94382. };
  94383. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94384. var defines = [];
  94385. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94386. var mesh = subMesh.getMesh();
  94387. var material = subMesh.getMaterial();
  94388. if (material) {
  94389. // Alpha test
  94390. if (material.needAlphaTesting()) {
  94391. defines.push("#define ALPHATEST");
  94392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94393. attribs.push(BABYLON.VertexBuffer.UVKind);
  94394. defines.push("#define UV1");
  94395. }
  94396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94397. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94398. defines.push("#define UV2");
  94399. }
  94400. }
  94401. //Logarithmic depth
  94402. if (material.useLogarithmicDepth) {
  94403. defines.push("#define LOGARITHMICDEPTH");
  94404. }
  94405. }
  94406. // Bones
  94407. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94408. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94409. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94410. if (mesh.numBoneInfluencers > 4) {
  94411. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94412. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94413. }
  94414. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94415. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94416. }
  94417. else {
  94418. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94419. }
  94420. // Instances
  94421. if (useInstances) {
  94422. defines.push("#define INSTANCES");
  94423. attribs.push("world0");
  94424. attribs.push("world1");
  94425. attribs.push("world2");
  94426. attribs.push("world3");
  94427. }
  94428. // Get correct effect
  94429. var join = defines.join("\n");
  94430. if (this._cachedDefines !== join) {
  94431. this._cachedDefines = join;
  94432. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94433. }
  94434. return this._effect.isReady();
  94435. };
  94436. return OutlineRenderer;
  94437. }());
  94438. BABYLON.OutlineRenderer = OutlineRenderer;
  94439. })(BABYLON || (BABYLON = {}));
  94440. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94441. var BABYLON;
  94442. (function (BABYLON) {
  94443. var FaceAdjacencies = /** @class */ (function () {
  94444. function FaceAdjacencies() {
  94445. this.edges = new Array();
  94446. this.edgesConnectedCount = 0;
  94447. }
  94448. return FaceAdjacencies;
  94449. }());
  94450. var EdgesRenderer = /** @class */ (function () {
  94451. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94452. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94453. if (epsilon === void 0) { epsilon = 0.95; }
  94454. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94455. this.edgesWidthScalerForOrthographic = 1000.0;
  94456. this.edgesWidthScalerForPerspective = 50.0;
  94457. this._linesPositions = new Array();
  94458. this._linesNormals = new Array();
  94459. this._linesIndices = new Array();
  94460. this._buffers = {};
  94461. this._checkVerticesInsteadOfIndices = false;
  94462. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94463. this.isEnabled = true;
  94464. this._source = source;
  94465. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94466. this._epsilon = epsilon;
  94467. this._prepareRessources();
  94468. this._generateEdgesLines();
  94469. }
  94470. EdgesRenderer.prototype._prepareRessources = function () {
  94471. if (this._lineShader) {
  94472. return;
  94473. }
  94474. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94475. attributes: ["position", "normal"],
  94476. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94477. });
  94478. this._lineShader.disableDepthWrite = true;
  94479. this._lineShader.backFaceCulling = false;
  94480. };
  94481. EdgesRenderer.prototype._rebuild = function () {
  94482. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94483. if (buffer) {
  94484. buffer._rebuild();
  94485. }
  94486. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94487. if (buffer) {
  94488. buffer._rebuild();
  94489. }
  94490. var scene = this._source.getScene();
  94491. var engine = scene.getEngine();
  94492. this._ib = engine.createIndexBuffer(this._linesIndices);
  94493. };
  94494. EdgesRenderer.prototype.dispose = function () {
  94495. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94496. if (buffer) {
  94497. buffer.dispose();
  94498. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94499. }
  94500. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94501. if (buffer) {
  94502. buffer.dispose();
  94503. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94504. }
  94505. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94506. this._lineShader.dispose();
  94507. };
  94508. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94509. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94510. return 0;
  94511. }
  94512. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94513. return 1;
  94514. }
  94515. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94516. return 2;
  94517. }
  94518. return -1;
  94519. };
  94520. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94521. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94522. return 0;
  94523. }
  94524. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94525. return 1;
  94526. }
  94527. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94528. return 2;
  94529. }
  94530. return -1;
  94531. };
  94532. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94533. var needToCreateLine;
  94534. if (edge === undefined) {
  94535. needToCreateLine = true;
  94536. }
  94537. else {
  94538. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94539. needToCreateLine = dotProduct < this._epsilon;
  94540. }
  94541. if (needToCreateLine) {
  94542. var offset = this._linesPositions.length / 3;
  94543. var normal = p0.subtract(p1);
  94544. normal.normalize();
  94545. // Positions
  94546. this._linesPositions.push(p0.x);
  94547. this._linesPositions.push(p0.y);
  94548. this._linesPositions.push(p0.z);
  94549. this._linesPositions.push(p0.x);
  94550. this._linesPositions.push(p0.y);
  94551. this._linesPositions.push(p0.z);
  94552. this._linesPositions.push(p1.x);
  94553. this._linesPositions.push(p1.y);
  94554. this._linesPositions.push(p1.z);
  94555. this._linesPositions.push(p1.x);
  94556. this._linesPositions.push(p1.y);
  94557. this._linesPositions.push(p1.z);
  94558. // Normals
  94559. this._linesNormals.push(p1.x);
  94560. this._linesNormals.push(p1.y);
  94561. this._linesNormals.push(p1.z);
  94562. this._linesNormals.push(-1);
  94563. this._linesNormals.push(p1.x);
  94564. this._linesNormals.push(p1.y);
  94565. this._linesNormals.push(p1.z);
  94566. this._linesNormals.push(1);
  94567. this._linesNormals.push(p0.x);
  94568. this._linesNormals.push(p0.y);
  94569. this._linesNormals.push(p0.z);
  94570. this._linesNormals.push(-1);
  94571. this._linesNormals.push(p0.x);
  94572. this._linesNormals.push(p0.y);
  94573. this._linesNormals.push(p0.z);
  94574. this._linesNormals.push(1);
  94575. // Indices
  94576. this._linesIndices.push(offset);
  94577. this._linesIndices.push(offset + 1);
  94578. this._linesIndices.push(offset + 2);
  94579. this._linesIndices.push(offset);
  94580. this._linesIndices.push(offset + 2);
  94581. this._linesIndices.push(offset + 3);
  94582. }
  94583. };
  94584. EdgesRenderer.prototype._generateEdgesLines = function () {
  94585. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94586. var indices = this._source.getIndices();
  94587. if (!indices || !positions) {
  94588. return;
  94589. }
  94590. // First let's find adjacencies
  94591. var adjacencies = new Array();
  94592. var faceNormals = new Array();
  94593. var index;
  94594. var faceAdjacencies;
  94595. // Prepare faces
  94596. for (index = 0; index < indices.length; index += 3) {
  94597. faceAdjacencies = new FaceAdjacencies();
  94598. var p0Index = indices[index];
  94599. var p1Index = indices[index + 1];
  94600. var p2Index = indices[index + 2];
  94601. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  94602. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  94603. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  94604. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  94605. faceNormal.normalize();
  94606. faceNormals.push(faceNormal);
  94607. adjacencies.push(faceAdjacencies);
  94608. }
  94609. // Scan
  94610. for (index = 0; index < adjacencies.length; index++) {
  94611. faceAdjacencies = adjacencies[index];
  94612. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  94613. var otherFaceAdjacencies = adjacencies[otherIndex];
  94614. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  94615. break;
  94616. }
  94617. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  94618. continue;
  94619. }
  94620. var otherP0 = indices[otherIndex * 3];
  94621. var otherP1 = indices[otherIndex * 3 + 1];
  94622. var otherP2 = indices[otherIndex * 3 + 2];
  94623. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  94624. var otherEdgeIndex = 0;
  94625. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  94626. continue;
  94627. }
  94628. switch (edgeIndex) {
  94629. case 0:
  94630. if (this._checkVerticesInsteadOfIndices) {
  94631. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94632. }
  94633. else {
  94634. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  94635. }
  94636. break;
  94637. case 1:
  94638. if (this._checkVerticesInsteadOfIndices) {
  94639. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94640. }
  94641. else {
  94642. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  94643. }
  94644. break;
  94645. case 2:
  94646. if (this._checkVerticesInsteadOfIndices) {
  94647. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94648. }
  94649. else {
  94650. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  94651. }
  94652. break;
  94653. }
  94654. if (otherEdgeIndex === -1) {
  94655. continue;
  94656. }
  94657. faceAdjacencies.edges[edgeIndex] = otherIndex;
  94658. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  94659. faceAdjacencies.edgesConnectedCount++;
  94660. otherFaceAdjacencies.edgesConnectedCount++;
  94661. if (faceAdjacencies.edgesConnectedCount === 3) {
  94662. break;
  94663. }
  94664. }
  94665. }
  94666. }
  94667. // Create lines
  94668. for (index = 0; index < adjacencies.length; index++) {
  94669. // 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
  94670. var current = adjacencies[index];
  94671. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  94672. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  94673. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  94674. }
  94675. // Merge into a single mesh
  94676. var engine = this._source.getScene().getEngine();
  94677. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  94678. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  94679. this._ib = engine.createIndexBuffer(this._linesIndices);
  94680. this._indicesCount = this._linesIndices.length;
  94681. };
  94682. EdgesRenderer.prototype.render = function () {
  94683. var scene = this._source.getScene();
  94684. if (!this._lineShader.isReady() || !scene.activeCamera) {
  94685. return;
  94686. }
  94687. var engine = scene.getEngine();
  94688. this._lineShader._preBind();
  94689. // VBOs
  94690. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  94691. scene.resetCachedMaterial();
  94692. this._lineShader.setColor4("color", this._source.edgesColor);
  94693. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  94694. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  94695. }
  94696. else {
  94697. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  94698. }
  94699. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  94700. this._lineShader.bind(this._source.getWorldMatrix());
  94701. // Draw order
  94702. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  94703. this._lineShader.unbind();
  94704. engine.setDepthWrite(true);
  94705. };
  94706. return EdgesRenderer;
  94707. }());
  94708. BABYLON.EdgesRenderer = EdgesRenderer;
  94709. })(BABYLON || (BABYLON = {}));
  94710. //# sourceMappingURL=babylon.edgesRenderer.js.map
  94711. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94712. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94713. s = arguments[i];
  94714. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94715. t[p] = s[p];
  94716. }
  94717. return t;
  94718. };
  94719. var BABYLON;
  94720. (function (BABYLON) {
  94721. /**
  94722. * The effect layer Helps adding post process effect blended with the main pass.
  94723. *
  94724. * This can be for instance use to generate glow or higlight effects on the scene.
  94725. *
  94726. * The effect layer class can not be used directly and is intented to inherited from to be
  94727. * customized per effects.
  94728. */
  94729. var EffectLayer = /** @class */ (function () {
  94730. /**
  94731. * Instantiates a new effect Layer and references it in the scene.
  94732. * @param name The name of the layer
  94733. * @param scene The scene to use the layer in
  94734. */
  94735. function EffectLayer(
  94736. /** The Friendly of the effect in the scene */
  94737. name, scene) {
  94738. this._vertexBuffers = {};
  94739. this._maxSize = 0;
  94740. this._mainTextureDesiredSize = { width: 0, height: 0 };
  94741. this._shouldRender = true;
  94742. this._postProcesses = [];
  94743. this._textures = [];
  94744. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  94745. /**
  94746. * The clear color of the texture used to generate the glow map.
  94747. */
  94748. this.neutralColor = new BABYLON.Color4();
  94749. /**
  94750. * Specifies wether the highlight layer is enabled or not.
  94751. */
  94752. this.isEnabled = true;
  94753. /**
  94754. * An event triggered when the effect layer has been disposed.
  94755. */
  94756. this.onDisposeObservable = new BABYLON.Observable();
  94757. /**
  94758. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  94759. */
  94760. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  94761. /**
  94762. * An event triggered when the generated texture is being merged in the scene.
  94763. */
  94764. this.onBeforeComposeObservable = new BABYLON.Observable();
  94765. /**
  94766. * An event triggered when the generated texture has been merged in the scene.
  94767. */
  94768. this.onAfterComposeObservable = new BABYLON.Observable();
  94769. /**
  94770. * An event triggered when the efffect layer changes its size.
  94771. */
  94772. this.onSizeChangedObservable = new BABYLON.Observable();
  94773. this.name = name;
  94774. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94775. this._engine = scene.getEngine();
  94776. this._maxSize = this._engine.getCaps().maxTextureSize;
  94777. this._scene.effectLayers.push(this);
  94778. // Generate Buffers
  94779. this._generateIndexBuffer();
  94780. this._genrateVertexBuffer();
  94781. }
  94782. Object.defineProperty(EffectLayer.prototype, "camera", {
  94783. /**
  94784. * Gets the camera attached to the layer.
  94785. */
  94786. get: function () {
  94787. return this._effectLayerOptions.camera;
  94788. },
  94789. enumerable: true,
  94790. configurable: true
  94791. });
  94792. /**
  94793. * Initializes the effect layer with the required options.
  94794. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  94795. */
  94796. EffectLayer.prototype._init = function (options) {
  94797. // Adapt options
  94798. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94799. this._setMainTextureSize();
  94800. this._createMainTexture();
  94801. this._createTextureAndPostProcesses();
  94802. this._mergeEffect = this._createMergeEffect();
  94803. };
  94804. /**
  94805. * Generates the index buffer of the full screen quad blending to the main canvas.
  94806. */
  94807. EffectLayer.prototype._generateIndexBuffer = function () {
  94808. // Indices
  94809. var indices = [];
  94810. indices.push(0);
  94811. indices.push(1);
  94812. indices.push(2);
  94813. indices.push(0);
  94814. indices.push(2);
  94815. indices.push(3);
  94816. this._indexBuffer = this._engine.createIndexBuffer(indices);
  94817. };
  94818. /**
  94819. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  94820. */
  94821. EffectLayer.prototype._genrateVertexBuffer = function () {
  94822. // VBO
  94823. var vertices = [];
  94824. vertices.push(1, 1);
  94825. vertices.push(-1, 1);
  94826. vertices.push(-1, -1);
  94827. vertices.push(1, -1);
  94828. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94829. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94830. };
  94831. /**
  94832. * Sets the main texture desired size which is the closest power of two
  94833. * of the engine canvas size.
  94834. */
  94835. EffectLayer.prototype._setMainTextureSize = function () {
  94836. if (this._effectLayerOptions.mainTextureFixedSize) {
  94837. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  94838. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  94839. }
  94840. else {
  94841. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  94842. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  94843. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  94844. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  94845. }
  94846. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  94847. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  94848. };
  94849. /**
  94850. * Creates the main texture for the effect layer.
  94851. */
  94852. EffectLayer.prototype._createMainTexture = function () {
  94853. var _this = this;
  94854. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  94855. width: this._mainTextureDesiredSize.width,
  94856. height: this._mainTextureDesiredSize.height
  94857. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94858. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  94859. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94860. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94861. this._mainTexture.anisotropicFilteringLevel = 1;
  94862. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94863. this._mainTexture.renderParticles = false;
  94864. this._mainTexture.renderList = null;
  94865. this._mainTexture.ignoreCameraViewport = true;
  94866. // Custom render function
  94867. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  94868. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  94869. var index;
  94870. var engine = _this._scene.getEngine();
  94871. if (depthOnlySubMeshes.length) {
  94872. engine.setColorWrite(false);
  94873. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  94874. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  94875. }
  94876. engine.setColorWrite(true);
  94877. }
  94878. for (index = 0; index < opaqueSubMeshes.length; index++) {
  94879. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  94880. }
  94881. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  94882. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  94883. }
  94884. for (index = 0; index < transparentSubMeshes.length; index++) {
  94885. _this._renderSubMesh(transparentSubMeshes.data[index]);
  94886. }
  94887. };
  94888. this._mainTexture.onClearObservable.add(function (engine) {
  94889. engine.clear(_this.neutralColor, true, true, true);
  94890. });
  94891. };
  94892. /**
  94893. * Checks for the readiness of the element composing the layer.
  94894. * @param subMesh the mesh to check for
  94895. * @param useInstances specify wether or not to use instances to render the mesh
  94896. * @param emissiveTexture the associated emissive texture used to generate the glow
  94897. * @return true if ready otherwise, false
  94898. */
  94899. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  94900. var material = subMesh.getMaterial();
  94901. if (!material) {
  94902. return false;
  94903. }
  94904. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94905. return false;
  94906. }
  94907. var defines = [];
  94908. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94909. var mesh = subMesh.getMesh();
  94910. var uv1 = false;
  94911. var uv2 = false;
  94912. // Alpha test
  94913. if (material && material.needAlphaTesting()) {
  94914. var alphaTexture = material.getAlphaTestTexture();
  94915. if (alphaTexture) {
  94916. defines.push("#define ALPHATEST");
  94917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94918. alphaTexture.coordinatesIndex === 1) {
  94919. defines.push("#define DIFFUSEUV2");
  94920. uv2 = true;
  94921. }
  94922. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94923. defines.push("#define DIFFUSEUV1");
  94924. uv1 = true;
  94925. }
  94926. }
  94927. }
  94928. // Emissive
  94929. if (emissiveTexture) {
  94930. defines.push("#define EMISSIVE");
  94931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94932. emissiveTexture.coordinatesIndex === 1) {
  94933. defines.push("#define EMISSIVEUV2");
  94934. uv2 = true;
  94935. }
  94936. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94937. defines.push("#define EMISSIVEUV1");
  94938. uv1 = true;
  94939. }
  94940. }
  94941. if (uv1) {
  94942. attribs.push(BABYLON.VertexBuffer.UVKind);
  94943. defines.push("#define UV1");
  94944. }
  94945. if (uv2) {
  94946. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94947. defines.push("#define UV2");
  94948. }
  94949. // Bones
  94950. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94951. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94952. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94953. if (mesh.numBoneInfluencers > 4) {
  94954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94956. }
  94957. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94958. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94959. }
  94960. else {
  94961. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94962. }
  94963. // Morph targets
  94964. var manager = mesh.morphTargetManager;
  94965. var morphInfluencers = 0;
  94966. if (manager) {
  94967. if (manager.numInfluencers > 0) {
  94968. defines.push("#define MORPHTARGETS");
  94969. morphInfluencers = manager.numInfluencers;
  94970. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94971. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94972. }
  94973. }
  94974. // Instances
  94975. if (useInstances) {
  94976. defines.push("#define INSTANCES");
  94977. attribs.push("world0");
  94978. attribs.push("world1");
  94979. attribs.push("world2");
  94980. attribs.push("world3");
  94981. }
  94982. // Get correct effect
  94983. var join = defines.join("\n");
  94984. if (this._cachedDefines !== join) {
  94985. this._cachedDefines = join;
  94986. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94987. }
  94988. return this._effectLayerMapGenerationEffect.isReady();
  94989. };
  94990. /**
  94991. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94992. */
  94993. EffectLayer.prototype.render = function () {
  94994. var currentEffect = this._mergeEffect;
  94995. // Check
  94996. if (!currentEffect.isReady())
  94997. return;
  94998. for (var i = 0; i < this._postProcesses.length; i++) {
  94999. if (!this._postProcesses[i].isReady()) {
  95000. return;
  95001. }
  95002. }
  95003. var engine = this._scene.getEngine();
  95004. this.onBeforeComposeObservable.notifyObservers(this);
  95005. // Render
  95006. engine.enableEffect(currentEffect);
  95007. engine.setState(false);
  95008. // VBOs
  95009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95010. // Cache
  95011. var previousAlphaMode = engine.getAlphaMode();
  95012. // Go Blend.
  95013. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95014. // Blends the map on the main canvas.
  95015. this._internalRender(currentEffect);
  95016. // Restore Alpha
  95017. engine.setAlphaMode(previousAlphaMode);
  95018. this.onAfterComposeObservable.notifyObservers(this);
  95019. // Handle size changes.
  95020. var size = this._mainTexture.getSize();
  95021. this._setMainTextureSize();
  95022. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95023. // Recreate RTT and post processes on size change.
  95024. this.onSizeChangedObservable.notifyObservers(this);
  95025. this._disposeTextureAndPostProcesses();
  95026. this._createMainTexture();
  95027. this._createTextureAndPostProcesses();
  95028. }
  95029. };
  95030. /**
  95031. * Determine if a given mesh will be used in the current effect.
  95032. * @param mesh mesh to test
  95033. * @returns true if the mesh will be used
  95034. */
  95035. EffectLayer.prototype.hasMesh = function (mesh) {
  95036. return true;
  95037. };
  95038. /**
  95039. * Returns true if the layer contains information to display, otherwise false.
  95040. * @returns true if the glow layer should be rendered
  95041. */
  95042. EffectLayer.prototype.shouldRender = function () {
  95043. return this.isEnabled && this._shouldRender;
  95044. };
  95045. /**
  95046. * Returns true if the mesh should render, otherwise false.
  95047. * @param mesh The mesh to render
  95048. * @returns true if it should render otherwise false
  95049. */
  95050. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95051. return true;
  95052. };
  95053. /**
  95054. * Returns true if the mesh should render, otherwise false.
  95055. * @param mesh The mesh to render
  95056. * @returns true if it should render otherwise false
  95057. */
  95058. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95059. return true;
  95060. };
  95061. /**
  95062. * Renders the submesh passed in parameter to the generation map.
  95063. */
  95064. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95065. var _this = this;
  95066. if (!this.shouldRender()) {
  95067. return;
  95068. }
  95069. var material = subMesh.getMaterial();
  95070. var mesh = subMesh.getRenderingMesh();
  95071. var scene = this._scene;
  95072. var engine = scene.getEngine();
  95073. if (!material) {
  95074. return;
  95075. }
  95076. // Do not block in blend mode.
  95077. if (material.needAlphaBlendingForMesh(mesh)) {
  95078. return;
  95079. }
  95080. // Culling
  95081. engine.setState(material.backFaceCulling);
  95082. // Managing instances
  95083. var batch = mesh._getInstancesRenderList(subMesh._id);
  95084. if (batch.mustReturn) {
  95085. return;
  95086. }
  95087. // Early Exit per mesh
  95088. if (!this._shouldRenderMesh(mesh)) {
  95089. return;
  95090. }
  95091. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95092. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95093. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95094. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95095. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95096. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95097. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95098. // Alpha test
  95099. if (material && material.needAlphaTesting()) {
  95100. var alphaTexture = material.getAlphaTestTexture();
  95101. if (alphaTexture) {
  95102. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95103. var textureMatrix = alphaTexture.getTextureMatrix();
  95104. if (textureMatrix) {
  95105. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95106. }
  95107. }
  95108. }
  95109. // Glow emissive only
  95110. if (this._emissiveTextureAndColor.texture) {
  95111. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95112. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95113. }
  95114. // Bones
  95115. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95116. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95117. }
  95118. // Morph targets
  95119. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95120. // Draw
  95121. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95122. }
  95123. else {
  95124. // Need to reset refresh rate of the shadowMap
  95125. this._mainTexture.resetRefreshCounter();
  95126. }
  95127. };
  95128. /**
  95129. * Rebuild the required buffers.
  95130. * @hidden Internal use only.
  95131. */
  95132. EffectLayer.prototype._rebuild = function () {
  95133. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95134. if (vb) {
  95135. vb._rebuild();
  95136. }
  95137. this._generateIndexBuffer();
  95138. };
  95139. /**
  95140. * Dispose only the render target textures and post process.
  95141. */
  95142. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95143. this._mainTexture.dispose();
  95144. for (var i = 0; i < this._postProcesses.length; i++) {
  95145. if (this._postProcesses[i]) {
  95146. this._postProcesses[i].dispose();
  95147. }
  95148. }
  95149. this._postProcesses = [];
  95150. for (var i = 0; i < this._textures.length; i++) {
  95151. if (this._textures[i]) {
  95152. this._textures[i].dispose();
  95153. }
  95154. }
  95155. this._textures = [];
  95156. };
  95157. /**
  95158. * Dispose the highlight layer and free resources.
  95159. */
  95160. EffectLayer.prototype.dispose = function () {
  95161. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95162. if (vertexBuffer) {
  95163. vertexBuffer.dispose();
  95164. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95165. }
  95166. if (this._indexBuffer) {
  95167. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95168. this._indexBuffer = null;
  95169. }
  95170. // Clean textures and post processes
  95171. this._disposeTextureAndPostProcesses();
  95172. // Remove from scene
  95173. var index = this._scene.effectLayers.indexOf(this, 0);
  95174. if (index > -1) {
  95175. this._scene.effectLayers.splice(index, 1);
  95176. }
  95177. // Callback
  95178. this.onDisposeObservable.notifyObservers(this);
  95179. this.onDisposeObservable.clear();
  95180. this.onBeforeRenderMainTextureObservable.clear();
  95181. this.onBeforeComposeObservable.clear();
  95182. this.onAfterComposeObservable.clear();
  95183. this.onSizeChangedObservable.clear();
  95184. };
  95185. /**
  95186. * Gets the class name of the effect layer
  95187. * @returns the string with the class name of the effect layer
  95188. */
  95189. EffectLayer.prototype.getClassName = function () {
  95190. return "EffectLayer";
  95191. };
  95192. /**
  95193. * Creates an effect layer from parsed effect layer data
  95194. * @param parsedEffectLayer defines effect layer data
  95195. * @param scene defines the current scene
  95196. * @param rootUrl defines the root URL containing the effect layer information
  95197. * @returns a parsed effect Layer
  95198. */
  95199. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95200. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95201. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95202. };
  95203. __decorate([
  95204. BABYLON.serialize()
  95205. ], EffectLayer.prototype, "name", void 0);
  95206. __decorate([
  95207. BABYLON.serializeAsColor4()
  95208. ], EffectLayer.prototype, "neutralColor", void 0);
  95209. __decorate([
  95210. BABYLON.serialize()
  95211. ], EffectLayer.prototype, "isEnabled", void 0);
  95212. __decorate([
  95213. BABYLON.serializeAsCameraReference()
  95214. ], EffectLayer.prototype, "camera", null);
  95215. return EffectLayer;
  95216. }());
  95217. BABYLON.EffectLayer = EffectLayer;
  95218. })(BABYLON || (BABYLON = {}));
  95219. //# sourceMappingURL=babylon.effectLayer.js.map
  95220. var BABYLON;
  95221. (function (BABYLON) {
  95222. /**
  95223. * Special Glow Blur post process only blurring the alpha channel
  95224. * It enforces keeping the most luminous color in the color channel.
  95225. */
  95226. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95227. __extends(GlowBlurPostProcess, _super);
  95228. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95230. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95231. _this.direction = direction;
  95232. _this.kernel = kernel;
  95233. _this.onApplyObservable.add(function (effect) {
  95234. effect.setFloat2("screenSize", _this.width, _this.height);
  95235. effect.setVector2("direction", _this.direction);
  95236. effect.setFloat("blurWidth", _this.kernel);
  95237. });
  95238. return _this;
  95239. }
  95240. return GlowBlurPostProcess;
  95241. }(BABYLON.PostProcess));
  95242. /**
  95243. * The highlight layer Helps adding a glow effect around a mesh.
  95244. *
  95245. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95246. * glowy meshes to your scene.
  95247. *
  95248. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95249. */
  95250. var HighlightLayer = /** @class */ (function (_super) {
  95251. __extends(HighlightLayer, _super);
  95252. /**
  95253. * Instantiates a new highlight Layer and references it to the scene..
  95254. * @param name The name of the layer
  95255. * @param scene The scene to use the layer in
  95256. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95257. */
  95258. function HighlightLayer(name, scene, options) {
  95259. var _this = _super.call(this, name, scene) || this;
  95260. _this.name = name;
  95261. /**
  95262. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95263. */
  95264. _this.innerGlow = true;
  95265. /**
  95266. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95267. */
  95268. _this.outerGlow = true;
  95269. /**
  95270. * An event triggered when the highlight layer is being blurred.
  95271. */
  95272. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95273. /**
  95274. * An event triggered when the highlight layer has been blurred.
  95275. */
  95276. _this.onAfterBlurObservable = new BABYLON.Observable();
  95277. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95278. _this._meshes = {};
  95279. _this._excludedMeshes = {};
  95280. _this.neutralColor = HighlightLayer.NeutralColor;
  95281. // Warn on stencil
  95282. if (!_this._engine.isStencilEnable) {
  95283. 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 }");
  95284. }
  95285. // Adapt options
  95286. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95287. // Initialize the layer
  95288. _this._init({
  95289. alphaBlendingMode: _this._options.alphaBlendingMode,
  95290. camera: _this._options.camera,
  95291. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95292. mainTextureRatio: _this._options.mainTextureRatio
  95293. });
  95294. // Do not render as long as no meshes have been added
  95295. _this._shouldRender = false;
  95296. return _this;
  95297. }
  95298. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95299. /**
  95300. * Gets the horizontal size of the blur.
  95301. */
  95302. get: function () {
  95303. return this._horizontalBlurPostprocess.kernel;
  95304. },
  95305. /**
  95306. * Specifies the horizontal size of the blur.
  95307. */
  95308. set: function (value) {
  95309. this._horizontalBlurPostprocess.kernel = value;
  95310. },
  95311. enumerable: true,
  95312. configurable: true
  95313. });
  95314. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95315. /**
  95316. * Gets the vertical size of the blur.
  95317. */
  95318. get: function () {
  95319. return this._verticalBlurPostprocess.kernel;
  95320. },
  95321. /**
  95322. * Specifies the vertical size of the blur.
  95323. */
  95324. set: function (value) {
  95325. this._verticalBlurPostprocess.kernel = value;
  95326. },
  95327. enumerable: true,
  95328. configurable: true
  95329. });
  95330. /**
  95331. * Get the effect name of the layer.
  95332. * @return The effect name
  95333. */
  95334. HighlightLayer.prototype.getEffectName = function () {
  95335. return HighlightLayer.EffectName;
  95336. };
  95337. /**
  95338. * Create the merge effect. This is the shader use to blit the information back
  95339. * to the main canvas at the end of the scene rendering.
  95340. */
  95341. HighlightLayer.prototype._createMergeEffect = function () {
  95342. // Effect
  95343. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95344. };
  95345. /**
  95346. * Creates the render target textures and post processes used in the highlight layer.
  95347. */
  95348. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95349. var _this = this;
  95350. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95351. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95352. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95353. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95354. var textureType = 0;
  95355. if (this._engine.getCaps().textureHalfFloatRender) {
  95356. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95357. }
  95358. else {
  95359. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95360. }
  95361. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95362. width: blurTextureWidth,
  95363. height: blurTextureHeight
  95364. }, this._scene, false, true, textureType);
  95365. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95366. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95367. this._blurTexture.anisotropicFilteringLevel = 16;
  95368. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95369. this._blurTexture.renderParticles = false;
  95370. this._blurTexture.ignoreCameraViewport = true;
  95371. this._textures = [this._blurTexture];
  95372. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95373. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95374. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95375. effect.setTexture("textureSampler", _this._mainTexture);
  95376. });
  95377. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95378. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95379. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95380. });
  95381. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95382. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95383. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95384. });
  95385. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95386. }
  95387. else {
  95388. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95389. width: blurTextureWidth,
  95390. height: blurTextureHeight
  95391. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95392. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95393. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95394. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95395. effect.setTexture("textureSampler", _this._mainTexture);
  95396. });
  95397. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95398. width: blurTextureWidth,
  95399. height: blurTextureHeight
  95400. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95401. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95402. }
  95403. this._mainTexture.onAfterUnbindObservable.add(function () {
  95404. _this.onBeforeBlurObservable.notifyObservers(_this);
  95405. var internalTexture = _this._blurTexture.getInternalTexture();
  95406. if (internalTexture) {
  95407. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95408. }
  95409. _this.onAfterBlurObservable.notifyObservers(_this);
  95410. });
  95411. // Prevent autoClear.
  95412. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95413. };
  95414. /**
  95415. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95416. */
  95417. HighlightLayer.prototype.needStencil = function () {
  95418. return true;
  95419. };
  95420. /**
  95421. * Checks for the readiness of the element composing the layer.
  95422. * @param subMesh the mesh to check for
  95423. * @param useInstances specify wether or not to use instances to render the mesh
  95424. * @param emissiveTexture the associated emissive texture used to generate the glow
  95425. * @return true if ready otherwise, false
  95426. */
  95427. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95428. var material = subMesh.getMaterial();
  95429. var mesh = subMesh.getRenderingMesh();
  95430. if (!material || !mesh || !this._meshes) {
  95431. return false;
  95432. }
  95433. var emissiveTexture = null;
  95434. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95435. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95436. emissiveTexture = material.emissiveTexture;
  95437. }
  95438. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95439. };
  95440. /**
  95441. * Implementation specific of rendering the generating effect on the main canvas.
  95442. * @param effect The effect used to render through
  95443. */
  95444. HighlightLayer.prototype._internalRender = function (effect) {
  95445. // Texture
  95446. effect.setTexture("textureSampler", this._blurTexture);
  95447. // Cache
  95448. var engine = this._engine;
  95449. var previousStencilBuffer = engine.getStencilBuffer();
  95450. var previousStencilFunction = engine.getStencilFunction();
  95451. var previousStencilMask = engine.getStencilMask();
  95452. var previousStencilOperationPass = engine.getStencilOperationPass();
  95453. var previousStencilOperationFail = engine.getStencilOperationFail();
  95454. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95455. var previousStencilReference = engine.getStencilFunctionReference();
  95456. // Stencil operations
  95457. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95458. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95459. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95460. // Draw order
  95461. engine.setStencilMask(0x00);
  95462. engine.setStencilBuffer(true);
  95463. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95464. // 2 passes inner outer
  95465. if (this.outerGlow) {
  95466. effect.setFloat("offset", 0);
  95467. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95469. }
  95470. if (this.innerGlow) {
  95471. effect.setFloat("offset", 1);
  95472. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95473. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95474. }
  95475. // Restore Cache
  95476. engine.setStencilFunction(previousStencilFunction);
  95477. engine.setStencilMask(previousStencilMask);
  95478. engine.setStencilBuffer(previousStencilBuffer);
  95479. engine.setStencilOperationPass(previousStencilOperationPass);
  95480. engine.setStencilOperationFail(previousStencilOperationFail);
  95481. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95482. engine.setStencilFunctionReference(previousStencilReference);
  95483. };
  95484. /**
  95485. * Returns true if the layer contains information to display, otherwise false.
  95486. */
  95487. HighlightLayer.prototype.shouldRender = function () {
  95488. if (_super.prototype.shouldRender.call(this)) {
  95489. return this._meshes ? true : false;
  95490. }
  95491. return false;
  95492. };
  95493. /**
  95494. * Returns true if the mesh should render, otherwise false.
  95495. * @param mesh The mesh to render
  95496. * @returns true if it should render otherwise false
  95497. */
  95498. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95499. // Excluded Mesh
  95500. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95501. return false;
  95502. }
  95503. ;
  95504. return true;
  95505. };
  95506. /**
  95507. * Sets the required values for both the emissive texture and and the main color.
  95508. */
  95509. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95510. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95511. if (highlightLayerMesh) {
  95512. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95513. }
  95514. else {
  95515. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95516. }
  95517. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95518. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95519. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95520. }
  95521. else {
  95522. this._emissiveTextureAndColor.texture = null;
  95523. }
  95524. };
  95525. /**
  95526. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95527. * @param mesh The mesh to exclude from the highlight layer
  95528. */
  95529. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95530. if (!this._excludedMeshes) {
  95531. return;
  95532. }
  95533. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95534. if (!meshExcluded) {
  95535. this._excludedMeshes[mesh.uniqueId] = {
  95536. mesh: mesh,
  95537. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95538. mesh.getEngine().setStencilBuffer(false);
  95539. }),
  95540. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95541. mesh.getEngine().setStencilBuffer(true);
  95542. }),
  95543. };
  95544. }
  95545. };
  95546. /**
  95547. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95548. * @param mesh The mesh to highlight
  95549. */
  95550. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95551. if (!this._excludedMeshes) {
  95552. return;
  95553. }
  95554. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95555. if (meshExcluded) {
  95556. if (meshExcluded.beforeRender) {
  95557. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95558. }
  95559. if (meshExcluded.afterRender) {
  95560. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95561. }
  95562. }
  95563. this._excludedMeshes[mesh.uniqueId] = null;
  95564. };
  95565. /**
  95566. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95567. * @param mesh mesh to test
  95568. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95569. */
  95570. HighlightLayer.prototype.hasMesh = function (mesh) {
  95571. if (!this._meshes) {
  95572. return false;
  95573. }
  95574. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95575. };
  95576. /**
  95577. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95578. * @param mesh The mesh to highlight
  95579. * @param color The color of the highlight
  95580. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95581. */
  95582. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95583. var _this = this;
  95584. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  95585. if (!this._meshes) {
  95586. return;
  95587. }
  95588. var meshHighlight = this._meshes[mesh.uniqueId];
  95589. if (meshHighlight) {
  95590. meshHighlight.color = color;
  95591. }
  95592. else {
  95593. this._meshes[mesh.uniqueId] = {
  95594. mesh: mesh,
  95595. color: color,
  95596. // Lambda required for capture due to Observable this context
  95597. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  95598. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  95599. _this._defaultStencilReference(mesh);
  95600. }
  95601. else {
  95602. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  95603. }
  95604. }),
  95605. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  95606. glowEmissiveOnly: glowEmissiveOnly
  95607. };
  95608. }
  95609. this._shouldRender = true;
  95610. };
  95611. /**
  95612. * Remove a mesh from the highlight layer in order to make it stop glowing.
  95613. * @param mesh The mesh to highlight
  95614. */
  95615. HighlightLayer.prototype.removeMesh = function (mesh) {
  95616. if (!this._meshes) {
  95617. return;
  95618. }
  95619. var meshHighlight = this._meshes[mesh.uniqueId];
  95620. if (meshHighlight) {
  95621. if (meshHighlight.observerHighlight) {
  95622. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95623. }
  95624. if (meshHighlight.observerDefault) {
  95625. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95626. }
  95627. delete this._meshes[mesh.uniqueId];
  95628. }
  95629. this._shouldRender = false;
  95630. for (var meshHighlightToCheck in this._meshes) {
  95631. if (this._meshes[meshHighlightToCheck]) {
  95632. this._shouldRender = true;
  95633. break;
  95634. }
  95635. }
  95636. };
  95637. /**
  95638. * Force the stencil to the normal expected value for none glowing parts
  95639. */
  95640. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  95641. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  95642. };
  95643. /**
  95644. * Free any resources and references associated to a mesh.
  95645. * Internal use
  95646. * @param mesh The mesh to free.
  95647. */
  95648. HighlightLayer.prototype._disposeMesh = function (mesh) {
  95649. this.removeMesh(mesh);
  95650. this.removeExcludedMesh(mesh);
  95651. };
  95652. /**
  95653. * Dispose the highlight layer and free resources.
  95654. */
  95655. HighlightLayer.prototype.dispose = function () {
  95656. if (this._meshes) {
  95657. // Clean mesh references
  95658. for (var id in this._meshes) {
  95659. var meshHighlight = this._meshes[id];
  95660. if (meshHighlight && meshHighlight.mesh) {
  95661. if (meshHighlight.observerHighlight) {
  95662. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95663. }
  95664. if (meshHighlight.observerDefault) {
  95665. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95666. }
  95667. }
  95668. }
  95669. this._meshes = null;
  95670. }
  95671. if (this._excludedMeshes) {
  95672. for (var id in this._excludedMeshes) {
  95673. var meshHighlight = this._excludedMeshes[id];
  95674. if (meshHighlight) {
  95675. if (meshHighlight.beforeRender) {
  95676. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  95677. }
  95678. if (meshHighlight.afterRender) {
  95679. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  95680. }
  95681. }
  95682. }
  95683. this._excludedMeshes = null;
  95684. }
  95685. _super.prototype.dispose.call(this);
  95686. };
  95687. /**
  95688. * Gets the class name of the effect layer
  95689. * @returns the string with the class name of the effect layer
  95690. */
  95691. HighlightLayer.prototype.getClassName = function () {
  95692. return "HighlightLayer";
  95693. };
  95694. /**
  95695. * Serializes this Highlight layer
  95696. * @returns a serialized Highlight layer object
  95697. */
  95698. HighlightLayer.prototype.serialize = function () {
  95699. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95700. serializationObject.customType = "BABYLON.HighlightLayer";
  95701. // Highlighted meshes
  95702. serializationObject.meshes = [];
  95703. if (this._meshes) {
  95704. for (var m in this._meshes) {
  95705. var mesh = this._meshes[m];
  95706. if (mesh) {
  95707. serializationObject.meshes.push({
  95708. glowEmissiveOnly: mesh.glowEmissiveOnly,
  95709. color: mesh.color.asArray(),
  95710. meshId: mesh.mesh.id
  95711. });
  95712. }
  95713. }
  95714. }
  95715. // Excluded meshes
  95716. serializationObject.excludedMeshes = [];
  95717. if (this._excludedMeshes) {
  95718. for (var e in this._excludedMeshes) {
  95719. var excludedMesh = this._excludedMeshes[e];
  95720. if (excludedMesh) {
  95721. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  95722. }
  95723. }
  95724. }
  95725. return serializationObject;
  95726. };
  95727. /**
  95728. * Creates a Highlight layer from parsed Highlight layer data
  95729. * @param parsedHightlightLayer defines the Highlight layer data
  95730. * @param scene defines the current scene
  95731. * @param rootUrl defines the root URL containing the Highlight layer information
  95732. * @returns a parsed Highlight layer
  95733. */
  95734. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  95735. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  95736. var index;
  95737. // Excluded meshes
  95738. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  95739. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  95740. if (mesh) {
  95741. hl.addExcludedMesh(mesh);
  95742. }
  95743. }
  95744. // Included meshes
  95745. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  95746. var highlightedMesh = parsedHightlightLayer.meshes[index];
  95747. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  95748. if (mesh) {
  95749. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  95750. }
  95751. }
  95752. return hl;
  95753. };
  95754. /**
  95755. * Effect Name of the highlight layer.
  95756. */
  95757. HighlightLayer.EffectName = "HighlightLayer";
  95758. /**
  95759. * The neutral color used during the preparation of the glow effect.
  95760. * This is black by default as the blend operation is a blend operation.
  95761. */
  95762. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  95763. /**
  95764. * Stencil value used for glowing meshes.
  95765. */
  95766. HighlightLayer.GlowingMeshStencilReference = 0x02;
  95767. /**
  95768. * Stencil value used for the other meshes in the scene.
  95769. */
  95770. HighlightLayer.NormalMeshStencilReference = 0x01;
  95771. __decorate([
  95772. BABYLON.serialize()
  95773. ], HighlightLayer.prototype, "innerGlow", void 0);
  95774. __decorate([
  95775. BABYLON.serialize()
  95776. ], HighlightLayer.prototype, "outerGlow", void 0);
  95777. __decorate([
  95778. BABYLON.serialize()
  95779. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  95780. __decorate([
  95781. BABYLON.serialize()
  95782. ], HighlightLayer.prototype, "blurVerticalSize", null);
  95783. __decorate([
  95784. BABYLON.serialize("options")
  95785. ], HighlightLayer.prototype, "_options", void 0);
  95786. return HighlightLayer;
  95787. }(BABYLON.EffectLayer));
  95788. BABYLON.HighlightLayer = HighlightLayer;
  95789. })(BABYLON || (BABYLON = {}));
  95790. //# sourceMappingURL=babylon.highlightLayer.js.map
  95791. var BABYLON;
  95792. (function (BABYLON) {
  95793. /**
  95794. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  95795. *
  95796. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95797. * glowy meshes to your scene.
  95798. *
  95799. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  95800. */
  95801. var GlowLayer = /** @class */ (function (_super) {
  95802. __extends(GlowLayer, _super);
  95803. /**
  95804. * Instantiates a new glow Layer and references it to the scene.
  95805. * @param name The name of the layer
  95806. * @param scene The scene to use the layer in
  95807. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  95808. */
  95809. function GlowLayer(name, scene, options) {
  95810. var _this = _super.call(this, name, scene) || this;
  95811. _this._intensity = 1.0;
  95812. _this._includedOnlyMeshes = [];
  95813. _this._excludedMeshes = [];
  95814. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  95815. // Adapt options
  95816. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  95817. // Initialize the layer
  95818. _this._init({
  95819. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  95820. camera: _this._options.camera,
  95821. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95822. mainTextureRatio: _this._options.mainTextureRatio
  95823. });
  95824. return _this;
  95825. }
  95826. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  95827. /**
  95828. * Gets the kernel size of the blur.
  95829. */
  95830. get: function () {
  95831. return this._horizontalBlurPostprocess1.kernel;
  95832. },
  95833. /**
  95834. * Sets the kernel size of the blur.
  95835. */
  95836. set: function (value) {
  95837. this._horizontalBlurPostprocess1.kernel = value;
  95838. this._verticalBlurPostprocess1.kernel = value;
  95839. this._horizontalBlurPostprocess2.kernel = value;
  95840. this._verticalBlurPostprocess2.kernel = value;
  95841. },
  95842. enumerable: true,
  95843. configurable: true
  95844. });
  95845. Object.defineProperty(GlowLayer.prototype, "intensity", {
  95846. /**
  95847. * Gets the glow intensity.
  95848. */
  95849. get: function () {
  95850. return this._intensity;
  95851. },
  95852. /**
  95853. * Sets the glow intensity.
  95854. */
  95855. set: function (value) {
  95856. this._intensity = value;
  95857. },
  95858. enumerable: true,
  95859. configurable: true
  95860. });
  95861. /**
  95862. * Get the effect name of the layer.
  95863. * @return The effect name
  95864. */
  95865. GlowLayer.prototype.getEffectName = function () {
  95866. return GlowLayer.EffectName;
  95867. };
  95868. /**
  95869. * Create the merge effect. This is the shader use to blit the information back
  95870. * to the main canvas at the end of the scene rendering.
  95871. */
  95872. GlowLayer.prototype._createMergeEffect = function () {
  95873. // Effect
  95874. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  95875. };
  95876. /**
  95877. * Creates the render target textures and post processes used in the glow layer.
  95878. */
  95879. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  95880. var _this = this;
  95881. var blurTextureWidth = this._mainTextureDesiredSize.width;
  95882. var blurTextureHeight = this._mainTextureDesiredSize.height;
  95883. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95884. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95885. var textureType = 0;
  95886. if (this._engine.getCaps().textureHalfFloatRender) {
  95887. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95888. }
  95889. else {
  95890. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95891. }
  95892. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  95893. width: blurTextureWidth,
  95894. height: blurTextureHeight
  95895. }, this._scene, false, true, textureType);
  95896. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95897. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95898. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95899. this._blurTexture1.renderParticles = false;
  95900. this._blurTexture1.ignoreCameraViewport = true;
  95901. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95902. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95903. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95904. width: blurTextureWidth2,
  95905. height: blurTextureHeight2
  95906. }, this._scene, false, true, textureType);
  95907. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95908. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95909. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95910. this._blurTexture2.renderParticles = false;
  95911. this._blurTexture2.ignoreCameraViewport = true;
  95912. this._textures = [this._blurTexture1, this._blurTexture2];
  95913. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95914. width: blurTextureWidth,
  95915. height: blurTextureHeight
  95916. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95917. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95918. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95919. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95920. effect.setTexture("textureSampler", _this._mainTexture);
  95921. });
  95922. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95923. width: blurTextureWidth,
  95924. height: blurTextureHeight
  95925. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95926. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95927. width: blurTextureWidth2,
  95928. height: blurTextureHeight2
  95929. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95930. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95931. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95932. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95933. effect.setTexture("textureSampler", _this._blurTexture1);
  95934. });
  95935. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95936. width: blurTextureWidth2,
  95937. height: blurTextureHeight2
  95938. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95939. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95940. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95941. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95942. this._mainTexture.samples = this._options.mainTextureSamples;
  95943. this._mainTexture.onAfterUnbindObservable.add(function () {
  95944. var internalTexture = _this._blurTexture1.getInternalTexture();
  95945. if (internalTexture) {
  95946. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95947. internalTexture = _this._blurTexture2.getInternalTexture();
  95948. if (internalTexture) {
  95949. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95950. }
  95951. }
  95952. });
  95953. // Prevent autoClear.
  95954. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95955. };
  95956. /**
  95957. * Checks for the readiness of the element composing the layer.
  95958. * @param subMesh the mesh to check for
  95959. * @param useInstances specify wether or not to use instances to render the mesh
  95960. * @param emissiveTexture the associated emissive texture used to generate the glow
  95961. * @return true if ready otherwise, false
  95962. */
  95963. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95964. var material = subMesh.getMaterial();
  95965. var mesh = subMesh.getRenderingMesh();
  95966. if (!material || !mesh) {
  95967. return false;
  95968. }
  95969. var emissiveTexture = material.emissiveTexture;
  95970. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95971. };
  95972. /**
  95973. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95974. */
  95975. GlowLayer.prototype.needStencil = function () {
  95976. return false;
  95977. };
  95978. /**
  95979. * Implementation specific of rendering the generating effect on the main canvas.
  95980. * @param effect The effect used to render through
  95981. */
  95982. GlowLayer.prototype._internalRender = function (effect) {
  95983. // Texture
  95984. effect.setTexture("textureSampler", this._blurTexture1);
  95985. effect.setTexture("textureSampler2", this._blurTexture2);
  95986. effect.setFloat("offset", this._intensity);
  95987. // Cache
  95988. var engine = this._engine;
  95989. var previousStencilBuffer = engine.getStencilBuffer();
  95990. // Draw order
  95991. engine.setStencilBuffer(false);
  95992. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95993. // Draw order
  95994. engine.setStencilBuffer(previousStencilBuffer);
  95995. };
  95996. /**
  95997. * Sets the required values for both the emissive texture and and the main color.
  95998. */
  95999. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96000. var textureLevel = 1.0;
  96001. if (this.customEmissiveTextureSelector) {
  96002. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96003. }
  96004. else {
  96005. if (material) {
  96006. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96007. if (this._emissiveTextureAndColor.texture) {
  96008. textureLevel = this._emissiveTextureAndColor.texture.level;
  96009. }
  96010. }
  96011. else {
  96012. this._emissiveTextureAndColor.texture = null;
  96013. }
  96014. }
  96015. if (this.customEmissiveColorSelector) {
  96016. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96017. }
  96018. else {
  96019. if (material.emissiveColor) {
  96020. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96021. }
  96022. else {
  96023. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96024. }
  96025. }
  96026. };
  96027. /**
  96028. * Returns true if the mesh should render, otherwise false.
  96029. * @param mesh The mesh to render
  96030. * @returns true if it should render otherwise false
  96031. */
  96032. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96033. return this.hasMesh(mesh);
  96034. };
  96035. /**
  96036. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96037. * @param mesh The mesh to exclude from the glow layer
  96038. */
  96039. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96040. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96041. this._excludedMeshes.push(mesh.uniqueId);
  96042. }
  96043. };
  96044. /**
  96045. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96046. * @param mesh The mesh to remove
  96047. */
  96048. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96049. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96050. if (index !== -1) {
  96051. this._excludedMeshes.splice(index, 1);
  96052. }
  96053. };
  96054. /**
  96055. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96056. * @param mesh The mesh to include in the glow layer
  96057. */
  96058. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96059. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96060. this._includedOnlyMeshes.push(mesh.uniqueId);
  96061. }
  96062. };
  96063. /**
  96064. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96065. * @param mesh The mesh to remove
  96066. */
  96067. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96068. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96069. if (index !== -1) {
  96070. this._includedOnlyMeshes.splice(index, 1);
  96071. }
  96072. };
  96073. /**
  96074. * Determine if a given mesh will be used in the glow layer
  96075. * @param mesh The mesh to test
  96076. * @returns true if the mesh will be highlighted by the current glow layer
  96077. */
  96078. GlowLayer.prototype.hasMesh = function (mesh) {
  96079. // Included Mesh
  96080. if (this._includedOnlyMeshes.length) {
  96081. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96082. }
  96083. ;
  96084. // Excluded Mesh
  96085. if (this._excludedMeshes.length) {
  96086. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96087. }
  96088. ;
  96089. return true;
  96090. };
  96091. /**
  96092. * Free any resources and references associated to a mesh.
  96093. * Internal use
  96094. * @param mesh The mesh to free.
  96095. */
  96096. GlowLayer.prototype._disposeMesh = function (mesh) {
  96097. this.removeIncludedOnlyMesh(mesh);
  96098. this.removeExcludedMesh(mesh);
  96099. };
  96100. /**
  96101. * Gets the class name of the effect layer
  96102. * @returns the string with the class name of the effect layer
  96103. */
  96104. GlowLayer.prototype.getClassName = function () {
  96105. return "GlowLayer";
  96106. };
  96107. /**
  96108. * Serializes this glow layer
  96109. * @returns a serialized glow layer object
  96110. */
  96111. GlowLayer.prototype.serialize = function () {
  96112. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96113. serializationObject.customType = "BABYLON.GlowLayer";
  96114. var index;
  96115. // Included meshes
  96116. serializationObject.includedMeshes = [];
  96117. if (this._includedOnlyMeshes.length) {
  96118. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96119. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96120. if (mesh) {
  96121. serializationObject.includedMeshes.push(mesh.id);
  96122. }
  96123. }
  96124. }
  96125. // Excluded meshes
  96126. serializationObject.excludedMeshes = [];
  96127. if (this._excludedMeshes.length) {
  96128. for (index = 0; index < this._excludedMeshes.length; index++) {
  96129. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96130. if (mesh) {
  96131. serializationObject.excludedMeshes.push(mesh.id);
  96132. }
  96133. }
  96134. }
  96135. return serializationObject;
  96136. };
  96137. /**
  96138. * Creates a Glow Layer from parsed glow layer data
  96139. * @param parsedGlowLayer defines glow layer data
  96140. * @param scene defines the current scene
  96141. * @param rootUrl defines the root URL containing the glow layer information
  96142. * @returns a parsed Glow Layer
  96143. */
  96144. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96145. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96146. var index;
  96147. // Excluded meshes
  96148. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96149. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96150. if (mesh) {
  96151. gl.addExcludedMesh(mesh);
  96152. }
  96153. }
  96154. // Included meshes
  96155. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96156. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96157. if (mesh) {
  96158. gl.addIncludedOnlyMesh(mesh);
  96159. }
  96160. }
  96161. return gl;
  96162. };
  96163. /**
  96164. * Effect Name of the layer.
  96165. */
  96166. GlowLayer.EffectName = "GlowLayer";
  96167. /**
  96168. * The default blur kernel size used for the glow.
  96169. */
  96170. GlowLayer.DefaultBlurKernelSize = 32;
  96171. /**
  96172. * The default texture size ratio used for the glow.
  96173. */
  96174. GlowLayer.DefaultTextureRatio = 0.5;
  96175. __decorate([
  96176. BABYLON.serialize()
  96177. ], GlowLayer.prototype, "blurKernelSize", null);
  96178. __decorate([
  96179. BABYLON.serialize()
  96180. ], GlowLayer.prototype, "intensity", null);
  96181. __decorate([
  96182. BABYLON.serialize("options")
  96183. ], GlowLayer.prototype, "_options", void 0);
  96184. return GlowLayer;
  96185. }(BABYLON.EffectLayer));
  96186. BABYLON.GlowLayer = GlowLayer;
  96187. })(BABYLON || (BABYLON = {}));
  96188. //# sourceMappingURL=babylon.glowLayer.js.map
  96189. var BABYLON;
  96190. (function (BABYLON) {
  96191. /**
  96192. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96193. */
  96194. var AssetTaskState;
  96195. (function (AssetTaskState) {
  96196. /**
  96197. * Initialization
  96198. */
  96199. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96200. /**
  96201. * Running
  96202. */
  96203. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96204. /**
  96205. * Done
  96206. */
  96207. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96208. /**
  96209. * Error
  96210. */
  96211. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96212. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96213. /**
  96214. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96215. */
  96216. var AbstractAssetTask = /** @class */ (function () {
  96217. /**
  96218. * Creates a new {BABYLON.AssetsManager}
  96219. * @param name defines the name of the task
  96220. */
  96221. function AbstractAssetTask(
  96222. /**
  96223. * Task name
  96224. */ name) {
  96225. this.name = name;
  96226. this._isCompleted = false;
  96227. this._taskState = AssetTaskState.INIT;
  96228. }
  96229. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96230. /**
  96231. * Get if the task is completed
  96232. */
  96233. get: function () {
  96234. return this._isCompleted;
  96235. },
  96236. enumerable: true,
  96237. configurable: true
  96238. });
  96239. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96240. /**
  96241. * Gets the current state of the task
  96242. */
  96243. get: function () {
  96244. return this._taskState;
  96245. },
  96246. enumerable: true,
  96247. configurable: true
  96248. });
  96249. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96250. /**
  96251. * Gets the current error object (if task is in error)
  96252. */
  96253. get: function () {
  96254. return this._errorObject;
  96255. },
  96256. enumerable: true,
  96257. configurable: true
  96258. });
  96259. /**
  96260. * Internal only
  96261. * @hidden
  96262. */
  96263. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96264. if (this._errorObject) {
  96265. return;
  96266. }
  96267. this._errorObject = {
  96268. message: message,
  96269. exception: exception
  96270. };
  96271. };
  96272. /**
  96273. * Execute the current task
  96274. * @param scene defines the scene where you want your assets to be loaded
  96275. * @param onSuccess is a callback called when the task is successfully executed
  96276. * @param onError is a callback called if an error occurs
  96277. */
  96278. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96279. var _this = this;
  96280. this._taskState = AssetTaskState.RUNNING;
  96281. this.runTask(scene, function () {
  96282. _this.onDoneCallback(onSuccess, onError);
  96283. }, function (msg, exception) {
  96284. _this.onErrorCallback(onError, msg, exception);
  96285. });
  96286. };
  96287. /**
  96288. * Execute the current task
  96289. * @param scene defines the scene where you want your assets to be loaded
  96290. * @param onSuccess is a callback called when the task is successfully executed
  96291. * @param onError is a callback called if an error occurs
  96292. */
  96293. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96294. throw new Error("runTask is not implemented");
  96295. };
  96296. /**
  96297. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96298. * This can be used with failed tasks that have the reason for failure fixed.
  96299. */
  96300. AbstractAssetTask.prototype.reset = function () {
  96301. this._taskState = AssetTaskState.INIT;
  96302. };
  96303. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96304. this._taskState = AssetTaskState.ERROR;
  96305. this._errorObject = {
  96306. message: message,
  96307. exception: exception
  96308. };
  96309. if (this.onError) {
  96310. this.onError(this, message, exception);
  96311. }
  96312. onError();
  96313. };
  96314. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96315. try {
  96316. this._taskState = AssetTaskState.DONE;
  96317. this._isCompleted = true;
  96318. if (this.onSuccess) {
  96319. this.onSuccess(this);
  96320. }
  96321. onSuccess();
  96322. }
  96323. catch (e) {
  96324. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96325. }
  96326. };
  96327. return AbstractAssetTask;
  96328. }());
  96329. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96330. /**
  96331. * Class used to share progress information about assets loading
  96332. */
  96333. var AssetsProgressEvent = /** @class */ (function () {
  96334. /**
  96335. * Creates a {BABYLON.AssetsProgressEvent}
  96336. * @param remainingCount defines the number of remaining tasks to process
  96337. * @param totalCount defines the total number of tasks
  96338. * @param task defines the task that was just processed
  96339. */
  96340. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96341. this.remainingCount = remainingCount;
  96342. this.totalCount = totalCount;
  96343. this.task = task;
  96344. }
  96345. return AssetsProgressEvent;
  96346. }());
  96347. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96348. /**
  96349. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96350. */
  96351. var MeshAssetTask = /** @class */ (function (_super) {
  96352. __extends(MeshAssetTask, _super);
  96353. /**
  96354. * Creates a new {BABYLON.MeshAssetTask}
  96355. * @param name defines the name of the task
  96356. * @param meshesNames defines the list of mesh's names you want to load
  96357. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96358. * @param sceneFilename defines the filename of the scene to load from
  96359. */
  96360. function MeshAssetTask(
  96361. /**
  96362. * Defines the name of the task
  96363. */
  96364. name,
  96365. /**
  96366. * Defines the list of mesh's names you want to load
  96367. */
  96368. meshesNames,
  96369. /**
  96370. * Defines the root url to use as a base to load your meshes and associated resources
  96371. */
  96372. rootUrl,
  96373. /**
  96374. * Defines the filename of the scene to load from
  96375. */
  96376. sceneFilename) {
  96377. var _this = _super.call(this, name) || this;
  96378. _this.name = name;
  96379. _this.meshesNames = meshesNames;
  96380. _this.rootUrl = rootUrl;
  96381. _this.sceneFilename = sceneFilename;
  96382. return _this;
  96383. }
  96384. /**
  96385. * Execute the current task
  96386. * @param scene defines the scene where you want your assets to be loaded
  96387. * @param onSuccess is a callback called when the task is successfully executed
  96388. * @param onError is a callback called if an error occurs
  96389. */
  96390. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96391. var _this = this;
  96392. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96393. _this.loadedMeshes = meshes;
  96394. _this.loadedParticleSystems = particleSystems;
  96395. _this.loadedSkeletons = skeletons;
  96396. onSuccess();
  96397. }, null, function (scene, message, exception) {
  96398. onError(message, exception);
  96399. });
  96400. };
  96401. return MeshAssetTask;
  96402. }(AbstractAssetTask));
  96403. BABYLON.MeshAssetTask = MeshAssetTask;
  96404. /**
  96405. * Define a task used by {BABYLON.AssetsManager} to load text content
  96406. */
  96407. var TextFileAssetTask = /** @class */ (function (_super) {
  96408. __extends(TextFileAssetTask, _super);
  96409. /**
  96410. * Creates a new TextFileAssetTask object
  96411. * @param name defines the name of the task
  96412. * @param url defines the location of the file to load
  96413. */
  96414. function TextFileAssetTask(
  96415. /**
  96416. * Defines the name of the task
  96417. */
  96418. name,
  96419. /**
  96420. * Defines the location of the file to load
  96421. */
  96422. url) {
  96423. var _this = _super.call(this, name) || this;
  96424. _this.name = name;
  96425. _this.url = url;
  96426. return _this;
  96427. }
  96428. /**
  96429. * Execute the current task
  96430. * @param scene defines the scene where you want your assets to be loaded
  96431. * @param onSuccess is a callback called when the task is successfully executed
  96432. * @param onError is a callback called if an error occurs
  96433. */
  96434. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96435. var _this = this;
  96436. scene._loadFile(this.url, function (data) {
  96437. _this.text = data;
  96438. onSuccess();
  96439. }, undefined, false, false, function (request, exception) {
  96440. if (request) {
  96441. onError(request.status + " " + request.statusText, exception);
  96442. }
  96443. });
  96444. };
  96445. return TextFileAssetTask;
  96446. }(AbstractAssetTask));
  96447. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96448. /**
  96449. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96450. */
  96451. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96452. __extends(BinaryFileAssetTask, _super);
  96453. /**
  96454. * Creates a new BinaryFileAssetTask object
  96455. * @param name defines the name of the new task
  96456. * @param url defines the location of the file to load
  96457. */
  96458. function BinaryFileAssetTask(
  96459. /**
  96460. * Defines the name of the task
  96461. */
  96462. name,
  96463. /**
  96464. * Defines the location of the file to load
  96465. */
  96466. url) {
  96467. var _this = _super.call(this, name) || this;
  96468. _this.name = name;
  96469. _this.url = url;
  96470. return _this;
  96471. }
  96472. /**
  96473. * Execute the current task
  96474. * @param scene defines the scene where you want your assets to be loaded
  96475. * @param onSuccess is a callback called when the task is successfully executed
  96476. * @param onError is a callback called if an error occurs
  96477. */
  96478. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96479. var _this = this;
  96480. scene._loadFile(this.url, function (data) {
  96481. _this.data = data;
  96482. onSuccess();
  96483. }, undefined, true, true, function (request, exception) {
  96484. if (request) {
  96485. onError(request.status + " " + request.statusText, exception);
  96486. }
  96487. });
  96488. };
  96489. return BinaryFileAssetTask;
  96490. }(AbstractAssetTask));
  96491. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96492. /**
  96493. * Define a task used by {BABYLON.AssetsManager} to load images
  96494. */
  96495. var ImageAssetTask = /** @class */ (function (_super) {
  96496. __extends(ImageAssetTask, _super);
  96497. /**
  96498. * Creates a new ImageAssetTask
  96499. * @param name defines the name of the task
  96500. * @param url defines the location of the image to load
  96501. */
  96502. function ImageAssetTask(
  96503. /**
  96504. * Defines the name of the task
  96505. */
  96506. name,
  96507. /**
  96508. * Defines the location of the image to load
  96509. */
  96510. url) {
  96511. var _this = _super.call(this, name) || this;
  96512. _this.name = name;
  96513. _this.url = url;
  96514. return _this;
  96515. }
  96516. /**
  96517. * Execute the current task
  96518. * @param scene defines the scene where you want your assets to be loaded
  96519. * @param onSuccess is a callback called when the task is successfully executed
  96520. * @param onError is a callback called if an error occurs
  96521. */
  96522. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96523. var _this = this;
  96524. var img = new Image();
  96525. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96526. img.onload = function () {
  96527. _this.image = img;
  96528. onSuccess();
  96529. };
  96530. img.onerror = function (err) {
  96531. onError("Error loading image", err);
  96532. };
  96533. img.src = this.url;
  96534. };
  96535. return ImageAssetTask;
  96536. }(AbstractAssetTask));
  96537. BABYLON.ImageAssetTask = ImageAssetTask;
  96538. /**
  96539. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96540. */
  96541. var TextureAssetTask = /** @class */ (function (_super) {
  96542. __extends(TextureAssetTask, _super);
  96543. /**
  96544. * Creates a new TextureAssetTask object
  96545. * @param name defines the name of the task
  96546. * @param url defines the location of the file to load
  96547. * @param noMipmap defines if mipmap should not be generated (default is false)
  96548. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96549. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96550. */
  96551. function TextureAssetTask(
  96552. /**
  96553. * Defines the name of the task
  96554. */
  96555. name,
  96556. /**
  96557. * Defines the location of the file to load
  96558. */
  96559. url,
  96560. /**
  96561. * Defines if mipmap should not be generated (default is false)
  96562. */
  96563. noMipmap,
  96564. /**
  96565. * Defines if texture must be inverted on Y axis (default is false)
  96566. */
  96567. invertY,
  96568. /**
  96569. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96570. */
  96571. samplingMode) {
  96572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96573. var _this = _super.call(this, name) || this;
  96574. _this.name = name;
  96575. _this.url = url;
  96576. _this.noMipmap = noMipmap;
  96577. _this.invertY = invertY;
  96578. _this.samplingMode = samplingMode;
  96579. return _this;
  96580. }
  96581. /**
  96582. * Execute the current task
  96583. * @param scene defines the scene where you want your assets to be loaded
  96584. * @param onSuccess is a callback called when the task is successfully executed
  96585. * @param onError is a callback called if an error occurs
  96586. */
  96587. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96588. var onload = function () {
  96589. onSuccess();
  96590. };
  96591. var onerror = function (message, exception) {
  96592. onError(message, exception);
  96593. };
  96594. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  96595. };
  96596. return TextureAssetTask;
  96597. }(AbstractAssetTask));
  96598. BABYLON.TextureAssetTask = TextureAssetTask;
  96599. /**
  96600. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  96601. */
  96602. var CubeTextureAssetTask = /** @class */ (function (_super) {
  96603. __extends(CubeTextureAssetTask, _super);
  96604. /**
  96605. * Creates a new CubeTextureAssetTask
  96606. * @param name defines the name of the task
  96607. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96608. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96609. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96610. * @param files defines the explicit list of files (undefined by default)
  96611. */
  96612. function CubeTextureAssetTask(
  96613. /**
  96614. * Defines the name of the task
  96615. */
  96616. name,
  96617. /**
  96618. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96619. */
  96620. url,
  96621. /**
  96622. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96623. */
  96624. extensions,
  96625. /**
  96626. * Defines if mipmaps should not be generated (default is false)
  96627. */
  96628. noMipmap,
  96629. /**
  96630. * Defines the explicit list of files (undefined by default)
  96631. */
  96632. files) {
  96633. var _this = _super.call(this, name) || this;
  96634. _this.name = name;
  96635. _this.url = url;
  96636. _this.extensions = extensions;
  96637. _this.noMipmap = noMipmap;
  96638. _this.files = files;
  96639. return _this;
  96640. }
  96641. /**
  96642. * Execute the current task
  96643. * @param scene defines the scene where you want your assets to be loaded
  96644. * @param onSuccess is a callback called when the task is successfully executed
  96645. * @param onError is a callback called if an error occurs
  96646. */
  96647. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96648. var onload = function () {
  96649. onSuccess();
  96650. };
  96651. var onerror = function (message, exception) {
  96652. onError(message, exception);
  96653. };
  96654. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  96655. };
  96656. return CubeTextureAssetTask;
  96657. }(AbstractAssetTask));
  96658. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  96659. /**
  96660. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  96661. */
  96662. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  96663. __extends(HDRCubeTextureAssetTask, _super);
  96664. /**
  96665. * Creates a new HDRCubeTextureAssetTask object
  96666. * @param name defines the name of the task
  96667. * @param url defines the location of the file to load
  96668. * @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.
  96669. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96670. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96671. * @param gammaSpace 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)
  96672. * @param reserved Internal use only
  96673. */
  96674. function HDRCubeTextureAssetTask(
  96675. /**
  96676. * Defines the name of the task
  96677. */
  96678. name,
  96679. /**
  96680. * Defines the location of the file to load
  96681. */
  96682. url,
  96683. /**
  96684. * Defines the desired size (the more it increases the longer the generation will be)
  96685. */
  96686. size,
  96687. /**
  96688. * Defines if mipmaps should not be generated (default is false)
  96689. */
  96690. noMipmap,
  96691. /**
  96692. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96693. */
  96694. generateHarmonics,
  96695. /**
  96696. * 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)
  96697. */
  96698. gammaSpace,
  96699. /**
  96700. * Internal Use Only
  96701. */
  96702. reserved) {
  96703. if (noMipmap === void 0) { noMipmap = false; }
  96704. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96705. if (gammaSpace === void 0) { gammaSpace = false; }
  96706. if (reserved === void 0) { reserved = false; }
  96707. var _this = _super.call(this, name) || this;
  96708. _this.name = name;
  96709. _this.url = url;
  96710. _this.size = size;
  96711. _this.noMipmap = noMipmap;
  96712. _this.generateHarmonics = generateHarmonics;
  96713. _this.gammaSpace = gammaSpace;
  96714. _this.reserved = reserved;
  96715. return _this;
  96716. }
  96717. /**
  96718. * Execute the current task
  96719. * @param scene defines the scene where you want your assets to be loaded
  96720. * @param onSuccess is a callback called when the task is successfully executed
  96721. * @param onError is a callback called if an error occurs
  96722. */
  96723. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96724. var onload = function () {
  96725. onSuccess();
  96726. };
  96727. var onerror = function (message, exception) {
  96728. onError(message, exception);
  96729. };
  96730. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  96731. };
  96732. return HDRCubeTextureAssetTask;
  96733. }(AbstractAssetTask));
  96734. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  96735. /**
  96736. * This class can be used to easily import assets into a scene
  96737. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  96738. */
  96739. var AssetsManager = /** @class */ (function () {
  96740. /**
  96741. * Creates a new AssetsManager
  96742. * @param scene defines the scene to work on
  96743. */
  96744. function AssetsManager(scene) {
  96745. this._isLoading = false;
  96746. this._tasks = new Array();
  96747. this._waitingTasksCount = 0;
  96748. this._totalTasksCount = 0;
  96749. /**
  96750. * Observable called when all tasks are processed
  96751. */
  96752. this.onTaskSuccessObservable = new BABYLON.Observable();
  96753. /**
  96754. * Observable called when a task had an error
  96755. */
  96756. this.onTaskErrorObservable = new BABYLON.Observable();
  96757. /**
  96758. * Observable called when a task is successful
  96759. */
  96760. this.onTasksDoneObservable = new BABYLON.Observable();
  96761. /**
  96762. * Observable called when a task is done (whatever the result is)
  96763. */
  96764. this.onProgressObservable = new BABYLON.Observable();
  96765. /**
  96766. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  96767. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  96768. */
  96769. this.useDefaultLoadingScreen = true;
  96770. this._scene = scene;
  96771. }
  96772. /**
  96773. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  96774. * @param taskName defines the name of the new task
  96775. * @param meshesNames defines the name of meshes to load
  96776. * @param rootUrl defines the root url to use to locate files
  96777. * @param sceneFilename defines the filename of the scene file
  96778. * @returns a new {BABYLON.MeshAssetTask} object
  96779. */
  96780. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  96781. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  96782. this._tasks.push(task);
  96783. return task;
  96784. };
  96785. /**
  96786. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  96787. * @param taskName defines the name of the new task
  96788. * @param url defines the url of the file to load
  96789. * @returns a new {BABYLON.TextFileAssetTask} object
  96790. */
  96791. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  96792. var task = new TextFileAssetTask(taskName, url);
  96793. this._tasks.push(task);
  96794. return task;
  96795. };
  96796. /**
  96797. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  96798. * @param taskName defines the name of the new task
  96799. * @param url defines the url of the file to load
  96800. * @returns a new {BABYLON.BinaryFileAssetTask} object
  96801. */
  96802. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  96803. var task = new BinaryFileAssetTask(taskName, url);
  96804. this._tasks.push(task);
  96805. return task;
  96806. };
  96807. /**
  96808. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  96809. * @param taskName defines the name of the new task
  96810. * @param url defines the url of the file to load
  96811. * @returns a new {BABYLON.ImageAssetTask} object
  96812. */
  96813. AssetsManager.prototype.addImageTask = function (taskName, url) {
  96814. var task = new ImageAssetTask(taskName, url);
  96815. this._tasks.push(task);
  96816. return task;
  96817. };
  96818. /**
  96819. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  96820. * @param taskName defines the name of the new task
  96821. * @param url defines the url of the file to load
  96822. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96823. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  96824. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  96825. * @returns a new {BABYLON.TextureAssetTask} object
  96826. */
  96827. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  96828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96829. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  96830. this._tasks.push(task);
  96831. return task;
  96832. };
  96833. /**
  96834. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  96835. * @param taskName defines the name of the new task
  96836. * @param url defines the url of the file to load
  96837. * @param extensions defines the extension to use to load the cube map (can be null)
  96838. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96839. * @param files defines the list of files to load (can be null)
  96840. * @returns a new {BABYLON.CubeTextureAssetTask} object
  96841. */
  96842. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  96843. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  96844. this._tasks.push(task);
  96845. return task;
  96846. };
  96847. /**
  96848. *
  96849. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  96850. * @param taskName defines the name of the new task
  96851. * @param url defines the url of the file to load
  96852. * @param size defines the size you want for the cubemap (can be null)
  96853. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96854. * @param generateHarmonics defines if you want to automatically generate (true by default)
  96855. * @param gammaSpace 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)
  96856. * @param reserved Internal use only
  96857. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  96858. */
  96859. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  96860. if (noMipmap === void 0) { noMipmap = false; }
  96861. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96862. if (gammaSpace === void 0) { gammaSpace = false; }
  96863. if (reserved === void 0) { reserved = false; }
  96864. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  96865. this._tasks.push(task);
  96866. return task;
  96867. };
  96868. /**
  96869. * Remove a task from the assets manager.
  96870. * @param task the task to remove
  96871. */
  96872. AssetsManager.prototype.removeTask = function (task) {
  96873. var index = this._tasks.indexOf(task);
  96874. if (index > -1) {
  96875. this._tasks.splice(index, 1);
  96876. }
  96877. };
  96878. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  96879. this._waitingTasksCount--;
  96880. try {
  96881. if (this.onProgress) {
  96882. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  96883. }
  96884. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  96885. }
  96886. catch (e) {
  96887. BABYLON.Tools.Error("Error running progress callbacks.");
  96888. console.log(e);
  96889. }
  96890. if (this._waitingTasksCount === 0) {
  96891. try {
  96892. if (this.onFinish) {
  96893. this.onFinish(this._tasks);
  96894. }
  96895. // Let's remove successfull tasks
  96896. var currentTasks = this._tasks.slice();
  96897. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  96898. var task = currentTasks_1[_i];
  96899. if (task.taskState === AssetTaskState.DONE) {
  96900. var index = this._tasks.indexOf(task);
  96901. if (index > -1) {
  96902. this._tasks.splice(index, 1);
  96903. }
  96904. }
  96905. }
  96906. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96907. }
  96908. catch (e) {
  96909. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96910. console.log(e);
  96911. }
  96912. this._isLoading = false;
  96913. this._scene.getEngine().hideLoadingUI();
  96914. }
  96915. };
  96916. AssetsManager.prototype._runTask = function (task) {
  96917. var _this = this;
  96918. var done = function () {
  96919. try {
  96920. if (_this.onTaskSuccess) {
  96921. _this.onTaskSuccess(task);
  96922. }
  96923. _this.onTaskSuccessObservable.notifyObservers(task);
  96924. _this._decreaseWaitingTasksCount(task);
  96925. }
  96926. catch (e) {
  96927. error("Error executing task success callbacks", e);
  96928. }
  96929. };
  96930. var error = function (message, exception) {
  96931. task._setErrorObject(message, exception);
  96932. if (_this.onTaskError) {
  96933. _this.onTaskError(task);
  96934. }
  96935. _this.onTaskErrorObservable.notifyObservers(task);
  96936. _this._decreaseWaitingTasksCount(task);
  96937. };
  96938. task.run(this._scene, done, error);
  96939. };
  96940. /**
  96941. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96942. * @return the current instance of the {BABYLON.AssetsManager}
  96943. */
  96944. AssetsManager.prototype.reset = function () {
  96945. this._isLoading = false;
  96946. this._tasks = new Array();
  96947. return this;
  96948. };
  96949. /**
  96950. * Start the loading process
  96951. * @return the current instance of the {BABYLON.AssetsManager}
  96952. */
  96953. AssetsManager.prototype.load = function () {
  96954. if (this._isLoading) {
  96955. return this;
  96956. }
  96957. this._isLoading = true;
  96958. this._waitingTasksCount = this._tasks.length;
  96959. this._totalTasksCount = this._tasks.length;
  96960. if (this._waitingTasksCount === 0) {
  96961. this._isLoading = false;
  96962. if (this.onFinish) {
  96963. this.onFinish(this._tasks);
  96964. }
  96965. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96966. return this;
  96967. }
  96968. if (this.useDefaultLoadingScreen) {
  96969. this._scene.getEngine().displayLoadingUI();
  96970. }
  96971. for (var index = 0; index < this._tasks.length; index++) {
  96972. var task = this._tasks[index];
  96973. if (task.taskState === AssetTaskState.INIT) {
  96974. this._runTask(task);
  96975. }
  96976. }
  96977. return this;
  96978. };
  96979. return AssetsManager;
  96980. }());
  96981. BABYLON.AssetsManager = AssetsManager;
  96982. })(BABYLON || (BABYLON = {}));
  96983. //# sourceMappingURL=babylon.assetsManager.js.map
  96984. var BABYLON;
  96985. (function (BABYLON) {
  96986. var serializedGeometries = [];
  96987. var serializeGeometry = function (geometry, serializationGeometries) {
  96988. if (serializedGeometries[geometry.id]) {
  96989. return;
  96990. }
  96991. if (geometry.doNotSerialize) {
  96992. return;
  96993. }
  96994. if (geometry instanceof BABYLON.BoxGeometry) {
  96995. serializationGeometries.boxes.push(geometry.serialize());
  96996. }
  96997. else if (geometry instanceof BABYLON.SphereGeometry) {
  96998. serializationGeometries.spheres.push(geometry.serialize());
  96999. }
  97000. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97001. serializationGeometries.cylinders.push(geometry.serialize());
  97002. }
  97003. else if (geometry instanceof BABYLON.TorusGeometry) {
  97004. serializationGeometries.toruses.push(geometry.serialize());
  97005. }
  97006. else if (geometry instanceof BABYLON.GroundGeometry) {
  97007. serializationGeometries.grounds.push(geometry.serialize());
  97008. }
  97009. else if (geometry instanceof BABYLON.Plane) {
  97010. serializationGeometries.planes.push(geometry.serialize());
  97011. }
  97012. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97013. serializationGeometries.torusKnots.push(geometry.serialize());
  97014. }
  97015. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97016. throw new Error("Unknown primitive type");
  97017. }
  97018. else {
  97019. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97020. }
  97021. serializedGeometries[geometry.id] = true;
  97022. };
  97023. var serializeMesh = function (mesh, serializationScene) {
  97024. var serializationObject = {};
  97025. // Geometry
  97026. var geometry = mesh._geometry;
  97027. if (geometry) {
  97028. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97029. // 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
  97030. serializeGeometry(geometry, serializationScene.geometries);
  97031. }
  97032. }
  97033. // Custom
  97034. if (mesh.serialize) {
  97035. mesh.serialize(serializationObject);
  97036. }
  97037. return serializationObject;
  97038. };
  97039. var finalizeSingleMesh = function (mesh, serializationObject) {
  97040. //only works if the mesh is already loaded
  97041. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97042. //serialize material
  97043. if (mesh.material) {
  97044. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97045. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97046. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97047. serializationObject.multiMaterials.push(mesh.material.serialize());
  97048. }
  97049. }
  97050. else {
  97051. serializationObject.materials = serializationObject.materials || [];
  97052. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97053. serializationObject.materials.push(mesh.material.serialize());
  97054. }
  97055. }
  97056. }
  97057. //serialize geometry
  97058. var geometry = mesh._geometry;
  97059. if (geometry) {
  97060. if (!serializationObject.geometries) {
  97061. serializationObject.geometries = {};
  97062. serializationObject.geometries.boxes = [];
  97063. serializationObject.geometries.spheres = [];
  97064. serializationObject.geometries.cylinders = [];
  97065. serializationObject.geometries.toruses = [];
  97066. serializationObject.geometries.grounds = [];
  97067. serializationObject.geometries.planes = [];
  97068. serializationObject.geometries.torusKnots = [];
  97069. serializationObject.geometries.vertexData = [];
  97070. }
  97071. serializeGeometry(geometry, serializationObject.geometries);
  97072. }
  97073. // Skeletons
  97074. if (mesh.skeleton) {
  97075. serializationObject.skeletons = serializationObject.skeletons || [];
  97076. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97077. }
  97078. //serialize the actual mesh
  97079. serializationObject.meshes = serializationObject.meshes || [];
  97080. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97081. }
  97082. };
  97083. var SceneSerializer = /** @class */ (function () {
  97084. function SceneSerializer() {
  97085. }
  97086. SceneSerializer.ClearCache = function () {
  97087. serializedGeometries = [];
  97088. };
  97089. SceneSerializer.Serialize = function (scene) {
  97090. var serializationObject = {};
  97091. SceneSerializer.ClearCache();
  97092. // Scene
  97093. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97094. serializationObject.autoClear = scene.autoClear;
  97095. serializationObject.clearColor = scene.clearColor.asArray();
  97096. serializationObject.ambientColor = scene.ambientColor.asArray();
  97097. serializationObject.gravity = scene.gravity.asArray();
  97098. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97099. serializationObject.workerCollisions = scene.workerCollisions;
  97100. // Fog
  97101. if (scene.fogMode && scene.fogMode !== 0) {
  97102. serializationObject.fogMode = scene.fogMode;
  97103. serializationObject.fogColor = scene.fogColor.asArray();
  97104. serializationObject.fogStart = scene.fogStart;
  97105. serializationObject.fogEnd = scene.fogEnd;
  97106. serializationObject.fogDensity = scene.fogDensity;
  97107. }
  97108. //Physics
  97109. if (scene.isPhysicsEnabled()) {
  97110. var physicEngine = scene.getPhysicsEngine();
  97111. if (physicEngine) {
  97112. serializationObject.physicsEnabled = true;
  97113. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97114. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97115. }
  97116. }
  97117. // Metadata
  97118. if (scene.metadata) {
  97119. serializationObject.metadata = scene.metadata;
  97120. }
  97121. // Morph targets
  97122. serializationObject.morphTargetManagers = [];
  97123. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97124. var abstractMesh = _a[_i];
  97125. var manager = abstractMesh.morphTargetManager;
  97126. if (manager) {
  97127. serializationObject.morphTargetManagers.push(manager.serialize());
  97128. }
  97129. }
  97130. // Lights
  97131. serializationObject.lights = [];
  97132. var index;
  97133. var light;
  97134. for (index = 0; index < scene.lights.length; index++) {
  97135. light = scene.lights[index];
  97136. if (!light.doNotSerialize) {
  97137. serializationObject.lights.push(light.serialize());
  97138. }
  97139. }
  97140. // Cameras
  97141. serializationObject.cameras = [];
  97142. for (index = 0; index < scene.cameras.length; index++) {
  97143. var camera = scene.cameras[index];
  97144. if (!camera.doNotSerialize) {
  97145. serializationObject.cameras.push(camera.serialize());
  97146. }
  97147. }
  97148. if (scene.activeCamera) {
  97149. serializationObject.activeCameraID = scene.activeCamera.id;
  97150. }
  97151. // Animations
  97152. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97153. // Materials
  97154. serializationObject.materials = [];
  97155. serializationObject.multiMaterials = [];
  97156. var material;
  97157. for (index = 0; index < scene.materials.length; index++) {
  97158. material = scene.materials[index];
  97159. if (!material.doNotSerialize) {
  97160. serializationObject.materials.push(material.serialize());
  97161. }
  97162. }
  97163. // MultiMaterials
  97164. serializationObject.multiMaterials = [];
  97165. for (index = 0; index < scene.multiMaterials.length; index++) {
  97166. var multiMaterial = scene.multiMaterials[index];
  97167. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97168. }
  97169. // Environment texture
  97170. if (scene.environmentTexture) {
  97171. serializationObject.environmentTexture = scene.environmentTexture.name;
  97172. }
  97173. // Skeletons
  97174. serializationObject.skeletons = [];
  97175. for (index = 0; index < scene.skeletons.length; index++) {
  97176. var skeleton = scene.skeletons[index];
  97177. if (!skeleton.doNotSerialize) {
  97178. serializationObject.skeletons.push(skeleton.serialize());
  97179. }
  97180. }
  97181. // Transform nodes
  97182. serializationObject.transformNodes = [];
  97183. for (index = 0; index < scene.transformNodes.length; index++) {
  97184. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97185. }
  97186. // Geometries
  97187. serializationObject.geometries = {};
  97188. serializationObject.geometries.boxes = [];
  97189. serializationObject.geometries.spheres = [];
  97190. serializationObject.geometries.cylinders = [];
  97191. serializationObject.geometries.toruses = [];
  97192. serializationObject.geometries.grounds = [];
  97193. serializationObject.geometries.planes = [];
  97194. serializationObject.geometries.torusKnots = [];
  97195. serializationObject.geometries.vertexData = [];
  97196. serializedGeometries = [];
  97197. var geometries = scene.getGeometries();
  97198. for (index = 0; index < geometries.length; index++) {
  97199. var geometry = geometries[index];
  97200. if (geometry.isReady()) {
  97201. serializeGeometry(geometry, serializationObject.geometries);
  97202. }
  97203. }
  97204. // Meshes
  97205. serializationObject.meshes = [];
  97206. for (index = 0; index < scene.meshes.length; index++) {
  97207. var abstractMesh = scene.meshes[index];
  97208. if (abstractMesh instanceof BABYLON.Mesh) {
  97209. var mesh = abstractMesh;
  97210. if (!mesh.doNotSerialize) {
  97211. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97212. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97213. }
  97214. }
  97215. }
  97216. }
  97217. // Particles Systems
  97218. serializationObject.particleSystems = [];
  97219. for (index = 0; index < scene.particleSystems.length; index++) {
  97220. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97221. }
  97222. // Lens flares
  97223. serializationObject.lensFlareSystems = [];
  97224. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97225. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97226. }
  97227. // Shadows
  97228. serializationObject.shadowGenerators = [];
  97229. for (index = 0; index < scene.lights.length; index++) {
  97230. light = scene.lights[index];
  97231. var shadowGenerator = light.getShadowGenerator();
  97232. if (shadowGenerator) {
  97233. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97234. }
  97235. }
  97236. // Action Manager
  97237. if (scene.actionManager) {
  97238. serializationObject.actions = scene.actionManager.serialize("scene");
  97239. }
  97240. // Audio
  97241. serializationObject.sounds = [];
  97242. for (index = 0; index < scene.soundTracks.length; index++) {
  97243. var soundtrack = scene.soundTracks[index];
  97244. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97245. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97246. }
  97247. }
  97248. // Effect layers
  97249. serializationObject.effectLayers = [];
  97250. for (index = 0; index < scene.effectLayers.length; index++) {
  97251. var layer = scene.effectLayers[index];
  97252. if (layer.serialize) {
  97253. serializationObject.effectLayers.push(layer.serialize());
  97254. }
  97255. }
  97256. return serializationObject;
  97257. };
  97258. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97259. if (withParents === void 0) { withParents = false; }
  97260. if (withChildren === void 0) { withChildren = false; }
  97261. var serializationObject = {};
  97262. SceneSerializer.ClearCache();
  97263. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97264. if (withParents || withChildren) {
  97265. //deliberate for loop! not for each, appended should be processed as well.
  97266. for (var i = 0; i < toSerialize.length; ++i) {
  97267. if (withChildren) {
  97268. toSerialize[i].getDescendants().forEach(function (node) {
  97269. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97270. toSerialize.push(node);
  97271. }
  97272. });
  97273. }
  97274. //make sure the array doesn't contain the object already
  97275. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97276. toSerialize.push(toSerialize[i].parent);
  97277. }
  97278. }
  97279. }
  97280. toSerialize.forEach(function (mesh) {
  97281. finalizeSingleMesh(mesh, serializationObject);
  97282. });
  97283. return serializationObject;
  97284. };
  97285. return SceneSerializer;
  97286. }());
  97287. BABYLON.SceneSerializer = SceneSerializer;
  97288. })(BABYLON || (BABYLON = {}));
  97289. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97290. var BABYLON;
  97291. (function (BABYLON) {
  97292. var ReflectionProbe = /** @class */ (function () {
  97293. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97294. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97295. var _this = this;
  97296. this.name = name;
  97297. this._viewMatrix = BABYLON.Matrix.Identity();
  97298. this._target = BABYLON.Vector3.Zero();
  97299. this._add = BABYLON.Vector3.Zero();
  97300. this._invertYAxis = false;
  97301. this.position = BABYLON.Vector3.Zero();
  97302. this._scene = scene;
  97303. this._scene.reflectionProbes.push(this);
  97304. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97305. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97306. switch (faceIndex) {
  97307. case 0:
  97308. _this._add.copyFromFloats(1, 0, 0);
  97309. break;
  97310. case 1:
  97311. _this._add.copyFromFloats(-1, 0, 0);
  97312. break;
  97313. case 2:
  97314. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97315. break;
  97316. case 3:
  97317. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97318. break;
  97319. case 4:
  97320. _this._add.copyFromFloats(0, 0, 1);
  97321. break;
  97322. case 5:
  97323. _this._add.copyFromFloats(0, 0, -1);
  97324. break;
  97325. }
  97326. if (_this._attachedMesh) {
  97327. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97328. }
  97329. _this.position.addToRef(_this._add, _this._target);
  97330. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97331. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97332. scene._forcedViewPosition = _this.position;
  97333. });
  97334. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97335. scene._forcedViewPosition = null;
  97336. scene.updateTransformMatrix(true);
  97337. });
  97338. if (scene.activeCamera) {
  97339. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97340. }
  97341. }
  97342. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97343. get: function () {
  97344. return this._renderTargetTexture.samples;
  97345. },
  97346. set: function (value) {
  97347. this._renderTargetTexture.samples = value;
  97348. },
  97349. enumerable: true,
  97350. configurable: true
  97351. });
  97352. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97353. get: function () {
  97354. return this._renderTargetTexture.refreshRate;
  97355. },
  97356. set: function (value) {
  97357. this._renderTargetTexture.refreshRate = value;
  97358. },
  97359. enumerable: true,
  97360. configurable: true
  97361. });
  97362. ReflectionProbe.prototype.getScene = function () {
  97363. return this._scene;
  97364. };
  97365. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97366. get: function () {
  97367. return this._renderTargetTexture;
  97368. },
  97369. enumerable: true,
  97370. configurable: true
  97371. });
  97372. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97373. get: function () {
  97374. return this._renderTargetTexture.renderList;
  97375. },
  97376. enumerable: true,
  97377. configurable: true
  97378. });
  97379. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97380. this._attachedMesh = mesh;
  97381. };
  97382. /**
  97383. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97384. *
  97385. * @param renderingGroupId The rendering group id corresponding to its index
  97386. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97387. */
  97388. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97389. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97390. };
  97391. ReflectionProbe.prototype.dispose = function () {
  97392. var index = this._scene.reflectionProbes.indexOf(this);
  97393. if (index !== -1) {
  97394. // Remove from the scene if found
  97395. this._scene.reflectionProbes.splice(index, 1);
  97396. }
  97397. if (this._renderTargetTexture) {
  97398. this._renderTargetTexture.dispose();
  97399. this._renderTargetTexture = null;
  97400. }
  97401. };
  97402. return ReflectionProbe;
  97403. }());
  97404. BABYLON.ReflectionProbe = ReflectionProbe;
  97405. })(BABYLON || (BABYLON = {}));
  97406. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97407. var BABYLON;
  97408. (function (BABYLON) {
  97409. var Layer = /** @class */ (function () {
  97410. function Layer(name, imgUrl, scene, isBackground, color) {
  97411. this.name = name;
  97412. this.scale = new BABYLON.Vector2(1, 1);
  97413. this.offset = new BABYLON.Vector2(0, 0);
  97414. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97415. this.layerMask = 0x0FFFFFFF;
  97416. this._vertexBuffers = {};
  97417. // Events
  97418. /**
  97419. * An event triggered when the layer is disposed.
  97420. */
  97421. this.onDisposeObservable = new BABYLON.Observable();
  97422. /**
  97423. * An event triggered before rendering the scene
  97424. */
  97425. this.onBeforeRenderObservable = new BABYLON.Observable();
  97426. /**
  97427. * An event triggered after rendering the scene
  97428. */
  97429. this.onAfterRenderObservable = new BABYLON.Observable();
  97430. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97431. this.isBackground = isBackground === undefined ? true : isBackground;
  97432. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97433. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97434. this._scene.layers.push(this);
  97435. var engine = this._scene.getEngine();
  97436. // VBO
  97437. var vertices = [];
  97438. vertices.push(1, 1);
  97439. vertices.push(-1, 1);
  97440. vertices.push(-1, -1);
  97441. vertices.push(1, -1);
  97442. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97443. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97444. this._createIndexBuffer();
  97445. // Effects
  97446. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97447. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97448. }
  97449. Object.defineProperty(Layer.prototype, "onDispose", {
  97450. set: function (callback) {
  97451. if (this._onDisposeObserver) {
  97452. this.onDisposeObservable.remove(this._onDisposeObserver);
  97453. }
  97454. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97455. },
  97456. enumerable: true,
  97457. configurable: true
  97458. });
  97459. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97460. set: function (callback) {
  97461. if (this._onBeforeRenderObserver) {
  97462. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97463. }
  97464. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97465. },
  97466. enumerable: true,
  97467. configurable: true
  97468. });
  97469. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97470. set: function (callback) {
  97471. if (this._onAfterRenderObserver) {
  97472. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97473. }
  97474. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97475. },
  97476. enumerable: true,
  97477. configurable: true
  97478. });
  97479. Layer.prototype._createIndexBuffer = function () {
  97480. var engine = this._scene.getEngine();
  97481. // Indices
  97482. var indices = [];
  97483. indices.push(0);
  97484. indices.push(1);
  97485. indices.push(2);
  97486. indices.push(0);
  97487. indices.push(2);
  97488. indices.push(3);
  97489. this._indexBuffer = engine.createIndexBuffer(indices);
  97490. };
  97491. Layer.prototype._rebuild = function () {
  97492. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97493. if (vb) {
  97494. vb._rebuild();
  97495. }
  97496. this._createIndexBuffer();
  97497. };
  97498. Layer.prototype.render = function () {
  97499. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97500. // Check
  97501. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97502. return;
  97503. var engine = this._scene.getEngine();
  97504. this.onBeforeRenderObservable.notifyObservers(this);
  97505. // Render
  97506. engine.enableEffect(currentEffect);
  97507. engine.setState(false);
  97508. // Texture
  97509. currentEffect.setTexture("textureSampler", this.texture);
  97510. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97511. // Color
  97512. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97513. // Scale / offset
  97514. currentEffect.setVector2("offset", this.offset);
  97515. currentEffect.setVector2("scale", this.scale);
  97516. // VBOs
  97517. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97518. // Draw order
  97519. if (!this.alphaTest) {
  97520. engine.setAlphaMode(this.alphaBlendingMode);
  97521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97522. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97523. }
  97524. else {
  97525. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97526. }
  97527. this.onAfterRenderObservable.notifyObservers(this);
  97528. };
  97529. Layer.prototype.dispose = function () {
  97530. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97531. if (vertexBuffer) {
  97532. vertexBuffer.dispose();
  97533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97534. }
  97535. if (this._indexBuffer) {
  97536. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97537. this._indexBuffer = null;
  97538. }
  97539. if (this.texture) {
  97540. this.texture.dispose();
  97541. this.texture = null;
  97542. }
  97543. // Remove from scene
  97544. var index = this._scene.layers.indexOf(this);
  97545. this._scene.layers.splice(index, 1);
  97546. // Callback
  97547. this.onDisposeObservable.notifyObservers(this);
  97548. this.onDisposeObservable.clear();
  97549. this.onAfterRenderObservable.clear();
  97550. this.onBeforeRenderObservable.clear();
  97551. };
  97552. return Layer;
  97553. }());
  97554. BABYLON.Layer = Layer;
  97555. })(BABYLON || (BABYLON = {}));
  97556. //# sourceMappingURL=babylon.layer.js.map
  97557. var BABYLON;
  97558. (function (BABYLON) {
  97559. var TextureTools = /** @class */ (function () {
  97560. function TextureTools() {
  97561. }
  97562. /**
  97563. * Uses the GPU to create a copy texture rescaled at a given size
  97564. * @param texture Texture to copy from
  97565. * @param width Desired width
  97566. * @param height Desired height
  97567. * @return Generated texture
  97568. */
  97569. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97570. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97571. var scene = texture.getScene();
  97572. var engine = scene.getEngine();
  97573. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97574. rtt.wrapU = texture.wrapU;
  97575. rtt.wrapV = texture.wrapV;
  97576. rtt.uOffset = texture.uOffset;
  97577. rtt.vOffset = texture.vOffset;
  97578. rtt.uScale = texture.uScale;
  97579. rtt.vScale = texture.vScale;
  97580. rtt.uAng = texture.uAng;
  97581. rtt.vAng = texture.vAng;
  97582. rtt.wAng = texture.wAng;
  97583. rtt.coordinatesIndex = texture.coordinatesIndex;
  97584. rtt.level = texture.level;
  97585. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  97586. rtt._texture.isReady = false;
  97587. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97588. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97589. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97590. passPostProcess.getEffect().executeWhenCompiled(function () {
  97591. passPostProcess.onApply = function (effect) {
  97592. effect.setTexture("textureSampler", texture);
  97593. };
  97594. var internalTexture = rtt.getInternalTexture();
  97595. if (internalTexture) {
  97596. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  97597. engine.unBindFramebuffer(internalTexture);
  97598. rtt.disposeFramebufferObjects();
  97599. passPostProcess.dispose();
  97600. internalTexture.isReady = true;
  97601. }
  97602. });
  97603. return rtt;
  97604. };
  97605. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  97606. if (!scene._environmentBRDFTexture) {
  97607. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97608. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97609. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97610. scene._environmentBRDFTexture = texture;
  97611. }
  97612. return scene._environmentBRDFTexture;
  97613. };
  97614. 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/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOE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skoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  97615. return TextureTools;
  97616. }());
  97617. BABYLON.TextureTools = TextureTools;
  97618. })(BABYLON || (BABYLON = {}));
  97619. //# sourceMappingURL=babylon.textureTools.js.map
  97620. var BABYLON;
  97621. (function (BABYLON) {
  97622. var FramingBehavior = /** @class */ (function () {
  97623. function FramingBehavior() {
  97624. this._mode = FramingBehavior.FitFrustumSidesMode;
  97625. this._radiusScale = 1.0;
  97626. this._positionScale = 0.5;
  97627. this._defaultElevation = 0.3;
  97628. this._elevationReturnTime = 1500;
  97629. this._elevationReturnWaitTime = 1000;
  97630. this._zoomStopsAnimation = false;
  97631. this._framingTime = 1500;
  97632. this._isPointerDown = false;
  97633. this._lastInteractionTime = -Infinity;
  97634. // Framing control
  97635. this._animatables = new Array();
  97636. this._betaIsAnimating = false;
  97637. }
  97638. Object.defineProperty(FramingBehavior.prototype, "name", {
  97639. get: function () {
  97640. return "Framing";
  97641. },
  97642. enumerable: true,
  97643. configurable: true
  97644. });
  97645. Object.defineProperty(FramingBehavior.prototype, "mode", {
  97646. /**
  97647. * Gets current mode used by the behavior.
  97648. */
  97649. get: function () {
  97650. return this._mode;
  97651. },
  97652. /**
  97653. * Sets the current mode used by the behavior
  97654. */
  97655. set: function (mode) {
  97656. this._mode = mode;
  97657. },
  97658. enumerable: true,
  97659. configurable: true
  97660. });
  97661. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  97662. /**
  97663. * Gets the scale applied to the radius
  97664. */
  97665. get: function () {
  97666. return this._radiusScale;
  97667. },
  97668. /**
  97669. * Sets the scale applied to the radius (1 by default)
  97670. */
  97671. set: function (radius) {
  97672. this._radiusScale = radius;
  97673. },
  97674. enumerable: true,
  97675. configurable: true
  97676. });
  97677. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  97678. /**
  97679. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97680. */
  97681. get: function () {
  97682. return this._positionScale;
  97683. },
  97684. /**
  97685. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97686. */
  97687. set: function (scale) {
  97688. this._positionScale = scale;
  97689. },
  97690. enumerable: true,
  97691. configurable: true
  97692. });
  97693. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  97694. /**
  97695. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97696. * behaviour is triggered, in radians.
  97697. */
  97698. get: function () {
  97699. return this._defaultElevation;
  97700. },
  97701. /**
  97702. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97703. * behaviour is triggered, in radians.
  97704. */
  97705. set: function (elevation) {
  97706. this._defaultElevation = elevation;
  97707. },
  97708. enumerable: true,
  97709. configurable: true
  97710. });
  97711. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  97712. /**
  97713. * Gets the time (in milliseconds) taken to return to the default beta position.
  97714. * Negative value indicates camera should not return to default.
  97715. */
  97716. get: function () {
  97717. return this._elevationReturnTime;
  97718. },
  97719. /**
  97720. * Sets the time (in milliseconds) taken to return to the default beta position.
  97721. * Negative value indicates camera should not return to default.
  97722. */
  97723. set: function (speed) {
  97724. this._elevationReturnTime = speed;
  97725. },
  97726. enumerable: true,
  97727. configurable: true
  97728. });
  97729. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  97730. /**
  97731. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97732. */
  97733. get: function () {
  97734. return this._elevationReturnWaitTime;
  97735. },
  97736. /**
  97737. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97738. */
  97739. set: function (time) {
  97740. this._elevationReturnWaitTime = time;
  97741. },
  97742. enumerable: true,
  97743. configurable: true
  97744. });
  97745. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  97746. /**
  97747. * Gets the flag that indicates if user zooming should stop animation.
  97748. */
  97749. get: function () {
  97750. return this._zoomStopsAnimation;
  97751. },
  97752. /**
  97753. * Sets the flag that indicates if user zooming should stop animation.
  97754. */
  97755. set: function (flag) {
  97756. this._zoomStopsAnimation = flag;
  97757. },
  97758. enumerable: true,
  97759. configurable: true
  97760. });
  97761. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  97762. /**
  97763. * Gets the transition time when framing the mesh, in milliseconds
  97764. */
  97765. get: function () {
  97766. return this._framingTime;
  97767. },
  97768. /**
  97769. * Sets the transition time when framing the mesh, in milliseconds
  97770. */
  97771. set: function (time) {
  97772. this._framingTime = time;
  97773. },
  97774. enumerable: true,
  97775. configurable: true
  97776. });
  97777. FramingBehavior.prototype.init = function () {
  97778. // Do notihng
  97779. };
  97780. FramingBehavior.prototype.attach = function (camera) {
  97781. var _this = this;
  97782. this._attachedCamera = camera;
  97783. var scene = this._attachedCamera.getScene();
  97784. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  97785. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97786. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97787. _this._isPointerDown = true;
  97788. return;
  97789. }
  97790. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97791. _this._isPointerDown = false;
  97792. }
  97793. });
  97794. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97795. if (mesh) {
  97796. _this.zoomOnMesh(mesh);
  97797. }
  97798. });
  97799. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97800. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97801. _this._applyUserInteraction();
  97802. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  97803. // back to the default position after a given timeout
  97804. _this._maintainCameraAboveGround();
  97805. });
  97806. };
  97807. FramingBehavior.prototype.detach = function () {
  97808. if (!this._attachedCamera) {
  97809. return;
  97810. }
  97811. var scene = this._attachedCamera.getScene();
  97812. if (this._onPrePointerObservableObserver) {
  97813. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97814. }
  97815. if (this._onAfterCheckInputsObserver) {
  97816. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97817. }
  97818. if (this._onMeshTargetChangedObserver) {
  97819. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97820. }
  97821. this._attachedCamera = null;
  97822. };
  97823. /**
  97824. * Targets the given mesh and updates zoom level accordingly.
  97825. * @param mesh The mesh to target.
  97826. * @param radius Optional. If a cached radius position already exists, overrides default.
  97827. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97828. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97829. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97830. */
  97831. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97832. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97833. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97834. mesh.computeWorldMatrix(true);
  97835. var boundingBox = mesh.getBoundingInfo().boundingBox;
  97836. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  97837. };
  97838. /**
  97839. * Targets the given mesh with its children and updates zoom level accordingly.
  97840. * @param mesh The mesh to target.
  97841. * @param radius Optional. If a cached radius position already exists, overrides default.
  97842. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97843. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97844. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97845. */
  97846. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97847. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97848. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97849. mesh.computeWorldMatrix(true);
  97850. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  97851. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  97852. };
  97853. /**
  97854. * Targets the given meshes with their children and updates zoom level accordingly.
  97855. * @param meshes The mesh to target.
  97856. * @param radius Optional. If a cached radius position already exists, overrides default.
  97857. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97858. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97859. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97860. */
  97861. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  97862. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97863. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97864. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  97865. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  97866. for (var i = 0; i < meshes.length; i++) {
  97867. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  97868. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  97869. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  97870. }
  97871. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  97872. };
  97873. /**
  97874. * Targets the given mesh and updates zoom level accordingly.
  97875. * @param mesh The mesh to target.
  97876. * @param radius Optional. If a cached radius position already exists, overrides default.
  97877. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97878. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97879. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97880. */
  97881. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  97882. var _this = this;
  97883. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97884. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97885. var zoomTarget;
  97886. if (!this._attachedCamera) {
  97887. return;
  97888. }
  97889. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  97890. var bottom = minimumWorld.y;
  97891. var top = maximumWorld.y;
  97892. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  97893. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  97894. if (focusOnOriginXZ) {
  97895. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  97896. }
  97897. else {
  97898. var centerWorld = minimumWorld.add(radiusWorld);
  97899. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  97900. }
  97901. if (!this._vectorTransition) {
  97902. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97903. }
  97904. this._betaIsAnimating = true;
  97905. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97906. if (animatable) {
  97907. this._animatables.push(animatable);
  97908. }
  97909. // sets the radius and lower radius bounds
  97910. // Small delta ensures camera is not always at lower zoom limit.
  97911. var radius = 0;
  97912. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97913. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97914. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97915. radius = position;
  97916. }
  97917. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97918. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97919. if (this._attachedCamera.lowerRadiusLimit === null) {
  97920. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97921. }
  97922. }
  97923. // Set sensibilities
  97924. var extend = maximumWorld.subtract(minimumWorld).length();
  97925. this._attachedCamera.panningSensibility = 5000 / extend;
  97926. this._attachedCamera.wheelPrecision = 100 / radius;
  97927. // transition to new radius
  97928. if (!this._radiusTransition) {
  97929. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97930. }
  97931. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97932. _this.stopAllAnimations();
  97933. if (onAnimationEnd) {
  97934. onAnimationEnd();
  97935. }
  97936. if (_this._attachedCamera) {
  97937. _this._attachedCamera.storeState();
  97938. }
  97939. });
  97940. if (animatable) {
  97941. this._animatables.push(animatable);
  97942. }
  97943. };
  97944. /**
  97945. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97946. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97947. * frustum width.
  97948. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97949. * to fully enclose the mesh in the viewing frustum.
  97950. */
  97951. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97952. var size = maximumWorld.subtract(minimumWorld);
  97953. var boxVectorGlobalDiagonal = size.length();
  97954. var frustumSlope = this._getFrustumSlope();
  97955. // Formula for setting distance
  97956. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97957. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97958. // Horizon distance
  97959. var radius = radiusWithoutFraming * this._radiusScale;
  97960. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97961. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97962. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97963. var camera = this._attachedCamera;
  97964. if (!camera) {
  97965. return 0;
  97966. }
  97967. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97968. // Don't exceed the requested limit
  97969. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97970. }
  97971. // Don't exceed the upper radius limit
  97972. if (camera.upperRadiusLimit) {
  97973. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97974. }
  97975. return distance;
  97976. };
  97977. /**
  97978. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97979. * is automatically returned to its default position (expected to be above ground plane).
  97980. */
  97981. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97982. var _this = this;
  97983. if (this._elevationReturnTime < 0) {
  97984. return;
  97985. }
  97986. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97987. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97988. var limitBeta = Math.PI * 0.5;
  97989. // Bring the camera back up if below the ground plane
  97990. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97991. this._betaIsAnimating = true;
  97992. //Transition to new position
  97993. this.stopAllAnimations();
  97994. if (!this._betaTransition) {
  97995. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97996. }
  97997. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97998. _this._clearAnimationLocks();
  97999. _this.stopAllAnimations();
  98000. });
  98001. if (animatabe) {
  98002. this._animatables.push(animatabe);
  98003. }
  98004. }
  98005. };
  98006. /**
  98007. * Returns the frustum slope based on the canvas ratio and camera FOV
  98008. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98009. */
  98010. FramingBehavior.prototype._getFrustumSlope = function () {
  98011. // Calculate the viewport ratio
  98012. // Aspect Ratio is Height/Width.
  98013. var camera = this._attachedCamera;
  98014. if (!camera) {
  98015. return BABYLON.Vector2.Zero();
  98016. }
  98017. var engine = camera.getScene().getEngine();
  98018. var aspectRatio = engine.getAspectRatio(camera);
  98019. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98020. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98021. var frustumSlopeY = Math.tan(camera.fov / 2);
  98022. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98023. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98024. // along the forward vector.
  98025. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98026. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98027. };
  98028. /**
  98029. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98030. */
  98031. FramingBehavior.prototype._clearAnimationLocks = function () {
  98032. this._betaIsAnimating = false;
  98033. };
  98034. /**
  98035. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98036. */
  98037. FramingBehavior.prototype._applyUserInteraction = function () {
  98038. if (this.isUserIsMoving) {
  98039. this._lastInteractionTime = BABYLON.Tools.Now;
  98040. this.stopAllAnimations();
  98041. this._clearAnimationLocks();
  98042. }
  98043. };
  98044. /**
  98045. * Stops and removes all animations that have been applied to the camera
  98046. */
  98047. FramingBehavior.prototype.stopAllAnimations = function () {
  98048. if (this._attachedCamera) {
  98049. this._attachedCamera.animations = [];
  98050. }
  98051. while (this._animatables.length) {
  98052. if (this._animatables[0]) {
  98053. this._animatables[0].onAnimationEnd = null;
  98054. this._animatables[0].stop();
  98055. }
  98056. this._animatables.shift();
  98057. }
  98058. };
  98059. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98060. /**
  98061. * Gets a value indicating if the user is moving the camera
  98062. */
  98063. get: function () {
  98064. if (!this._attachedCamera) {
  98065. return false;
  98066. }
  98067. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98068. this._attachedCamera.inertialBetaOffset !== 0 ||
  98069. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98070. this._attachedCamera.inertialPanningX !== 0 ||
  98071. this._attachedCamera.inertialPanningY !== 0 ||
  98072. this._isPointerDown;
  98073. },
  98074. enumerable: true,
  98075. configurable: true
  98076. });
  98077. /**
  98078. * The easing function used by animations
  98079. */
  98080. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98081. /**
  98082. * The easing mode used by animations
  98083. */
  98084. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98085. // Statics
  98086. /**
  98087. * The camera can move all the way towards the mesh.
  98088. */
  98089. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98090. /**
  98091. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98092. */
  98093. FramingBehavior.FitFrustumSidesMode = 1;
  98094. return FramingBehavior;
  98095. }());
  98096. BABYLON.FramingBehavior = FramingBehavior;
  98097. })(BABYLON || (BABYLON = {}));
  98098. //# sourceMappingURL=babylon.framingBehavior.js.map
  98099. var BABYLON;
  98100. (function (BABYLON) {
  98101. /**
  98102. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98103. */
  98104. var BouncingBehavior = /** @class */ (function () {
  98105. function BouncingBehavior() {
  98106. /**
  98107. * The duration of the animation, in milliseconds
  98108. */
  98109. this.transitionDuration = 450;
  98110. /**
  98111. * Length of the distance animated by the transition when lower radius is reached
  98112. */
  98113. this.lowerRadiusTransitionRange = 2;
  98114. /**
  98115. * Length of the distance animated by the transition when upper radius is reached
  98116. */
  98117. this.upperRadiusTransitionRange = -2;
  98118. this._autoTransitionRange = false;
  98119. // Animations
  98120. this._radiusIsAnimating = false;
  98121. this._radiusBounceTransition = null;
  98122. this._animatables = new Array();
  98123. }
  98124. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98125. get: function () {
  98126. return "Bouncing";
  98127. },
  98128. enumerable: true,
  98129. configurable: true
  98130. });
  98131. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98132. /**
  98133. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98134. */
  98135. get: function () {
  98136. return this._autoTransitionRange;
  98137. },
  98138. /**
  98139. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98140. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98141. */
  98142. set: function (value) {
  98143. var _this = this;
  98144. if (this._autoTransitionRange === value) {
  98145. return;
  98146. }
  98147. this._autoTransitionRange = value;
  98148. var camera = this._attachedCamera;
  98149. if (!camera) {
  98150. return;
  98151. }
  98152. if (value) {
  98153. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98154. if (!mesh) {
  98155. return;
  98156. }
  98157. mesh.computeWorldMatrix(true);
  98158. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98159. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98160. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98161. });
  98162. }
  98163. else if (this._onMeshTargetChangedObserver) {
  98164. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98165. }
  98166. },
  98167. enumerable: true,
  98168. configurable: true
  98169. });
  98170. BouncingBehavior.prototype.init = function () {
  98171. // Do notihng
  98172. };
  98173. BouncingBehavior.prototype.attach = function (camera) {
  98174. var _this = this;
  98175. this._attachedCamera = camera;
  98176. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98177. if (!_this._attachedCamera) {
  98178. return;
  98179. }
  98180. // Add the bounce animation to the lower radius limit
  98181. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98182. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98183. }
  98184. // Add the bounce animation to the upper radius limit
  98185. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98186. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98187. }
  98188. });
  98189. };
  98190. BouncingBehavior.prototype.detach = function () {
  98191. if (!this._attachedCamera) {
  98192. return;
  98193. }
  98194. if (this._onAfterCheckInputsObserver) {
  98195. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98196. }
  98197. if (this._onMeshTargetChangedObserver) {
  98198. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98199. }
  98200. this._attachedCamera = null;
  98201. };
  98202. /**
  98203. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98204. * @param radiusLimit The limit to check against.
  98205. * @return Bool to indicate if at limit.
  98206. */
  98207. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98208. if (!this._attachedCamera) {
  98209. return false;
  98210. }
  98211. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98212. return true;
  98213. }
  98214. return false;
  98215. };
  98216. /**
  98217. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98218. * @param radiusDelta The delta by which to animate to. Can be negative.
  98219. */
  98220. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98221. var _this = this;
  98222. if (!this._attachedCamera) {
  98223. return;
  98224. }
  98225. if (!this._radiusBounceTransition) {
  98226. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98227. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98228. }
  98229. // Prevent zoom until bounce has completed
  98230. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98231. this._attachedCamera.wheelPrecision = Infinity;
  98232. this._attachedCamera.inertialRadiusOffset = 0;
  98233. // Animate to the radius limit
  98234. this.stopAllAnimations();
  98235. this._radiusIsAnimating = true;
  98236. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98237. if (animatable) {
  98238. this._animatables.push(animatable);
  98239. }
  98240. };
  98241. /**
  98242. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98243. */
  98244. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98245. this._radiusIsAnimating = false;
  98246. if (this._attachedCamera) {
  98247. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98248. }
  98249. };
  98250. /**
  98251. * Stops and removes all animations that have been applied to the camera
  98252. */
  98253. BouncingBehavior.prototype.stopAllAnimations = function () {
  98254. if (this._attachedCamera) {
  98255. this._attachedCamera.animations = [];
  98256. }
  98257. while (this._animatables.length) {
  98258. this._animatables[0].onAnimationEnd = null;
  98259. this._animatables[0].stop();
  98260. this._animatables.shift();
  98261. }
  98262. };
  98263. /**
  98264. * The easing function used by animations
  98265. */
  98266. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98267. /**
  98268. * The easing mode used by animations
  98269. */
  98270. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98271. return BouncingBehavior;
  98272. }());
  98273. BABYLON.BouncingBehavior = BouncingBehavior;
  98274. })(BABYLON || (BABYLON = {}));
  98275. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98276. var BABYLON;
  98277. (function (BABYLON) {
  98278. var AutoRotationBehavior = /** @class */ (function () {
  98279. function AutoRotationBehavior() {
  98280. this._zoomStopsAnimation = false;
  98281. this._idleRotationSpeed = 0.05;
  98282. this._idleRotationWaitTime = 2000;
  98283. this._idleRotationSpinupTime = 2000;
  98284. this._isPointerDown = false;
  98285. this._lastFrameTime = null;
  98286. this._lastInteractionTime = -Infinity;
  98287. this._cameraRotationSpeed = 0;
  98288. this._lastFrameRadius = 0;
  98289. }
  98290. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98291. get: function () {
  98292. return "AutoRotation";
  98293. },
  98294. enumerable: true,
  98295. configurable: true
  98296. });
  98297. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98298. /**
  98299. * Gets the flag that indicates if user zooming should stop animation.
  98300. */
  98301. get: function () {
  98302. return this._zoomStopsAnimation;
  98303. },
  98304. /**
  98305. * Sets the flag that indicates if user zooming should stop animation.
  98306. */
  98307. set: function (flag) {
  98308. this._zoomStopsAnimation = flag;
  98309. },
  98310. enumerable: true,
  98311. configurable: true
  98312. });
  98313. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98314. /**
  98315. * Gets the default speed at which the camera rotates around the model.
  98316. */
  98317. get: function () {
  98318. return this._idleRotationSpeed;
  98319. },
  98320. /**
  98321. * Sets the default speed at which the camera rotates around the model.
  98322. */
  98323. set: function (speed) {
  98324. this._idleRotationSpeed = speed;
  98325. },
  98326. enumerable: true,
  98327. configurable: true
  98328. });
  98329. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98330. /**
  98331. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98332. */
  98333. get: function () {
  98334. return this._idleRotationWaitTime;
  98335. },
  98336. /**
  98337. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98338. */
  98339. set: function (time) {
  98340. this._idleRotationWaitTime = time;
  98341. },
  98342. enumerable: true,
  98343. configurable: true
  98344. });
  98345. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98346. /**
  98347. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98348. */
  98349. get: function () {
  98350. return this._idleRotationSpinupTime;
  98351. },
  98352. /**
  98353. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98354. */
  98355. set: function (time) {
  98356. this._idleRotationSpinupTime = time;
  98357. },
  98358. enumerable: true,
  98359. configurable: true
  98360. });
  98361. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98362. /**
  98363. * Gets a value indicating if the camera is currently rotating because of this behavior
  98364. */
  98365. get: function () {
  98366. return Math.abs(this._cameraRotationSpeed) > 0;
  98367. },
  98368. enumerable: true,
  98369. configurable: true
  98370. });
  98371. AutoRotationBehavior.prototype.init = function () {
  98372. // Do notihng
  98373. };
  98374. AutoRotationBehavior.prototype.attach = function (camera) {
  98375. var _this = this;
  98376. this._attachedCamera = camera;
  98377. var scene = this._attachedCamera.getScene();
  98378. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98379. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98380. _this._isPointerDown = true;
  98381. return;
  98382. }
  98383. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98384. _this._isPointerDown = false;
  98385. }
  98386. });
  98387. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98388. var now = BABYLON.Tools.Now;
  98389. var dt = 0;
  98390. if (_this._lastFrameTime != null) {
  98391. dt = now - _this._lastFrameTime;
  98392. }
  98393. _this._lastFrameTime = now;
  98394. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98395. _this._applyUserInteraction();
  98396. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98397. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98398. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98399. // Step camera rotation by rotation speed
  98400. if (_this._attachedCamera) {
  98401. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98402. }
  98403. });
  98404. };
  98405. AutoRotationBehavior.prototype.detach = function () {
  98406. if (!this._attachedCamera) {
  98407. return;
  98408. }
  98409. var scene = this._attachedCamera.getScene();
  98410. if (this._onPrePointerObservableObserver) {
  98411. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98412. }
  98413. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98414. this._attachedCamera = null;
  98415. };
  98416. /**
  98417. * Returns true if user is scrolling.
  98418. * @return true if user is scrolling.
  98419. */
  98420. AutoRotationBehavior.prototype._userIsZooming = function () {
  98421. if (!this._attachedCamera) {
  98422. return false;
  98423. }
  98424. return this._attachedCamera.inertialRadiusOffset !== 0;
  98425. };
  98426. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98427. if (!this._attachedCamera) {
  98428. return false;
  98429. }
  98430. var zoomHasHitLimit = false;
  98431. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98432. zoomHasHitLimit = true;
  98433. }
  98434. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98435. this._lastFrameRadius = this._attachedCamera.radius;
  98436. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98437. };
  98438. /**
  98439. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98440. */
  98441. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98442. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98443. this._lastInteractionTime = BABYLON.Tools.Now;
  98444. }
  98445. };
  98446. // Tools
  98447. AutoRotationBehavior.prototype._userIsMoving = function () {
  98448. if (!this._attachedCamera) {
  98449. return false;
  98450. }
  98451. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98452. this._attachedCamera.inertialBetaOffset !== 0 ||
  98453. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98454. this._attachedCamera.inertialPanningX !== 0 ||
  98455. this._attachedCamera.inertialPanningY !== 0 ||
  98456. this._isPointerDown;
  98457. };
  98458. return AutoRotationBehavior;
  98459. }());
  98460. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98461. })(BABYLON || (BABYLON = {}));
  98462. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98463. var BABYLON;
  98464. (function (BABYLON) {
  98465. var NullEngineOptions = /** @class */ (function () {
  98466. function NullEngineOptions() {
  98467. this.renderWidth = 512;
  98468. this.renderHeight = 256;
  98469. this.textureSize = 512;
  98470. this.deterministicLockstep = false;
  98471. this.lockstepMaxSteps = 4;
  98472. }
  98473. return NullEngineOptions;
  98474. }());
  98475. BABYLON.NullEngineOptions = NullEngineOptions;
  98476. /**
  98477. * The null engine class provides support for headless version of babylon.js.
  98478. * This can be used in server side scenario or for testing purposes
  98479. */
  98480. var NullEngine = /** @class */ (function (_super) {
  98481. __extends(NullEngine, _super);
  98482. function NullEngine(options) {
  98483. if (options === void 0) { options = new NullEngineOptions(); }
  98484. var _this = _super.call(this, null) || this;
  98485. if (options.deterministicLockstep === undefined) {
  98486. options.deterministicLockstep = false;
  98487. }
  98488. if (options.lockstepMaxSteps === undefined) {
  98489. options.lockstepMaxSteps = 4;
  98490. }
  98491. _this._options = options;
  98492. // Init caps
  98493. // We consider we are on a webgl1 capable device
  98494. _this._caps = new BABYLON.EngineCapabilities();
  98495. _this._caps.maxTexturesImageUnits = 16;
  98496. _this._caps.maxVertexTextureImageUnits = 16;
  98497. _this._caps.maxTextureSize = 512;
  98498. _this._caps.maxCubemapTextureSize = 512;
  98499. _this._caps.maxRenderTextureSize = 512;
  98500. _this._caps.maxVertexAttribs = 16;
  98501. _this._caps.maxVaryingVectors = 16;
  98502. _this._caps.maxFragmentUniformVectors = 16;
  98503. _this._caps.maxVertexUniformVectors = 16;
  98504. // Extensions
  98505. _this._caps.standardDerivatives = false;
  98506. _this._caps.astc = null;
  98507. _this._caps.s3tc = null;
  98508. _this._caps.pvrtc = null;
  98509. _this._caps.etc1 = null;
  98510. _this._caps.etc2 = null;
  98511. _this._caps.textureAnisotropicFilterExtension = null;
  98512. _this._caps.maxAnisotropy = 0;
  98513. _this._caps.uintIndices = false;
  98514. _this._caps.fragmentDepthSupported = false;
  98515. _this._caps.highPrecisionShaderSupported = true;
  98516. _this._caps.colorBufferFloat = false;
  98517. _this._caps.textureFloat = false;
  98518. _this._caps.textureFloatLinearFiltering = false;
  98519. _this._caps.textureFloatRender = false;
  98520. _this._caps.textureHalfFloat = false;
  98521. _this._caps.textureHalfFloatLinearFiltering = false;
  98522. _this._caps.textureHalfFloatRender = false;
  98523. _this._caps.textureLOD = false;
  98524. _this._caps.drawBuffersExtension = false;
  98525. _this._caps.depthTextureExtension = false;
  98526. _this._caps.vertexArrayObject = false;
  98527. _this._caps.instancedArrays = false;
  98528. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98529. // Wrappers
  98530. if (typeof URL === "undefined") {
  98531. URL = {
  98532. createObjectURL: function () { },
  98533. revokeObjectURL: function () { }
  98534. };
  98535. }
  98536. if (typeof Blob === "undefined") {
  98537. Blob = function () { };
  98538. }
  98539. return _this;
  98540. }
  98541. NullEngine.prototype.isDeterministicLockStep = function () {
  98542. return this._options.deterministicLockstep;
  98543. };
  98544. NullEngine.prototype.getLockstepMaxSteps = function () {
  98545. return this._options.lockstepMaxSteps;
  98546. };
  98547. NullEngine.prototype.getHardwareScalingLevel = function () {
  98548. return 1.0;
  98549. };
  98550. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98551. return {
  98552. capacity: 0,
  98553. references: 1,
  98554. is32Bits: false
  98555. };
  98556. };
  98557. NullEngine.prototype.createIndexBuffer = function (indices) {
  98558. return {
  98559. capacity: 0,
  98560. references: 1,
  98561. is32Bits: false
  98562. };
  98563. };
  98564. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98565. if (stencil === void 0) { stencil = false; }
  98566. };
  98567. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98568. if (useScreen === void 0) { useScreen = false; }
  98569. if (!useScreen && this._currentRenderTarget) {
  98570. return this._currentRenderTarget.width;
  98571. }
  98572. return this._options.renderWidth;
  98573. };
  98574. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98575. if (useScreen === void 0) { useScreen = false; }
  98576. if (!useScreen && this._currentRenderTarget) {
  98577. return this._currentRenderTarget.height;
  98578. }
  98579. return this._options.renderHeight;
  98580. };
  98581. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98582. this._cachedViewport = viewport;
  98583. };
  98584. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  98585. return {
  98586. transformFeedback: null,
  98587. __SPECTOR_rebuildProgram: null
  98588. };
  98589. };
  98590. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  98591. return [];
  98592. };
  98593. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  98594. return [];
  98595. };
  98596. NullEngine.prototype.bindSamplers = function (effect) {
  98597. this._currentEffect = null;
  98598. };
  98599. NullEngine.prototype.enableEffect = function (effect) {
  98600. this._currentEffect = effect;
  98601. if (effect.onBind) {
  98602. effect.onBind(effect);
  98603. }
  98604. effect.onBindObservable.notifyObservers(effect);
  98605. };
  98606. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  98607. if (zOffset === void 0) { zOffset = 0; }
  98608. if (reverseSide === void 0) { reverseSide = false; }
  98609. };
  98610. NullEngine.prototype.setIntArray = function (uniform, array) {
  98611. };
  98612. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  98613. };
  98614. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  98615. };
  98616. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  98617. };
  98618. NullEngine.prototype.setFloatArray = function (uniform, array) {
  98619. };
  98620. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  98621. };
  98622. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  98623. };
  98624. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  98625. };
  98626. NullEngine.prototype.setArray = function (uniform, array) {
  98627. };
  98628. NullEngine.prototype.setArray2 = function (uniform, array) {
  98629. };
  98630. NullEngine.prototype.setArray3 = function (uniform, array) {
  98631. };
  98632. NullEngine.prototype.setArray4 = function (uniform, array) {
  98633. };
  98634. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  98635. };
  98636. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  98637. };
  98638. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  98639. };
  98640. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  98641. };
  98642. NullEngine.prototype.setFloat = function (uniform, value) {
  98643. };
  98644. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  98645. };
  98646. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  98647. };
  98648. NullEngine.prototype.setBool = function (uniform, bool) {
  98649. };
  98650. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  98651. };
  98652. NullEngine.prototype.setColor3 = function (uniform, color3) {
  98653. };
  98654. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  98655. };
  98656. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  98657. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  98658. if (this._alphaMode === mode) {
  98659. return;
  98660. }
  98661. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  98662. if (!noDepthWriteChange) {
  98663. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  98664. }
  98665. this._alphaMode = mode;
  98666. };
  98667. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  98668. };
  98669. NullEngine.prototype.wipeCaches = function (bruteForce) {
  98670. if (this.preventCacheWipeBetweenFrames) {
  98671. return;
  98672. }
  98673. this.resetTextureCache();
  98674. this._currentEffect = null;
  98675. if (bruteForce) {
  98676. this._currentProgram = null;
  98677. this._stencilState.reset();
  98678. this._depthCullingState.reset();
  98679. this._alphaState.reset();
  98680. }
  98681. this._cachedVertexBuffers = null;
  98682. this._cachedIndexBuffer = null;
  98683. this._cachedEffectForVertexBuffers = null;
  98684. };
  98685. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  98686. };
  98687. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  98688. };
  98689. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  98690. };
  98691. NullEngine.prototype._createTexture = function () {
  98692. return {};
  98693. };
  98694. NullEngine.prototype._releaseTexture = function (texture) {
  98695. };
  98696. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  98697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98698. if (onLoad === void 0) { onLoad = null; }
  98699. if (onError === void 0) { onError = null; }
  98700. if (buffer === void 0) { buffer = null; }
  98701. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  98702. var url = String(urlArg);
  98703. texture.url = url;
  98704. texture.generateMipMaps = !noMipmap;
  98705. texture.samplingMode = samplingMode;
  98706. texture.invertY = invertY;
  98707. texture.baseWidth = this._options.textureSize;
  98708. texture.baseHeight = this._options.textureSize;
  98709. texture.width = this._options.textureSize;
  98710. texture.height = this._options.textureSize;
  98711. if (format) {
  98712. texture.format = format;
  98713. }
  98714. texture.isReady = true;
  98715. if (onLoad) {
  98716. onLoad();
  98717. }
  98718. this._internalTexturesCache.push(texture);
  98719. return texture;
  98720. };
  98721. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  98722. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  98723. if (options !== undefined && typeof options === "object") {
  98724. fullOptions.generateMipMaps = options.generateMipMaps;
  98725. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  98726. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  98727. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  98728. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  98729. }
  98730. else {
  98731. fullOptions.generateMipMaps = options;
  98732. fullOptions.generateDepthBuffer = true;
  98733. fullOptions.generateStencilBuffer = false;
  98734. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98735. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98736. }
  98737. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  98738. var width = size.width || size;
  98739. var height = size.height || size;
  98740. texture._depthStencilBuffer = {};
  98741. texture._framebuffer = {};
  98742. texture.baseWidth = width;
  98743. texture.baseHeight = height;
  98744. texture.width = width;
  98745. texture.height = height;
  98746. texture.isReady = true;
  98747. texture.samples = 1;
  98748. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  98749. texture.samplingMode = fullOptions.samplingMode;
  98750. texture.type = fullOptions.type;
  98751. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  98752. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  98753. this._internalTexturesCache.push(texture);
  98754. return texture;
  98755. };
  98756. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  98757. texture.samplingMode = samplingMode;
  98758. };
  98759. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  98760. if (this._currentRenderTarget) {
  98761. this.unBindFramebuffer(this._currentRenderTarget);
  98762. }
  98763. this._currentRenderTarget = texture;
  98764. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  98765. if (this._cachedViewport && !forceFullscreenViewport) {
  98766. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  98767. }
  98768. };
  98769. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  98770. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  98771. this._currentRenderTarget = null;
  98772. if (onBeforeUnbind) {
  98773. if (texture._MSAAFramebuffer) {
  98774. this._currentFramebuffer = texture._framebuffer;
  98775. }
  98776. onBeforeUnbind();
  98777. }
  98778. this._currentFramebuffer = null;
  98779. };
  98780. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  98781. var vbo = {
  98782. capacity: 1,
  98783. references: 1,
  98784. is32Bits: false
  98785. };
  98786. return vbo;
  98787. };
  98788. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  98789. if (offset === void 0) { offset = 0; }
  98790. };
  98791. /**
  98792. * Updates a dynamic vertex buffer.
  98793. * @param vertexBuffer the vertex buffer to update
  98794. * @param data the data used to update the vertex buffer
  98795. * @param byteOffset the byte offset of the data (optional)
  98796. * @param byteLength the byte length of the data (optional)
  98797. */
  98798. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  98799. };
  98800. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  98801. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  98802. this._boundTexturesCache[this._activeChannel] = texture;
  98803. return true;
  98804. }
  98805. return false;
  98806. };
  98807. NullEngine.prototype._bindTexture = function (channel, texture) {
  98808. if (channel < 0) {
  98809. return;
  98810. }
  98811. this._bindTextureDirectly(0, texture);
  98812. };
  98813. NullEngine.prototype._releaseBuffer = function (buffer) {
  98814. buffer.references--;
  98815. if (buffer.references === 0) {
  98816. return true;
  98817. }
  98818. return false;
  98819. };
  98820. NullEngine.prototype.releaseEffects = function () {
  98821. };
  98822. return NullEngine;
  98823. }(BABYLON.Engine));
  98824. BABYLON.NullEngine = NullEngine;
  98825. })(BABYLON || (BABYLON = {}));
  98826. //# sourceMappingURL=babylon.nullEngine.js.map
  98827. var BABYLON;
  98828. (function (BABYLON) {
  98829. /**
  98830. * This class can be used to get instrumentation data from a Babylon engine
  98831. */
  98832. var EngineInstrumentation = /** @class */ (function () {
  98833. function EngineInstrumentation(engine) {
  98834. this.engine = engine;
  98835. this._captureGPUFrameTime = false;
  98836. this._gpuFrameTime = new BABYLON.PerfCounter();
  98837. this._captureShaderCompilationTime = false;
  98838. this._shaderCompilationTime = new BABYLON.PerfCounter();
  98839. // Observers
  98840. this._onBeginFrameObserver = null;
  98841. this._onEndFrameObserver = null;
  98842. this._onBeforeShaderCompilationObserver = null;
  98843. this._onAfterShaderCompilationObserver = null;
  98844. }
  98845. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  98846. // Properties
  98847. /**
  98848. * Gets the perf counter used for GPU frame time
  98849. */
  98850. get: function () {
  98851. return this._gpuFrameTime;
  98852. },
  98853. enumerable: true,
  98854. configurable: true
  98855. });
  98856. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  98857. /**
  98858. * Gets the GPU frame time capture status
  98859. */
  98860. get: function () {
  98861. return this._captureGPUFrameTime;
  98862. },
  98863. /**
  98864. * Enable or disable the GPU frame time capture
  98865. */
  98866. set: function (value) {
  98867. var _this = this;
  98868. if (value === this._captureGPUFrameTime) {
  98869. return;
  98870. }
  98871. this._captureGPUFrameTime = value;
  98872. if (value) {
  98873. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  98874. if (!_this._gpuFrameTimeToken) {
  98875. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  98876. }
  98877. });
  98878. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  98879. if (!_this._gpuFrameTimeToken) {
  98880. return;
  98881. }
  98882. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  98883. if (time > -1) {
  98884. _this._gpuFrameTimeToken = null;
  98885. _this._gpuFrameTime.fetchNewFrame();
  98886. _this._gpuFrameTime.addCount(time, true);
  98887. }
  98888. });
  98889. }
  98890. else {
  98891. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98892. this._onBeginFrameObserver = null;
  98893. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98894. this._onEndFrameObserver = null;
  98895. }
  98896. },
  98897. enumerable: true,
  98898. configurable: true
  98899. });
  98900. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  98901. /**
  98902. * Gets the perf counter used for shader compilation time
  98903. */
  98904. get: function () {
  98905. return this._shaderCompilationTime;
  98906. },
  98907. enumerable: true,
  98908. configurable: true
  98909. });
  98910. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98911. /**
  98912. * Gets the shader compilation time capture status
  98913. */
  98914. get: function () {
  98915. return this._captureShaderCompilationTime;
  98916. },
  98917. /**
  98918. * Enable or disable the shader compilation time capture
  98919. */
  98920. set: function (value) {
  98921. var _this = this;
  98922. if (value === this._captureShaderCompilationTime) {
  98923. return;
  98924. }
  98925. this._captureShaderCompilationTime = value;
  98926. if (value) {
  98927. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98928. _this._shaderCompilationTime.fetchNewFrame();
  98929. _this._shaderCompilationTime.beginMonitoring();
  98930. });
  98931. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98932. _this._shaderCompilationTime.endMonitoring();
  98933. });
  98934. }
  98935. else {
  98936. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98937. this._onBeforeShaderCompilationObserver = null;
  98938. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98939. this._onAfterShaderCompilationObserver = null;
  98940. }
  98941. },
  98942. enumerable: true,
  98943. configurable: true
  98944. });
  98945. EngineInstrumentation.prototype.dispose = function () {
  98946. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98947. this._onBeginFrameObserver = null;
  98948. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98949. this._onEndFrameObserver = null;
  98950. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98951. this._onBeforeShaderCompilationObserver = null;
  98952. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98953. this._onAfterShaderCompilationObserver = null;
  98954. this.engine = null;
  98955. };
  98956. return EngineInstrumentation;
  98957. }());
  98958. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98959. })(BABYLON || (BABYLON = {}));
  98960. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98961. var BABYLON;
  98962. (function (BABYLON) {
  98963. /**
  98964. * This class can be used to get instrumentation data from a Babylon engine
  98965. */
  98966. var SceneInstrumentation = /** @class */ (function () {
  98967. function SceneInstrumentation(scene) {
  98968. var _this = this;
  98969. this.scene = scene;
  98970. this._captureActiveMeshesEvaluationTime = false;
  98971. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98972. this._captureRenderTargetsRenderTime = false;
  98973. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98974. this._captureFrameTime = false;
  98975. this._frameTime = new BABYLON.PerfCounter();
  98976. this._captureRenderTime = false;
  98977. this._renderTime = new BABYLON.PerfCounter();
  98978. this._captureInterFrameTime = false;
  98979. this._interFrameTime = new BABYLON.PerfCounter();
  98980. this._captureParticlesRenderTime = false;
  98981. this._particlesRenderTime = new BABYLON.PerfCounter();
  98982. this._captureSpritesRenderTime = false;
  98983. this._spritesRenderTime = new BABYLON.PerfCounter();
  98984. this._capturePhysicsTime = false;
  98985. this._physicsTime = new BABYLON.PerfCounter();
  98986. this._captureAnimationsTime = false;
  98987. this._animationsTime = new BABYLON.PerfCounter();
  98988. this._captureCameraRenderTime = false;
  98989. this._cameraRenderTime = new BABYLON.PerfCounter();
  98990. // Observers
  98991. this._onBeforeActiveMeshesEvaluationObserver = null;
  98992. this._onAfterActiveMeshesEvaluationObserver = null;
  98993. this._onBeforeRenderTargetsRenderObserver = null;
  98994. this._onAfterRenderTargetsRenderObserver = null;
  98995. this._onAfterRenderObserver = null;
  98996. this._onBeforeDrawPhaseObserver = null;
  98997. this._onAfterDrawPhaseObserver = null;
  98998. this._onBeforeAnimationsObserver = null;
  98999. this._onBeforeParticlesRenderingObserver = null;
  99000. this._onAfterParticlesRenderingObserver = null;
  99001. this._onBeforeSpritesRenderingObserver = null;
  99002. this._onAfterSpritesRenderingObserver = null;
  99003. this._onBeforePhysicsObserver = null;
  99004. this._onAfterPhysicsObserver = null;
  99005. this._onAfterAnimationsObserver = null;
  99006. this._onBeforeCameraRenderObserver = null;
  99007. this._onAfterCameraRenderObserver = null;
  99008. // Before render
  99009. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99010. if (_this._captureActiveMeshesEvaluationTime) {
  99011. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99012. }
  99013. if (_this._captureRenderTargetsRenderTime) {
  99014. _this._renderTargetsRenderTime.fetchNewFrame();
  99015. }
  99016. if (_this._captureFrameTime) {
  99017. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99018. _this._frameTime.beginMonitoring();
  99019. }
  99020. if (_this._captureInterFrameTime) {
  99021. _this._interFrameTime.endMonitoring();
  99022. }
  99023. if (_this._captureParticlesRenderTime) {
  99024. _this._particlesRenderTime.fetchNewFrame();
  99025. }
  99026. if (_this._captureSpritesRenderTime) {
  99027. _this._spritesRenderTime.fetchNewFrame();
  99028. }
  99029. if (_this._captureAnimationsTime) {
  99030. _this._animationsTime.beginMonitoring();
  99031. }
  99032. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99033. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99034. });
  99035. // After render
  99036. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99037. if (_this._captureFrameTime) {
  99038. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99039. _this._frameTime.endMonitoring();
  99040. }
  99041. if (_this._captureRenderTime) {
  99042. _this._renderTime.endMonitoring(false);
  99043. }
  99044. if (_this._captureInterFrameTime) {
  99045. _this._interFrameTime.beginMonitoring();
  99046. }
  99047. });
  99048. }
  99049. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99050. // Properties
  99051. /**
  99052. * Gets the perf counter used for active meshes evaluation time
  99053. */
  99054. get: function () {
  99055. return this._activeMeshesEvaluationTime;
  99056. },
  99057. enumerable: true,
  99058. configurable: true
  99059. });
  99060. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99061. /**
  99062. * Gets the active meshes evaluation time capture status
  99063. */
  99064. get: function () {
  99065. return this._captureActiveMeshesEvaluationTime;
  99066. },
  99067. /**
  99068. * Enable or disable the active meshes evaluation time capture
  99069. */
  99070. set: function (value) {
  99071. var _this = this;
  99072. if (value === this._captureActiveMeshesEvaluationTime) {
  99073. return;
  99074. }
  99075. this._captureActiveMeshesEvaluationTime = value;
  99076. if (value) {
  99077. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99078. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99079. _this._activeMeshesEvaluationTime.beginMonitoring();
  99080. });
  99081. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99082. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99083. _this._activeMeshesEvaluationTime.endMonitoring();
  99084. });
  99085. }
  99086. else {
  99087. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99088. this._onBeforeActiveMeshesEvaluationObserver = null;
  99089. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99090. this._onAfterActiveMeshesEvaluationObserver = null;
  99091. }
  99092. },
  99093. enumerable: true,
  99094. configurable: true
  99095. });
  99096. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99097. /**
  99098. * Gets the perf counter used for render targets render time
  99099. */
  99100. get: function () {
  99101. return this._renderTargetsRenderTime;
  99102. },
  99103. enumerable: true,
  99104. configurable: true
  99105. });
  99106. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99107. /**
  99108. * Gets the render targets render time capture status
  99109. */
  99110. get: function () {
  99111. return this._captureRenderTargetsRenderTime;
  99112. },
  99113. /**
  99114. * Enable or disable the render targets render time capture
  99115. */
  99116. set: function (value) {
  99117. var _this = this;
  99118. if (value === this._captureRenderTargetsRenderTime) {
  99119. return;
  99120. }
  99121. this._captureRenderTargetsRenderTime = value;
  99122. if (value) {
  99123. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99124. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99125. _this._renderTargetsRenderTime.beginMonitoring();
  99126. });
  99127. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99128. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99129. _this._renderTargetsRenderTime.endMonitoring(false);
  99130. });
  99131. }
  99132. else {
  99133. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99134. this._onBeforeRenderTargetsRenderObserver = null;
  99135. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99136. this._onAfterRenderTargetsRenderObserver = null;
  99137. }
  99138. },
  99139. enumerable: true,
  99140. configurable: true
  99141. });
  99142. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99143. /**
  99144. * Gets the perf counter used for particles render time
  99145. */
  99146. get: function () {
  99147. return this._particlesRenderTime;
  99148. },
  99149. enumerable: true,
  99150. configurable: true
  99151. });
  99152. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99153. /**
  99154. * Gets the particles render time capture status
  99155. */
  99156. get: function () {
  99157. return this._captureParticlesRenderTime;
  99158. },
  99159. /**
  99160. * Enable or disable the particles render time capture
  99161. */
  99162. set: function (value) {
  99163. var _this = this;
  99164. if (value === this._captureParticlesRenderTime) {
  99165. return;
  99166. }
  99167. this._captureParticlesRenderTime = value;
  99168. if (value) {
  99169. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99170. BABYLON.Tools.StartPerformanceCounter("Particles");
  99171. _this._particlesRenderTime.beginMonitoring();
  99172. });
  99173. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99174. BABYLON.Tools.EndPerformanceCounter("Particles");
  99175. _this._particlesRenderTime.endMonitoring(false);
  99176. });
  99177. }
  99178. else {
  99179. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99180. this._onBeforeParticlesRenderingObserver = null;
  99181. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99182. this._onAfterParticlesRenderingObserver = null;
  99183. }
  99184. },
  99185. enumerable: true,
  99186. configurable: true
  99187. });
  99188. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99189. /**
  99190. * Gets the perf counter used for sprites render time
  99191. */
  99192. get: function () {
  99193. return this._spritesRenderTime;
  99194. },
  99195. enumerable: true,
  99196. configurable: true
  99197. });
  99198. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99199. /**
  99200. * Gets the sprites render time capture status
  99201. */
  99202. get: function () {
  99203. return this._captureSpritesRenderTime;
  99204. },
  99205. /**
  99206. * Enable or disable the sprites render time capture
  99207. */
  99208. set: function (value) {
  99209. var _this = this;
  99210. if (value === this._captureSpritesRenderTime) {
  99211. return;
  99212. }
  99213. this._captureSpritesRenderTime = value;
  99214. if (value) {
  99215. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99216. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99217. _this._spritesRenderTime.beginMonitoring();
  99218. });
  99219. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99220. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99221. _this._spritesRenderTime.endMonitoring(false);
  99222. });
  99223. }
  99224. else {
  99225. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99226. this._onBeforeSpritesRenderingObserver = null;
  99227. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99228. this._onAfterSpritesRenderingObserver = null;
  99229. }
  99230. },
  99231. enumerable: true,
  99232. configurable: true
  99233. });
  99234. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99235. /**
  99236. * Gets the perf counter used for physics time
  99237. */
  99238. get: function () {
  99239. return this._physicsTime;
  99240. },
  99241. enumerable: true,
  99242. configurable: true
  99243. });
  99244. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99245. /**
  99246. * Gets the physics time capture status
  99247. */
  99248. get: function () {
  99249. return this._capturePhysicsTime;
  99250. },
  99251. /**
  99252. * Enable or disable the physics time capture
  99253. */
  99254. set: function (value) {
  99255. var _this = this;
  99256. if (value === this._capturePhysicsTime) {
  99257. return;
  99258. }
  99259. this._capturePhysicsTime = value;
  99260. if (value) {
  99261. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99262. BABYLON.Tools.StartPerformanceCounter("Physics");
  99263. _this._physicsTime.beginMonitoring();
  99264. });
  99265. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99266. BABYLON.Tools.EndPerformanceCounter("Physics");
  99267. _this._physicsTime.endMonitoring();
  99268. });
  99269. }
  99270. else {
  99271. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99272. this._onBeforePhysicsObserver = null;
  99273. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99274. this._onAfterPhysicsObserver = null;
  99275. }
  99276. },
  99277. enumerable: true,
  99278. configurable: true
  99279. });
  99280. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99281. /**
  99282. * Gets the perf counter used for animations time
  99283. */
  99284. get: function () {
  99285. return this._animationsTime;
  99286. },
  99287. enumerable: true,
  99288. configurable: true
  99289. });
  99290. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99291. /**
  99292. * Gets the animations time capture status
  99293. */
  99294. get: function () {
  99295. return this._captureAnimationsTime;
  99296. },
  99297. /**
  99298. * Enable or disable the animations time capture
  99299. */
  99300. set: function (value) {
  99301. var _this = this;
  99302. if (value === this._captureAnimationsTime) {
  99303. return;
  99304. }
  99305. this._captureAnimationsTime = value;
  99306. if (value) {
  99307. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99308. _this._animationsTime.endMonitoring();
  99309. });
  99310. }
  99311. else {
  99312. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99313. this._onAfterAnimationsObserver = null;
  99314. }
  99315. },
  99316. enumerable: true,
  99317. configurable: true
  99318. });
  99319. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99320. /**
  99321. * Gets the perf counter used for frame time capture
  99322. */
  99323. get: function () {
  99324. return this._frameTime;
  99325. },
  99326. enumerable: true,
  99327. configurable: true
  99328. });
  99329. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99330. /**
  99331. * Gets the frame time capture status
  99332. */
  99333. get: function () {
  99334. return this._captureFrameTime;
  99335. },
  99336. /**
  99337. * Enable or disable the frame time capture
  99338. */
  99339. set: function (value) {
  99340. this._captureFrameTime = value;
  99341. },
  99342. enumerable: true,
  99343. configurable: true
  99344. });
  99345. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99346. /**
  99347. * Gets the perf counter used for inter-frames time capture
  99348. */
  99349. get: function () {
  99350. return this._interFrameTime;
  99351. },
  99352. enumerable: true,
  99353. configurable: true
  99354. });
  99355. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99356. /**
  99357. * Gets the inter-frames time capture status
  99358. */
  99359. get: function () {
  99360. return this._captureInterFrameTime;
  99361. },
  99362. /**
  99363. * Enable or disable the inter-frames time capture
  99364. */
  99365. set: function (value) {
  99366. this._captureInterFrameTime = value;
  99367. },
  99368. enumerable: true,
  99369. configurable: true
  99370. });
  99371. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99372. /**
  99373. * Gets the perf counter used for render time capture
  99374. */
  99375. get: function () {
  99376. return this._renderTime;
  99377. },
  99378. enumerable: true,
  99379. configurable: true
  99380. });
  99381. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99382. /**
  99383. * Gets the render time capture status
  99384. */
  99385. get: function () {
  99386. return this._captureRenderTime;
  99387. },
  99388. /**
  99389. * Enable or disable the render time capture
  99390. */
  99391. set: function (value) {
  99392. var _this = this;
  99393. if (value === this._captureRenderTime) {
  99394. return;
  99395. }
  99396. this._captureRenderTime = value;
  99397. if (value) {
  99398. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99399. _this._renderTime.beginMonitoring();
  99400. BABYLON.Tools.StartPerformanceCounter("Main render");
  99401. });
  99402. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99403. _this._renderTime.endMonitoring(false);
  99404. BABYLON.Tools.EndPerformanceCounter("Main render");
  99405. });
  99406. }
  99407. else {
  99408. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99409. this._onBeforeDrawPhaseObserver = null;
  99410. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99411. this._onAfterDrawPhaseObserver = null;
  99412. }
  99413. },
  99414. enumerable: true,
  99415. configurable: true
  99416. });
  99417. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99418. /**
  99419. * Gets the perf counter used for camera render time capture
  99420. */
  99421. get: function () {
  99422. return this._cameraRenderTime;
  99423. },
  99424. enumerable: true,
  99425. configurable: true
  99426. });
  99427. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99428. /**
  99429. * Gets the camera render time capture status
  99430. */
  99431. get: function () {
  99432. return this._captureCameraRenderTime;
  99433. },
  99434. /**
  99435. * Enable or disable the camera render time capture
  99436. */
  99437. set: function (value) {
  99438. var _this = this;
  99439. if (value === this._captureCameraRenderTime) {
  99440. return;
  99441. }
  99442. this._captureCameraRenderTime = value;
  99443. if (value) {
  99444. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99445. _this._cameraRenderTime.beginMonitoring();
  99446. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99447. });
  99448. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99449. _this._cameraRenderTime.endMonitoring(false);
  99450. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99451. });
  99452. }
  99453. else {
  99454. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99455. this._onBeforeCameraRenderObserver = null;
  99456. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99457. this._onAfterCameraRenderObserver = null;
  99458. }
  99459. },
  99460. enumerable: true,
  99461. configurable: true
  99462. });
  99463. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99464. /**
  99465. * Gets the perf counter used for draw calls
  99466. */
  99467. get: function () {
  99468. return this.scene.getEngine()._drawCalls;
  99469. },
  99470. enumerable: true,
  99471. configurable: true
  99472. });
  99473. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99474. /**
  99475. * Gets the perf counter used for texture collisions
  99476. */
  99477. get: function () {
  99478. return this.scene.getEngine()._textureCollisions;
  99479. },
  99480. enumerable: true,
  99481. configurable: true
  99482. });
  99483. SceneInstrumentation.prototype.dispose = function () {
  99484. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99485. this._onAfterRenderObserver = null;
  99486. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99487. this._onBeforeActiveMeshesEvaluationObserver = null;
  99488. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99489. this._onAfterActiveMeshesEvaluationObserver = null;
  99490. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99491. this._onBeforeRenderTargetsRenderObserver = null;
  99492. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99493. this._onAfterRenderTargetsRenderObserver = null;
  99494. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99495. this._onBeforeAnimationsObserver = null;
  99496. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99497. this._onBeforeParticlesRenderingObserver = null;
  99498. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99499. this._onAfterParticlesRenderingObserver = null;
  99500. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99501. this._onBeforeSpritesRenderingObserver = null;
  99502. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99503. this._onAfterSpritesRenderingObserver = null;
  99504. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99505. this._onBeforeDrawPhaseObserver = null;
  99506. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99507. this._onAfterDrawPhaseObserver = null;
  99508. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99509. this._onBeforePhysicsObserver = null;
  99510. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99511. this._onAfterPhysicsObserver = null;
  99512. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99513. this._onAfterAnimationsObserver = null;
  99514. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99515. this._onBeforeCameraRenderObserver = null;
  99516. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99517. this._onAfterCameraRenderObserver = null;
  99518. this.scene = null;
  99519. };
  99520. return SceneInstrumentation;
  99521. }());
  99522. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99523. })(BABYLON || (BABYLON = {}));
  99524. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99525. var BABYLON;
  99526. (function (BABYLON) {
  99527. /**
  99528. * @hidden
  99529. **/
  99530. var _TimeToken = /** @class */ (function () {
  99531. function _TimeToken() {
  99532. this._timeElapsedQueryEnded = false;
  99533. }
  99534. return _TimeToken;
  99535. }());
  99536. BABYLON._TimeToken = _TimeToken;
  99537. })(BABYLON || (BABYLON = {}));
  99538. //# sourceMappingURL=babylon.timeToken.js.map
  99539. var BABYLON;
  99540. (function (BABYLON) {
  99541. /**
  99542. * Background material defines definition.
  99543. * @hidden Mainly internal Use
  99544. */
  99545. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99546. __extends(BackgroundMaterialDefines, _super);
  99547. /**
  99548. * Constructor of the defines.
  99549. */
  99550. function BackgroundMaterialDefines() {
  99551. var _this = _super.call(this) || this;
  99552. /**
  99553. * True if the diffuse texture is in use.
  99554. */
  99555. _this.DIFFUSE = false;
  99556. /**
  99557. * The direct UV channel to use.
  99558. */
  99559. _this.DIFFUSEDIRECTUV = 0;
  99560. /**
  99561. * True if the diffuse texture is in gamma space.
  99562. */
  99563. _this.GAMMADIFFUSE = false;
  99564. /**
  99565. * True if the diffuse texture has opacity in the alpha channel.
  99566. */
  99567. _this.DIFFUSEHASALPHA = false;
  99568. /**
  99569. * True if you want the material to fade to transparent at grazing angle.
  99570. */
  99571. _this.OPACITYFRESNEL = false;
  99572. /**
  99573. * True if an extra blur needs to be added in the reflection.
  99574. */
  99575. _this.REFLECTIONBLUR = false;
  99576. /**
  99577. * True if you want the material to fade to reflection at grazing angle.
  99578. */
  99579. _this.REFLECTIONFRESNEL = false;
  99580. /**
  99581. * True if you want the material to falloff as far as you move away from the scene center.
  99582. */
  99583. _this.REFLECTIONFALLOFF = false;
  99584. /**
  99585. * False if the current Webgl implementation does not support the texture lod extension.
  99586. */
  99587. _this.TEXTURELODSUPPORT = false;
  99588. /**
  99589. * True to ensure the data are premultiplied.
  99590. */
  99591. _this.PREMULTIPLYALPHA = false;
  99592. /**
  99593. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  99594. */
  99595. _this.USERGBCOLOR = false;
  99596. /**
  99597. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  99598. * stays aligned with the desired configuration.
  99599. */
  99600. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  99601. /**
  99602. * True to add noise in order to reduce the banding effect.
  99603. */
  99604. _this.NOISE = false;
  99605. /**
  99606. * is the reflection texture in BGR color scheme?
  99607. * Mainly used to solve a bug in ios10 video tag
  99608. */
  99609. _this.REFLECTIONBGR = false;
  99610. _this.IMAGEPROCESSING = false;
  99611. _this.VIGNETTE = false;
  99612. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  99613. _this.VIGNETTEBLENDMODEOPAQUE = false;
  99614. _this.TONEMAPPING = false;
  99615. _this.CONTRAST = false;
  99616. _this.COLORCURVES = false;
  99617. _this.COLORGRADING = false;
  99618. _this.COLORGRADING3D = false;
  99619. _this.SAMPLER3DGREENDEPTH = false;
  99620. _this.SAMPLER3DBGRMAP = false;
  99621. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  99622. _this.EXPOSURE = false;
  99623. // Reflection.
  99624. _this.REFLECTION = false;
  99625. _this.REFLECTIONMAP_3D = false;
  99626. _this.REFLECTIONMAP_SPHERICAL = false;
  99627. _this.REFLECTIONMAP_PLANAR = false;
  99628. _this.REFLECTIONMAP_CUBIC = false;
  99629. _this.REFLECTIONMAP_PROJECTION = false;
  99630. _this.REFLECTIONMAP_SKYBOX = false;
  99631. _this.REFLECTIONMAP_EXPLICIT = false;
  99632. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99633. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99634. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99635. _this.INVERTCUBICMAP = false;
  99636. _this.REFLECTIONMAP_OPPOSITEZ = false;
  99637. _this.LODINREFLECTIONALPHA = false;
  99638. _this.GAMMAREFLECTION = false;
  99639. _this.RGBDREFLECTION = false;
  99640. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  99641. // Default BJS.
  99642. _this.MAINUV1 = false;
  99643. _this.MAINUV2 = false;
  99644. _this.UV1 = false;
  99645. _this.UV2 = false;
  99646. _this.CLIPPLANE = false;
  99647. _this.POINTSIZE = false;
  99648. _this.FOG = false;
  99649. _this.NORMAL = false;
  99650. _this.NUM_BONE_INFLUENCERS = 0;
  99651. _this.BonesPerMesh = 0;
  99652. _this.INSTANCES = false;
  99653. _this.SHADOWFLOAT = false;
  99654. _this.rebuild();
  99655. return _this;
  99656. }
  99657. return BackgroundMaterialDefines;
  99658. }(BABYLON.MaterialDefines));
  99659. /**
  99660. * Background material used to create an efficient environement around your scene.
  99661. */
  99662. var BackgroundMaterial = /** @class */ (function (_super) {
  99663. __extends(BackgroundMaterial, _super);
  99664. /**
  99665. * Instantiates a Background Material in the given scene
  99666. * @param name The friendly name of the material
  99667. * @param scene The scene to add the material to
  99668. */
  99669. function BackgroundMaterial(name, scene) {
  99670. var _this = _super.call(this, name, scene) || this;
  99671. /**
  99672. * Key light Color (multiply against the environement texture)
  99673. */
  99674. _this.primaryColor = BABYLON.Color3.White();
  99675. _this._primaryColorShadowLevel = 0;
  99676. _this._primaryColorHighlightLevel = 0;
  99677. /**
  99678. * Reflection Texture used in the material.
  99679. * Should be author in a specific way for the best result (refer to the documentation).
  99680. */
  99681. _this.reflectionTexture = null;
  99682. /**
  99683. * Reflection Texture level of blur.
  99684. *
  99685. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  99686. * texture twice.
  99687. */
  99688. _this.reflectionBlur = 0;
  99689. /**
  99690. * Diffuse Texture used in the material.
  99691. * Should be author in a specific way for the best result (refer to the documentation).
  99692. */
  99693. _this.diffuseTexture = null;
  99694. _this._shadowLights = null;
  99695. /**
  99696. * Specify the list of lights casting shadow on the material.
  99697. * All scene shadow lights will be included if null.
  99698. */
  99699. _this.shadowLights = null;
  99700. /**
  99701. * Helps adjusting the shadow to a softer level if required.
  99702. * 0 means black shadows and 1 means no shadows.
  99703. */
  99704. _this.shadowLevel = 0;
  99705. /**
  99706. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  99707. * It is usually zero but might be interesting to modify according to your setup.
  99708. */
  99709. _this.sceneCenter = BABYLON.Vector3.Zero();
  99710. /**
  99711. * This helps specifying that the material is falling off to the sky box at grazing angle.
  99712. * This helps ensuring a nice transition when the camera goes under the ground.
  99713. */
  99714. _this.opacityFresnel = true;
  99715. /**
  99716. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  99717. * This helps adding a mirror texture on the ground.
  99718. */
  99719. _this.reflectionFresnel = false;
  99720. /**
  99721. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  99722. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  99723. */
  99724. _this.reflectionFalloffDistance = 0.0;
  99725. /**
  99726. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  99727. */
  99728. _this.reflectionAmount = 1.0;
  99729. /**
  99730. * This specifies the weight of the reflection at grazing angle.
  99731. */
  99732. _this.reflectionReflectance0 = 0.05;
  99733. /**
  99734. * This specifies the weight of the reflection at a perpendicular point of view.
  99735. */
  99736. _this.reflectionReflectance90 = 0.5;
  99737. /**
  99738. * Helps to directly use the maps channels instead of their level.
  99739. */
  99740. _this.useRGBColor = true;
  99741. /**
  99742. * This helps reducing the banding effect that could occur on the background.
  99743. */
  99744. _this.enableNoise = false;
  99745. _this._fovMultiplier = 1.0;
  99746. /**
  99747. * Enable the FOV adjustment feature controlled by fovMultiplier.
  99748. */
  99749. _this.useEquirectangularFOV = false;
  99750. _this._maxSimultaneousLights = 4;
  99751. /**
  99752. * Number of Simultaneous lights allowed on the material.
  99753. */
  99754. _this.maxSimultaneousLights = 4;
  99755. /**
  99756. * Keep track of the image processing observer to allow dispose and replace.
  99757. */
  99758. _this._imageProcessingObserver = null;
  99759. /**
  99760. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  99761. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  99762. */
  99763. _this.switchToBGR = false;
  99764. // Temp values kept as cache in the material.
  99765. _this._renderTargets = new BABYLON.SmartArray(16);
  99766. _this._reflectionControls = BABYLON.Vector4.Zero();
  99767. _this._white = BABYLON.Color3.White();
  99768. _this._primaryShadowColor = BABYLON.Color3.Black();
  99769. _this._primaryHighlightColor = BABYLON.Color3.Black();
  99770. // Setup the default processing configuration to the scene.
  99771. _this._attachImageProcessingConfiguration(null);
  99772. _this.getRenderTargetTextures = function () {
  99773. _this._renderTargets.reset();
  99774. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  99775. _this._renderTargets.push(_this._diffuseTexture);
  99776. }
  99777. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  99778. _this._renderTargets.push(_this._reflectionTexture);
  99779. }
  99780. return _this._renderTargets;
  99781. };
  99782. return _this;
  99783. }
  99784. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  99785. /**
  99786. * Experimental Internal Use Only.
  99787. *
  99788. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  99789. * This acts as a helper to set the primary color to a more "human friendly" value.
  99790. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  99791. * output color as close as possible from the chosen value.
  99792. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  99793. * part of lighting setup.)
  99794. */
  99795. get: function () {
  99796. return this.__perceptualColor;
  99797. },
  99798. set: function (value) {
  99799. this.__perceptualColor = value;
  99800. this._computePrimaryColorFromPerceptualColor();
  99801. this._markAllSubMeshesAsLightsDirty();
  99802. },
  99803. enumerable: true,
  99804. configurable: true
  99805. });
  99806. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  99807. /**
  99808. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  99809. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  99810. */
  99811. get: function () {
  99812. return this._primaryColorShadowLevel;
  99813. },
  99814. set: function (value) {
  99815. this._primaryColorShadowLevel = value;
  99816. this._computePrimaryColors();
  99817. this._markAllSubMeshesAsLightsDirty();
  99818. },
  99819. enumerable: true,
  99820. configurable: true
  99821. });
  99822. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  99823. /**
  99824. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  99825. * The primary color is used at the level chosen to define what the white area would look.
  99826. */
  99827. get: function () {
  99828. return this._primaryColorHighlightLevel;
  99829. },
  99830. set: function (value) {
  99831. this._primaryColorHighlightLevel = value;
  99832. this._computePrimaryColors();
  99833. this._markAllSubMeshesAsLightsDirty();
  99834. },
  99835. enumerable: true,
  99836. configurable: true
  99837. });
  99838. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  99839. /**
  99840. * Sets the reflection reflectance fresnel values according to the default standard
  99841. * empirically know to work well :-)
  99842. */
  99843. set: function (value) {
  99844. var reflectionWeight = value;
  99845. if (reflectionWeight < 0.5) {
  99846. reflectionWeight = reflectionWeight * 2.0;
  99847. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  99848. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  99849. }
  99850. else {
  99851. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  99852. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  99853. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  99854. }
  99855. },
  99856. enumerable: true,
  99857. configurable: true
  99858. });
  99859. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  99860. /**
  99861. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99862. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  99863. * Recommended to be keep at 1.0 except for special cases.
  99864. */
  99865. get: function () {
  99866. return this._fovMultiplier;
  99867. },
  99868. set: function (value) {
  99869. if (isNaN(value)) {
  99870. value = 1.0;
  99871. }
  99872. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  99873. },
  99874. enumerable: true,
  99875. configurable: true
  99876. });
  99877. /**
  99878. * Attaches a new image processing configuration to the PBR Material.
  99879. * @param configuration (if null the scene configuration will be use)
  99880. */
  99881. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  99882. var _this = this;
  99883. if (configuration === this._imageProcessingConfiguration) {
  99884. return;
  99885. }
  99886. // Detaches observer.
  99887. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99888. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99889. }
  99890. // Pick the scene configuration if needed.
  99891. if (!configuration) {
  99892. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  99893. }
  99894. else {
  99895. this._imageProcessingConfiguration = configuration;
  99896. }
  99897. // Attaches observer.
  99898. if (this._imageProcessingConfiguration) {
  99899. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  99900. _this._computePrimaryColorFromPerceptualColor();
  99901. _this._markAllSubMeshesAsImageProcessingDirty();
  99902. });
  99903. }
  99904. };
  99905. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  99906. /**
  99907. * Gets the image processing configuration used either in this material.
  99908. */
  99909. get: function () {
  99910. return this._imageProcessingConfiguration;
  99911. },
  99912. /**
  99913. * Sets the Default image processing configuration used either in the this material.
  99914. *
  99915. * If sets to null, the scene one is in use.
  99916. */
  99917. set: function (value) {
  99918. this._attachImageProcessingConfiguration(value);
  99919. // Ensure the effect will be rebuilt.
  99920. this._markAllSubMeshesAsTexturesDirty();
  99921. },
  99922. enumerable: true,
  99923. configurable: true
  99924. });
  99925. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  99926. /**
  99927. * Gets wether the color curves effect is enabled.
  99928. */
  99929. get: function () {
  99930. return this.imageProcessingConfiguration.colorCurvesEnabled;
  99931. },
  99932. /**
  99933. * Sets wether the color curves effect is enabled.
  99934. */
  99935. set: function (value) {
  99936. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  99937. },
  99938. enumerable: true,
  99939. configurable: true
  99940. });
  99941. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  99942. /**
  99943. * Gets wether the color grading effect is enabled.
  99944. */
  99945. get: function () {
  99946. return this.imageProcessingConfiguration.colorGradingEnabled;
  99947. },
  99948. /**
  99949. * Gets wether the color grading effect is enabled.
  99950. */
  99951. set: function (value) {
  99952. this.imageProcessingConfiguration.colorGradingEnabled = value;
  99953. },
  99954. enumerable: true,
  99955. configurable: true
  99956. });
  99957. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99958. /**
  99959. * Gets wether tonemapping is enabled or not.
  99960. */
  99961. get: function () {
  99962. return this._imageProcessingConfiguration.toneMappingEnabled;
  99963. },
  99964. /**
  99965. * Sets wether tonemapping is enabled or not
  99966. */
  99967. set: function (value) {
  99968. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99969. },
  99970. enumerable: true,
  99971. configurable: true
  99972. });
  99973. ;
  99974. ;
  99975. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99976. /**
  99977. * The camera exposure used on this material.
  99978. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99979. * This corresponds to a photographic exposure.
  99980. */
  99981. get: function () {
  99982. return this._imageProcessingConfiguration.exposure;
  99983. },
  99984. /**
  99985. * The camera exposure used on this material.
  99986. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99987. * This corresponds to a photographic exposure.
  99988. */
  99989. set: function (value) {
  99990. this._imageProcessingConfiguration.exposure = value;
  99991. },
  99992. enumerable: true,
  99993. configurable: true
  99994. });
  99995. ;
  99996. ;
  99997. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99998. /**
  99999. * Gets The camera contrast used on this material.
  100000. */
  100001. get: function () {
  100002. return this._imageProcessingConfiguration.contrast;
  100003. },
  100004. /**
  100005. * Sets The camera contrast used on this material.
  100006. */
  100007. set: function (value) {
  100008. this._imageProcessingConfiguration.contrast = value;
  100009. },
  100010. enumerable: true,
  100011. configurable: true
  100012. });
  100013. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100014. /**
  100015. * Gets the Color Grading 2D Lookup Texture.
  100016. */
  100017. get: function () {
  100018. return this._imageProcessingConfiguration.colorGradingTexture;
  100019. },
  100020. /**
  100021. * Sets the Color Grading 2D Lookup Texture.
  100022. */
  100023. set: function (value) {
  100024. this.imageProcessingConfiguration.colorGradingTexture = value;
  100025. },
  100026. enumerable: true,
  100027. configurable: true
  100028. });
  100029. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100030. /**
  100031. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100032. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100033. * 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;
  100034. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100035. */
  100036. get: function () {
  100037. return this.imageProcessingConfiguration.colorCurves;
  100038. },
  100039. /**
  100040. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100041. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100042. * 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;
  100043. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100044. */
  100045. set: function (value) {
  100046. this.imageProcessingConfiguration.colorCurves = value;
  100047. },
  100048. enumerable: true,
  100049. configurable: true
  100050. });
  100051. /**
  100052. * The entire material has been created in order to prevent overdraw.
  100053. * @returns false
  100054. */
  100055. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100056. return true;
  100057. };
  100058. /**
  100059. * The entire material has been created in order to prevent overdraw.
  100060. * @returns true if blending is enable
  100061. */
  100062. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100063. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100064. };
  100065. /**
  100066. * Checks wether the material is ready to be rendered for a given mesh.
  100067. * @param mesh The mesh to render
  100068. * @param subMesh The submesh to check against
  100069. * @param useInstances Specify wether or not the material is used with instances
  100070. * @returns true if all the dependencies are ready (Textures, Effects...)
  100071. */
  100072. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100073. var _this = this;
  100074. if (useInstances === void 0) { useInstances = false; }
  100075. if (subMesh.effect && this.isFrozen) {
  100076. if (this._wasPreviouslyReady) {
  100077. return true;
  100078. }
  100079. }
  100080. if (!subMesh._materialDefines) {
  100081. subMesh._materialDefines = new BackgroundMaterialDefines();
  100082. }
  100083. var scene = this.getScene();
  100084. var defines = subMesh._materialDefines;
  100085. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100086. if (defines._renderId === scene.getRenderId()) {
  100087. return true;
  100088. }
  100089. }
  100090. var engine = scene.getEngine();
  100091. // Lights
  100092. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100093. defines._needNormals = true;
  100094. // Textures
  100095. if (defines._areTexturesDirty) {
  100096. defines._needUVs = false;
  100097. if (scene.texturesEnabled) {
  100098. if (scene.getEngine().getCaps().textureLOD) {
  100099. defines.TEXTURELODSUPPORT = true;
  100100. }
  100101. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100102. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100103. return false;
  100104. }
  100105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100106. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100107. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100108. defines.OPACITYFRESNEL = this._opacityFresnel;
  100109. }
  100110. else {
  100111. defines.DIFFUSE = false;
  100112. defines.DIFFUSEHASALPHA = false;
  100113. defines.GAMMADIFFUSE = false;
  100114. defines.OPACITYFRESNEL = false;
  100115. }
  100116. var reflectionTexture = this._reflectionTexture;
  100117. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100118. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100119. return false;
  100120. }
  100121. defines.REFLECTION = true;
  100122. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100123. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100124. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100125. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100126. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100127. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100128. defines.REFLECTIONBGR = this.switchToBGR;
  100129. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100130. defines.INVERTCUBICMAP = true;
  100131. }
  100132. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100133. switch (reflectionTexture.coordinatesMode) {
  100134. case BABYLON.Texture.EXPLICIT_MODE:
  100135. defines.REFLECTIONMAP_EXPLICIT = true;
  100136. break;
  100137. case BABYLON.Texture.PLANAR_MODE:
  100138. defines.REFLECTIONMAP_PLANAR = true;
  100139. break;
  100140. case BABYLON.Texture.PROJECTION_MODE:
  100141. defines.REFLECTIONMAP_PROJECTION = true;
  100142. break;
  100143. case BABYLON.Texture.SKYBOX_MODE:
  100144. defines.REFLECTIONMAP_SKYBOX = true;
  100145. break;
  100146. case BABYLON.Texture.SPHERICAL_MODE:
  100147. defines.REFLECTIONMAP_SPHERICAL = true;
  100148. break;
  100149. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100150. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100151. break;
  100152. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100153. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100154. break;
  100155. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100156. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100157. break;
  100158. case BABYLON.Texture.CUBIC_MODE:
  100159. case BABYLON.Texture.INVCUBIC_MODE:
  100160. default:
  100161. defines.REFLECTIONMAP_CUBIC = true;
  100162. break;
  100163. }
  100164. if (this.reflectionFresnel) {
  100165. defines.REFLECTIONFRESNEL = true;
  100166. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100167. this._reflectionControls.x = this.reflectionAmount;
  100168. this._reflectionControls.y = this.reflectionReflectance0;
  100169. this._reflectionControls.z = this.reflectionReflectance90;
  100170. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100171. }
  100172. else {
  100173. defines.REFLECTIONFRESNEL = false;
  100174. defines.REFLECTIONFALLOFF = false;
  100175. }
  100176. }
  100177. else {
  100178. defines.REFLECTION = false;
  100179. defines.REFLECTIONFRESNEL = false;
  100180. defines.REFLECTIONFALLOFF = false;
  100181. defines.REFLECTIONBLUR = false;
  100182. defines.REFLECTIONMAP_3D = false;
  100183. defines.REFLECTIONMAP_SPHERICAL = false;
  100184. defines.REFLECTIONMAP_PLANAR = false;
  100185. defines.REFLECTIONMAP_CUBIC = false;
  100186. defines.REFLECTIONMAP_PROJECTION = false;
  100187. defines.REFLECTIONMAP_SKYBOX = false;
  100188. defines.REFLECTIONMAP_EXPLICIT = false;
  100189. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100190. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100191. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100192. defines.INVERTCUBICMAP = false;
  100193. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100194. defines.LODINREFLECTIONALPHA = false;
  100195. defines.GAMMAREFLECTION = false;
  100196. defines.RGBDREFLECTION = false;
  100197. }
  100198. }
  100199. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100200. defines.USERGBCOLOR = this._useRGBColor;
  100201. defines.NOISE = this._enableNoise;
  100202. }
  100203. if (defines._areLightsDirty) {
  100204. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100205. }
  100206. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100207. if (!this._imageProcessingConfiguration.isReady()) {
  100208. return false;
  100209. }
  100210. this._imageProcessingConfiguration.prepareDefines(defines);
  100211. }
  100212. // Misc.
  100213. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100214. // Values that need to be evaluated on every frame
  100215. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100216. // Attribs
  100217. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100218. if (mesh) {
  100219. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100220. mesh.createNormals(true);
  100221. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100222. }
  100223. }
  100224. }
  100225. // Get correct effect
  100226. if (defines.isDirty) {
  100227. defines.markAsProcessed();
  100228. scene.resetCachedMaterial();
  100229. // Fallbacks
  100230. var fallbacks = new BABYLON.EffectFallbacks();
  100231. if (defines.FOG) {
  100232. fallbacks.addFallback(0, "FOG");
  100233. }
  100234. if (defines.POINTSIZE) {
  100235. fallbacks.addFallback(1, "POINTSIZE");
  100236. }
  100237. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100238. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100239. fallbacks.addCPUSkinningFallback(0, mesh);
  100240. }
  100241. //Attributes
  100242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100243. if (defines.NORMAL) {
  100244. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100245. }
  100246. if (defines.UV1) {
  100247. attribs.push(BABYLON.VertexBuffer.UVKind);
  100248. }
  100249. if (defines.UV2) {
  100250. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100251. }
  100252. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100253. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100254. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100255. "vFogInfos", "vFogColor", "pointSize",
  100256. "vClipPlane", "mBones",
  100257. "vPrimaryColor", "vPrimaryColorShadow",
  100258. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100259. "shadowLevel", "alpha",
  100260. "vBackgroundCenter", "vReflectionControl",
  100261. "vDiffuseInfos", "diffuseMatrix",
  100262. ];
  100263. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100264. var uniformBuffers = ["Material", "Scene"];
  100265. if (BABYLON.ImageProcessingConfiguration) {
  100266. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100267. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100268. }
  100269. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100270. uniformsNames: uniforms,
  100271. uniformBuffersNames: uniformBuffers,
  100272. samplers: samplers,
  100273. defines: defines,
  100274. maxSimultaneousLights: this._maxSimultaneousLights
  100275. });
  100276. var onCompiled = function (effect) {
  100277. if (_this.onCompiled) {
  100278. _this.onCompiled(effect);
  100279. }
  100280. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100281. };
  100282. var join = defines.toString();
  100283. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100284. attributes: attribs,
  100285. uniformsNames: uniforms,
  100286. uniformBuffersNames: uniformBuffers,
  100287. samplers: samplers,
  100288. defines: join,
  100289. fallbacks: fallbacks,
  100290. onCompiled: onCompiled,
  100291. onError: this.onError,
  100292. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100293. }, engine), defines);
  100294. this.buildUniformLayout();
  100295. }
  100296. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100297. return false;
  100298. }
  100299. defines._renderId = scene.getRenderId();
  100300. this._wasPreviouslyReady = true;
  100301. return true;
  100302. };
  100303. /**
  100304. * Compute the primary color according to the chosen perceptual color.
  100305. */
  100306. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100307. if (!this.__perceptualColor) {
  100308. return;
  100309. }
  100310. this._primaryColor.copyFrom(this.__perceptualColor);
  100311. // Revert gamma space.
  100312. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100313. // Revert image processing configuration.
  100314. if (this._imageProcessingConfiguration) {
  100315. // Revert Exposure.
  100316. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100317. }
  100318. this._computePrimaryColors();
  100319. };
  100320. /**
  100321. * Compute the highlights and shadow colors according to their chosen levels.
  100322. */
  100323. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100324. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100325. return;
  100326. }
  100327. // Find the highlight color based on the configuration.
  100328. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100329. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100330. // Find the shadow color based on the configuration.
  100331. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100332. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100333. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100334. };
  100335. /**
  100336. * Build the uniform buffer used in the material.
  100337. */
  100338. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100339. // Order is important !
  100340. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100341. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100342. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100343. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100344. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100345. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100346. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100347. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100348. this._uniformBuffer.addUniform("pointSize", 1);
  100349. this._uniformBuffer.addUniform("shadowLevel", 1);
  100350. this._uniformBuffer.addUniform("alpha", 1);
  100351. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100352. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100353. this._uniformBuffer.create();
  100354. };
  100355. /**
  100356. * Unbind the material.
  100357. */
  100358. BackgroundMaterial.prototype.unbind = function () {
  100359. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100360. this._uniformBuffer.setTexture("diffuseSampler", null);
  100361. }
  100362. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100363. this._uniformBuffer.setTexture("reflectionSampler", null);
  100364. }
  100365. _super.prototype.unbind.call(this);
  100366. };
  100367. /**
  100368. * Bind only the world matrix to the material.
  100369. * @param world The world matrix to bind.
  100370. */
  100371. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100372. this._activeEffect.setMatrix("world", world);
  100373. };
  100374. /**
  100375. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100376. * @param world The world matrix to bind.
  100377. * @param subMesh The submesh to bind for.
  100378. */
  100379. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100380. var scene = this.getScene();
  100381. var defines = subMesh._materialDefines;
  100382. if (!defines) {
  100383. return;
  100384. }
  100385. var effect = subMesh.effect;
  100386. if (!effect) {
  100387. return;
  100388. }
  100389. this._activeEffect = effect;
  100390. // Matrices
  100391. this.bindOnlyWorldMatrix(world);
  100392. // Bones
  100393. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100394. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100395. if (mustRebind) {
  100396. this._uniformBuffer.bindToEffect(effect, "Material");
  100397. this.bindViewProjection(effect);
  100398. var reflectionTexture = this._reflectionTexture;
  100399. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100400. // Texture uniforms
  100401. if (scene.texturesEnabled) {
  100402. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100403. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100404. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100405. }
  100406. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100407. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100408. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100409. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100410. }
  100411. }
  100412. if (this.shadowLevel > 0) {
  100413. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100414. }
  100415. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100416. // Point size
  100417. if (this.pointsCloud) {
  100418. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100419. }
  100420. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100421. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100422. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100423. }
  100424. else {
  100425. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100426. }
  100427. }
  100428. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100429. // Textures
  100430. if (scene.texturesEnabled) {
  100431. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100432. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100433. }
  100434. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100435. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100436. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100437. }
  100438. else if (!defines.REFLECTIONBLUR) {
  100439. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100440. }
  100441. else {
  100442. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100443. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100444. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100445. }
  100446. if (defines.REFLECTIONFRESNEL) {
  100447. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100448. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100449. }
  100450. }
  100451. }
  100452. // Clip plane
  100453. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100454. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100455. }
  100456. if (mustRebind || !this.isFrozen) {
  100457. if (scene.lightsEnabled) {
  100458. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100459. }
  100460. // View
  100461. this.bindView(effect);
  100462. // Fog
  100463. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100464. // image processing
  100465. if (this._imageProcessingConfiguration) {
  100466. this._imageProcessingConfiguration.bind(this._activeEffect);
  100467. }
  100468. }
  100469. this._uniformBuffer.update();
  100470. this._afterBind(mesh, this._activeEffect);
  100471. };
  100472. /**
  100473. * Dispose the material.
  100474. * @param forceDisposeEffect Force disposal of the associated effect.
  100475. * @param forceDisposeTextures Force disposal of the associated textures.
  100476. */
  100477. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100478. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100479. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100480. if (forceDisposeTextures) {
  100481. if (this.diffuseTexture) {
  100482. this.diffuseTexture.dispose();
  100483. }
  100484. if (this.reflectionTexture) {
  100485. this.reflectionTexture.dispose();
  100486. }
  100487. }
  100488. this._renderTargets.dispose();
  100489. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100490. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100491. }
  100492. _super.prototype.dispose.call(this, forceDisposeEffect);
  100493. };
  100494. /**
  100495. * Clones the material.
  100496. * @param name The cloned name.
  100497. * @returns The cloned material.
  100498. */
  100499. BackgroundMaterial.prototype.clone = function (name) {
  100500. var _this = this;
  100501. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100502. };
  100503. /**
  100504. * Serializes the current material to its JSON representation.
  100505. * @returns The JSON representation.
  100506. */
  100507. BackgroundMaterial.prototype.serialize = function () {
  100508. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100509. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100510. return serializationObject;
  100511. };
  100512. /**
  100513. * Gets the class name of the material
  100514. * @returns "BackgroundMaterial"
  100515. */
  100516. BackgroundMaterial.prototype.getClassName = function () {
  100517. return "BackgroundMaterial";
  100518. };
  100519. /**
  100520. * Parse a JSON input to create back a background material.
  100521. * @param source The JSON data to parse
  100522. * @param scene The scene to create the parsed material in
  100523. * @param rootUrl The root url of the assets the material depends upon
  100524. * @returns the instantiated BackgroundMaterial.
  100525. */
  100526. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100527. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100528. };
  100529. /**
  100530. * Standard reflectance value at parallel view angle.
  100531. */
  100532. BackgroundMaterial.StandardReflectance0 = 0.05;
  100533. /**
  100534. * Standard reflectance value at grazing angle.
  100535. */
  100536. BackgroundMaterial.StandardReflectance90 = 0.5;
  100537. __decorate([
  100538. BABYLON.serializeAsColor3()
  100539. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100540. __decorate([
  100541. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100542. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100543. __decorate([
  100544. BABYLON.serializeAsColor3()
  100545. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100546. __decorate([
  100547. BABYLON.serialize()
  100548. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100549. __decorate([
  100550. BABYLON.serialize()
  100551. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100552. __decorate([
  100553. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100554. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100555. __decorate([
  100556. BABYLON.serializeAsTexture()
  100557. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100558. __decorate([
  100559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100560. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100561. __decorate([
  100562. BABYLON.serialize()
  100563. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100564. __decorate([
  100565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100566. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100567. __decorate([
  100568. BABYLON.serializeAsTexture()
  100569. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100570. __decorate([
  100571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100572. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100573. __decorate([
  100574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100575. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100576. __decorate([
  100577. BABYLON.serialize()
  100578. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100579. __decorate([
  100580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100581. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100582. __decorate([
  100583. BABYLON.serializeAsVector3()
  100584. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  100585. __decorate([
  100586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100587. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  100588. __decorate([
  100589. BABYLON.serialize()
  100590. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  100591. __decorate([
  100592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100593. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  100594. __decorate([
  100595. BABYLON.serialize()
  100596. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  100597. __decorate([
  100598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100599. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  100600. __decorate([
  100601. BABYLON.serialize()
  100602. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  100603. __decorate([
  100604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100605. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  100606. __decorate([
  100607. BABYLON.serialize()
  100608. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  100609. __decorate([
  100610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100611. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  100612. __decorate([
  100613. BABYLON.serialize()
  100614. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  100615. __decorate([
  100616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100617. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  100618. __decorate([
  100619. BABYLON.serialize()
  100620. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  100621. __decorate([
  100622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100623. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  100624. __decorate([
  100625. BABYLON.serialize()
  100626. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  100627. __decorate([
  100628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100629. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  100630. __decorate([
  100631. BABYLON.serialize()
  100632. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  100633. __decorate([
  100634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100635. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  100636. __decorate([
  100637. BABYLON.serialize()
  100638. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  100639. __decorate([
  100640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100641. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  100642. __decorate([
  100643. BABYLON.serializeAsImageProcessingConfiguration()
  100644. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  100645. return BackgroundMaterial;
  100646. }(BABYLON.PushMaterial));
  100647. BABYLON.BackgroundMaterial = BackgroundMaterial;
  100648. })(BABYLON || (BABYLON = {}));
  100649. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  100650. var __assign = (this && this.__assign) || Object.assign || function(t) {
  100651. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100652. s = arguments[i];
  100653. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100654. t[p] = s[p];
  100655. }
  100656. return t;
  100657. };
  100658. var BABYLON;
  100659. (function (BABYLON) {
  100660. /**
  100661. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  100662. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  100663. * It also helps with the default setup of your imageProcessing configuration.
  100664. */
  100665. var EnvironmentHelper = /** @class */ (function () {
  100666. /**
  100667. * constructor
  100668. * @param options
  100669. * @param scene The scene to add the material to
  100670. */
  100671. function EnvironmentHelper(options, scene) {
  100672. var _this = this;
  100673. this._errorHandler = function (message, exception) {
  100674. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  100675. };
  100676. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  100677. this._scene = scene;
  100678. this.onErrorObservable = new BABYLON.Observable();
  100679. this._setupBackground();
  100680. this._setupImageProcessing();
  100681. }
  100682. /**
  100683. * Creates the default options for the helper.
  100684. */
  100685. EnvironmentHelper._getDefaultOptions = function () {
  100686. return {
  100687. createGround: true,
  100688. groundSize: 15,
  100689. groundTexture: this._groundTextureCDNUrl,
  100690. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100691. groundOpacity: 0.9,
  100692. enableGroundShadow: true,
  100693. groundShadowLevel: 0.5,
  100694. enableGroundMirror: false,
  100695. groundMirrorSizeRatio: 0.3,
  100696. groundMirrorBlurKernel: 64,
  100697. groundMirrorAmount: 1,
  100698. groundMirrorFresnelWeight: 1,
  100699. groundMirrorFallOffDistance: 0,
  100700. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  100701. groundYBias: 0.00001,
  100702. createSkybox: true,
  100703. skyboxSize: 20,
  100704. skyboxTexture: this._skyboxTextureCDNUrl,
  100705. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100706. backgroundYRotation: 0,
  100707. sizeAuto: true,
  100708. rootPosition: BABYLON.Vector3.Zero(),
  100709. setupImageProcessing: true,
  100710. environmentTexture: this._environmentTextureCDNUrl,
  100711. cameraExposure: 0.8,
  100712. cameraContrast: 1.2,
  100713. toneMappingEnabled: true,
  100714. };
  100715. };
  100716. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  100717. /**
  100718. * Gets the root mesh created by the helper.
  100719. */
  100720. get: function () {
  100721. return this._rootMesh;
  100722. },
  100723. enumerable: true,
  100724. configurable: true
  100725. });
  100726. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  100727. /**
  100728. * Gets the skybox created by the helper.
  100729. */
  100730. get: function () {
  100731. return this._skybox;
  100732. },
  100733. enumerable: true,
  100734. configurable: true
  100735. });
  100736. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  100737. /**
  100738. * Gets the skybox texture created by the helper.
  100739. */
  100740. get: function () {
  100741. return this._skyboxTexture;
  100742. },
  100743. enumerable: true,
  100744. configurable: true
  100745. });
  100746. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  100747. /**
  100748. * Gets the skybox material created by the helper.
  100749. */
  100750. get: function () {
  100751. return this._skyboxMaterial;
  100752. },
  100753. enumerable: true,
  100754. configurable: true
  100755. });
  100756. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  100757. /**
  100758. * Gets the ground mesh created by the helper.
  100759. */
  100760. get: function () {
  100761. return this._ground;
  100762. },
  100763. enumerable: true,
  100764. configurable: true
  100765. });
  100766. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  100767. /**
  100768. * Gets the ground texture created by the helper.
  100769. */
  100770. get: function () {
  100771. return this._groundTexture;
  100772. },
  100773. enumerable: true,
  100774. configurable: true
  100775. });
  100776. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  100777. /**
  100778. * Gets the ground mirror created by the helper.
  100779. */
  100780. get: function () {
  100781. return this._groundMirror;
  100782. },
  100783. enumerable: true,
  100784. configurable: true
  100785. });
  100786. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  100787. /**
  100788. * Gets the ground mirror render list to helps pushing the meshes
  100789. * you wish in the ground reflection.
  100790. */
  100791. get: function () {
  100792. if (this._groundMirror) {
  100793. return this._groundMirror.renderList;
  100794. }
  100795. return null;
  100796. },
  100797. enumerable: true,
  100798. configurable: true
  100799. });
  100800. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  100801. /**
  100802. * Gets the ground material created by the helper.
  100803. */
  100804. get: function () {
  100805. return this._groundMaterial;
  100806. },
  100807. enumerable: true,
  100808. configurable: true
  100809. });
  100810. /**
  100811. * Updates the background according to the new options
  100812. * @param options
  100813. */
  100814. EnvironmentHelper.prototype.updateOptions = function (options) {
  100815. var newOptions = __assign({}, this._options, options);
  100816. if (this._ground && !newOptions.createGround) {
  100817. this._ground.dispose();
  100818. this._ground = null;
  100819. }
  100820. if (this._groundMaterial && !newOptions.createGround) {
  100821. this._groundMaterial.dispose();
  100822. this._groundMaterial = null;
  100823. }
  100824. if (this._groundTexture) {
  100825. if (this._options.groundTexture != newOptions.groundTexture) {
  100826. this._groundTexture.dispose();
  100827. this._groundTexture = null;
  100828. }
  100829. }
  100830. if (this._skybox && !newOptions.createSkybox) {
  100831. this._skybox.dispose();
  100832. this._skybox = null;
  100833. }
  100834. if (this._skyboxMaterial && !newOptions.createSkybox) {
  100835. this._skyboxMaterial.dispose();
  100836. this._skyboxMaterial = null;
  100837. }
  100838. if (this._skyboxTexture) {
  100839. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  100840. this._skyboxTexture.dispose();
  100841. this._skyboxTexture = null;
  100842. }
  100843. }
  100844. if (this._groundMirror && !newOptions.enableGroundMirror) {
  100845. this._groundMirror.dispose();
  100846. this._groundMirror = null;
  100847. }
  100848. if (this._scene.environmentTexture) {
  100849. if (this._options.environmentTexture != newOptions.environmentTexture) {
  100850. this._scene.environmentTexture.dispose();
  100851. }
  100852. }
  100853. this._options = newOptions;
  100854. this._setupBackground();
  100855. this._setupImageProcessing();
  100856. };
  100857. /**
  100858. * Sets the primary color of all the available elements.
  100859. * @param color the main color to affect to the ground and the background
  100860. */
  100861. EnvironmentHelper.prototype.setMainColor = function (color) {
  100862. if (this.groundMaterial) {
  100863. this.groundMaterial.primaryColor = color;
  100864. }
  100865. if (this.skyboxMaterial) {
  100866. this.skyboxMaterial.primaryColor = color;
  100867. }
  100868. if (this.groundMirror) {
  100869. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  100870. }
  100871. };
  100872. /**
  100873. * Setup the image processing according to the specified options.
  100874. */
  100875. EnvironmentHelper.prototype._setupImageProcessing = function () {
  100876. if (this._options.setupImageProcessing) {
  100877. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  100878. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  100879. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  100880. this._setupEnvironmentTexture();
  100881. }
  100882. };
  100883. /**
  100884. * Setup the environment texture according to the specified options.
  100885. */
  100886. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  100887. if (this._scene.environmentTexture) {
  100888. return;
  100889. }
  100890. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  100891. this._scene.environmentTexture = this._options.environmentTexture;
  100892. return;
  100893. }
  100894. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  100895. this._scene.environmentTexture = environmentTexture;
  100896. };
  100897. /**
  100898. * Setup the background according to the specified options.
  100899. */
  100900. EnvironmentHelper.prototype._setupBackground = function () {
  100901. if (!this._rootMesh) {
  100902. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  100903. }
  100904. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  100905. var sceneSize = this._getSceneSize();
  100906. if (this._options.createGround) {
  100907. this._setupGround(sceneSize);
  100908. this._setupGroundMaterial();
  100909. this._setupGroundDiffuseTexture();
  100910. if (this._options.enableGroundMirror) {
  100911. this._setupGroundMirrorTexture(sceneSize);
  100912. }
  100913. this._setupMirrorInGroundMaterial();
  100914. }
  100915. if (this._options.createSkybox) {
  100916. this._setupSkybox(sceneSize);
  100917. this._setupSkyboxMaterial();
  100918. this._setupSkyboxReflectionTexture();
  100919. }
  100920. this._rootMesh.position.x = sceneSize.rootPosition.x;
  100921. this._rootMesh.position.z = sceneSize.rootPosition.z;
  100922. this._rootMesh.position.y = sceneSize.rootPosition.y;
  100923. };
  100924. /**
  100925. * Get the scene sizes according to the setup.
  100926. */
  100927. EnvironmentHelper.prototype._getSceneSize = function () {
  100928. var _this = this;
  100929. var groundSize = this._options.groundSize;
  100930. var skyboxSize = this._options.skyboxSize;
  100931. var rootPosition = this._options.rootPosition;
  100932. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  100933. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100934. }
  100935. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  100936. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  100937. });
  100938. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  100939. if (this._options.sizeAuto) {
  100940. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  100941. this._scene.activeCamera.upperRadiusLimit) {
  100942. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  100943. skyboxSize = groundSize;
  100944. }
  100945. var sceneDiagonalLenght = sceneDiagonal.length();
  100946. if (sceneDiagonalLenght > groundSize) {
  100947. groundSize = sceneDiagonalLenght * 2;
  100948. skyboxSize = groundSize;
  100949. }
  100950. // 10 % bigger.
  100951. groundSize *= 1.1;
  100952. skyboxSize *= 1.5;
  100953. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  100954. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  100955. }
  100956. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100957. };
  100958. /**
  100959. * Setup the ground according to the specified options.
  100960. */
  100961. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100962. var _this = this;
  100963. if (!this._ground || this._ground.isDisposed()) {
  100964. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100965. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100966. this._ground.parent = this._rootMesh;
  100967. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100968. }
  100969. this._ground.receiveShadows = this._options.enableGroundShadow;
  100970. };
  100971. /**
  100972. * Setup the ground material according to the specified options.
  100973. */
  100974. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100975. if (!this._groundMaterial) {
  100976. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100977. }
  100978. this._groundMaterial.alpha = this._options.groundOpacity;
  100979. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100980. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100981. this._groundMaterial.primaryColor = this._options.groundColor;
  100982. this._groundMaterial.useRGBColor = false;
  100983. this._groundMaterial.enableNoise = true;
  100984. if (this._ground) {
  100985. this._ground.material = this._groundMaterial;
  100986. }
  100987. };
  100988. /**
  100989. * Setup the ground diffuse texture according to the specified options.
  100990. */
  100991. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100992. if (!this._groundMaterial) {
  100993. return;
  100994. }
  100995. if (this._groundTexture) {
  100996. return;
  100997. }
  100998. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100999. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101000. return;
  101001. }
  101002. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101003. diffuseTexture.gammaSpace = false;
  101004. diffuseTexture.hasAlpha = true;
  101005. this._groundMaterial.diffuseTexture = diffuseTexture;
  101006. };
  101007. /**
  101008. * Setup the ground mirror texture according to the specified options.
  101009. */
  101010. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101011. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101012. if (!this._groundMirror) {
  101013. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101014. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101015. this._groundMirror.anisotropicFilteringLevel = 1;
  101016. this._groundMirror.wrapU = wrapping;
  101017. this._groundMirror.wrapV = wrapping;
  101018. this._groundMirror.gammaSpace = false;
  101019. if (this._groundMirror.renderList) {
  101020. for (var i = 0; i < this._scene.meshes.length; i++) {
  101021. var mesh = this._scene.meshes[i];
  101022. if (mesh !== this._ground &&
  101023. mesh !== this._skybox &&
  101024. mesh !== this._rootMesh) {
  101025. this._groundMirror.renderList.push(mesh);
  101026. }
  101027. }
  101028. }
  101029. }
  101030. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101031. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101032. };
  101033. /**
  101034. * Setup the ground to receive the mirror texture.
  101035. */
  101036. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101037. if (this._groundMaterial) {
  101038. this._groundMaterial.reflectionTexture = this._groundMirror;
  101039. this._groundMaterial.reflectionFresnel = true;
  101040. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101041. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101042. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101043. }
  101044. };
  101045. /**
  101046. * Setup the skybox according to the specified options.
  101047. */
  101048. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101049. var _this = this;
  101050. if (!this._skybox || this._skybox.isDisposed()) {
  101051. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101052. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101053. }
  101054. this._skybox.parent = this._rootMesh;
  101055. };
  101056. /**
  101057. * Setup the skybox material according to the specified options.
  101058. */
  101059. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101060. if (!this._skybox) {
  101061. return;
  101062. }
  101063. if (!this._skyboxMaterial) {
  101064. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101065. }
  101066. this._skyboxMaterial.useRGBColor = false;
  101067. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101068. this._skyboxMaterial.enableNoise = true;
  101069. this._skybox.material = this._skyboxMaterial;
  101070. };
  101071. /**
  101072. * Setup the skybox reflection texture according to the specified options.
  101073. */
  101074. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101075. if (!this._skyboxMaterial) {
  101076. return;
  101077. }
  101078. if (this._skyboxTexture) {
  101079. return;
  101080. }
  101081. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101082. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101083. return;
  101084. }
  101085. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101086. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101087. this._skyboxTexture.gammaSpace = false;
  101088. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101089. };
  101090. /**
  101091. * Dispose all the elements created by the Helper.
  101092. */
  101093. EnvironmentHelper.prototype.dispose = function () {
  101094. if (this._groundMaterial) {
  101095. this._groundMaterial.dispose(true, true);
  101096. }
  101097. if (this._skyboxMaterial) {
  101098. this._skyboxMaterial.dispose(true, true);
  101099. }
  101100. this._rootMesh.dispose(false);
  101101. };
  101102. /**
  101103. * Default ground texture URL.
  101104. */
  101105. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101106. /**
  101107. * Default skybox texture URL.
  101108. */
  101109. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101110. /**
  101111. * Default environment texture URL.
  101112. */
  101113. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101114. return EnvironmentHelper;
  101115. }());
  101116. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101117. })(BABYLON || (BABYLON = {}));
  101118. //# sourceMappingURL=babylon.environmentHelper.js.map
  101119. var BABYLON;
  101120. (function (BABYLON) {
  101121. /**
  101122. * This class is made for on one-liner static method to help creating particle systems.
  101123. */
  101124. var ParticleHelper = /** @class */ (function () {
  101125. function ParticleHelper() {
  101126. }
  101127. /**
  101128. * This is the main static method (one-liner) of this helper to create different particle systems.
  101129. * @param type This string represents the type to the particle system to create
  101130. * @param emitter The object where the particle system will start to emit from.
  101131. * @param scene The scene where the particle system should live.
  101132. * @param gpu If the system will use gpu.
  101133. * @returns the ParticleSystem created.
  101134. */
  101135. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101136. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101137. if (gpu === void 0) { gpu = false; }
  101138. return new Promise(function (resolve, reject) {
  101139. if (!scene) {
  101140. scene = BABYLON.Engine.LastCreatedScene;
  101141. ;
  101142. }
  101143. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101144. return reject("Particle system with GPU is not supported.");
  101145. }
  101146. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101147. var newData = JSON.parse(data.toString());
  101148. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101149. }, undefined, undefined, undefined, function (req, exception) {
  101150. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101151. });
  101152. });
  101153. };
  101154. /**
  101155. * Static function used to create a new particle system from a IParticleSystemData
  101156. * @param data defines the source data
  101157. * @param scene defines the hosting scene
  101158. * @param emitter defines the particle emitter
  101159. * @returns a new ParticleSystem based on referenced data
  101160. */
  101161. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101162. // Create a particle system
  101163. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101164. // Where the particles come from
  101165. system.emitter = emitter; // the starting object, the emitter
  101166. ParticleHelper.UpdateSystem(system, data, scene);
  101167. return system;
  101168. };
  101169. /**
  101170. * Static function used to update a particle system from a IParticleSystemData
  101171. * @param system defines the particle system to update
  101172. * @param data defines the source data
  101173. * @param scene defines the hosting scene
  101174. */
  101175. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101176. // Texture of each particle
  101177. if (data.textureFile) {
  101178. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101179. }
  101180. // Colors of all particles
  101181. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101182. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101183. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101184. // Size of each particle (random between...
  101185. system.minSize = data.minSize;
  101186. system.maxSize = data.maxSize;
  101187. system.minScaleX = data.minScaleX;
  101188. system.maxScaleX = data.maxScaleX;
  101189. system.minScaleY = data.minScaleY;
  101190. system.maxScaleY = data.maxScaleY;
  101191. // Life time of each particle (random between...
  101192. system.minLifeTime = data.minLifeTime;
  101193. system.maxLifeTime = data.maxLifeTime;
  101194. // Emission rate
  101195. system.emitRate = data.emitRate;
  101196. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101197. system.blendMode = data.blendMode;
  101198. // Set the gravity of all particles
  101199. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101200. // Angular speed, in radians
  101201. system.minAngularSpeed = data.minAngularSpeed;
  101202. system.maxAngularSpeed = data.maxAngularSpeed;
  101203. // Speed
  101204. system.minEmitPower = data.minEmitPower;
  101205. system.maxEmitPower = data.maxEmitPower;
  101206. system.updateSpeed = data.updateSpeed;
  101207. switch (data.emitterType) {
  101208. case "box":
  101209. if (!data.direction1 || !data.direction2) {
  101210. throw new Error("Directions are missing in this particle system.");
  101211. }
  101212. if (!data.minEmitBox || !data.maxEmitBox) {
  101213. throw new Error("EmitBox is missing in this particle system.");
  101214. }
  101215. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101216. break;
  101217. case "sphere":
  101218. system.createSphereEmitter(data.radius);
  101219. break;
  101220. case "directed_sphere":
  101221. if (!data.direction1 || !data.direction2) {
  101222. throw new Error("Directions are missing in this particle system.");
  101223. }
  101224. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101225. break;
  101226. case "cone":
  101227. system.createConeEmitter(data.radius, data.angle);
  101228. break;
  101229. default:
  101230. break;
  101231. }
  101232. };
  101233. /**
  101234. * Static function used to export a particle system to a IParticleSystemData variable.
  101235. * Please note that texture file name is not exported and must be added manually
  101236. * @param system defines the particle system to export
  101237. */
  101238. ParticleHelper.ExportSystem = function (system) {
  101239. var outData = {};
  101240. // Colors of all particles
  101241. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101242. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101243. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101244. // Size of each particle (random between...
  101245. outData.minSize = system.minSize;
  101246. outData.maxSize = system.maxSize;
  101247. outData.minScaleX = system.minScaleX;
  101248. outData.maxScaleX = system.maxScaleX;
  101249. outData.minScaleY = system.minScaleY;
  101250. outData.maxScaleY = system.maxScaleY;
  101251. // Life time of each particle (random between...
  101252. outData.minLifeTime = system.minLifeTime;
  101253. outData.maxLifeTime = system.maxLifeTime;
  101254. // Emission rate
  101255. outData.emitRate = system.emitRate;
  101256. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101257. outData.blendMode = system.blendMode;
  101258. // Set the gravity of all particles
  101259. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101260. // Angular speed, in radians
  101261. outData.minAngularSpeed = system.minAngularSpeed;
  101262. outData.maxAngularSpeed = system.maxAngularSpeed;
  101263. // Speed
  101264. outData.minEmitPower = system.minEmitPower;
  101265. outData.maxEmitPower = system.maxEmitPower;
  101266. outData.updateSpeed = system.updateSpeed;
  101267. switch (system.particleEmitterType.getClassName()) {
  101268. case "BoxEmitter":
  101269. outData.emitterType = "box";
  101270. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101271. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101272. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101273. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101274. break;
  101275. case "SphereParticleEmitter":
  101276. outData.emitterType = "sphere";
  101277. outData.radius = system.particleEmitterType.radius;
  101278. break;
  101279. case "SphereDirectedParticleEmitter":
  101280. outData.emitterType = "directed_sphere";
  101281. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101282. outData.radius = sphereDirectedParticleEmitter.radius;
  101283. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101284. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101285. break;
  101286. case "ConeEmitter":
  101287. outData.emitterType = "cone";
  101288. outData.radius = system.particleEmitterType.radius;
  101289. outData.angle = system.particleEmitterType.angle;
  101290. break;
  101291. default:
  101292. break;
  101293. }
  101294. return outData;
  101295. };
  101296. /**
  101297. * Base Assets URL.
  101298. */
  101299. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101300. return ParticleHelper;
  101301. }());
  101302. BABYLON.ParticleHelper = ParticleHelper;
  101303. })(BABYLON || (BABYLON = {}));
  101304. //# sourceMappingURL=babylon.particleHelper.js.map
  101305. var BABYLON;
  101306. (function (BABYLON) {
  101307. /**
  101308. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101309. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101310. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101311. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101312. */
  101313. var VideoDome = /** @class */ (function (_super) {
  101314. __extends(VideoDome, _super);
  101315. /**
  101316. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101317. * @param name Element's name, child elements will append suffixes for their own names.
  101318. * @param urlsOrVideo defines the url(s) or the video element to use
  101319. * @param options An object containing optional or exposed sub element properties
  101320. */
  101321. function VideoDome(name, urlsOrVideo, options, scene) {
  101322. var _this = _super.call(this, name, scene) || this;
  101323. // set defaults and manage values
  101324. name = name || "videoDome";
  101325. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  101326. options.clickToPlay = Boolean(options.clickToPlay);
  101327. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101328. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101329. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101330. // create
  101331. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101332. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101333. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101334. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  101335. flat: false,
  101336. radius: options.size,
  101337. subdivisions: options.resolution,
  101338. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  101339. }, scene);
  101340. // configure material
  101341. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101342. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  101343. material.reflectionTexture = _this._videoTexture;
  101344. material.useEquirectangularFOV = true;
  101345. material.fovMultiplier = 1.0;
  101346. // configure mesh
  101347. _this._mesh.material = material;
  101348. _this._mesh.parent = _this;
  101349. // optional configuration
  101350. if (options.clickToPlay) {
  101351. scene.onPointerUp = function () {
  101352. _this._videoTexture.video.play();
  101353. };
  101354. }
  101355. return _this;
  101356. }
  101357. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101358. /**
  101359. * Gets the video texture being displayed on the sphere
  101360. */
  101361. get: function () {
  101362. return this._videoTexture;
  101363. },
  101364. enumerable: true,
  101365. configurable: true
  101366. });
  101367. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101368. /**
  101369. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101370. * Also see the options.resolution property.
  101371. */
  101372. get: function () {
  101373. return this._material.fovMultiplier;
  101374. },
  101375. set: function (value) {
  101376. this._material.fovMultiplier = value;
  101377. },
  101378. enumerable: true,
  101379. configurable: true
  101380. });
  101381. /**
  101382. * Releases resources associated with this node.
  101383. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101384. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101385. */
  101386. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101387. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101388. this._videoTexture.dispose();
  101389. this._mesh.dispose();
  101390. this._material.dispose();
  101391. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101392. };
  101393. return VideoDome;
  101394. }(BABYLON.Node));
  101395. BABYLON.VideoDome = VideoDome;
  101396. })(BABYLON || (BABYLON = {}));
  101397. //# sourceMappingURL=babylon.videoDome.js.map
  101398. var BABYLON;
  101399. (function (BABYLON) {
  101400. /**
  101401. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101402. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101403. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101404. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101405. */
  101406. var PhotoDome = /** @class */ (function (_super) {
  101407. __extends(PhotoDome, _super);
  101408. /**
  101409. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101410. * @param name Element's name, child elements will append suffixes for their own names.
  101411. * @param urlsOfPhoto define the url of the photo to display
  101412. * @param options An object containing optional or exposed sub element properties
  101413. */
  101414. function PhotoDome(name, urlOfPhoto, options, scene) {
  101415. var _this = _super.call(this, name, scene) || this;
  101416. // set defaults and manage values
  101417. name = name || "photoDome";
  101418. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  101419. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101420. // create
  101421. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101422. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  101423. flat: false,
  101424. radius: options.size,
  101425. subdivisions: options.resolution,
  101426. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  101427. }, scene);
  101428. // configure material
  101429. material.useEquirectangularFOV = true;
  101430. material.fovMultiplier = 1.0;
  101431. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  101432. // configure mesh
  101433. _this._mesh.material = material;
  101434. _this._mesh.parent = _this;
  101435. return _this;
  101436. }
  101437. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101438. /**
  101439. * Gets or sets the texture being displayed on the sphere
  101440. */
  101441. get: function () {
  101442. return this._photoTexture;
  101443. },
  101444. set: function (value) {
  101445. if (this._photoTexture === value) {
  101446. return;
  101447. }
  101448. this._photoTexture = value;
  101449. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101450. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  101451. this._material.reflectionTexture = this._photoTexture;
  101452. },
  101453. enumerable: true,
  101454. configurable: true
  101455. });
  101456. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101457. /**
  101458. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101459. * Also see the options.resolution property.
  101460. */
  101461. get: function () {
  101462. return this._material.fovMultiplier;
  101463. },
  101464. set: function (value) {
  101465. this._material.fovMultiplier = value;
  101466. },
  101467. enumerable: true,
  101468. configurable: true
  101469. });
  101470. /**
  101471. * Releases resources associated with this node.
  101472. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101473. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101474. */
  101475. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101476. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101477. this._photoTexture.dispose();
  101478. this._mesh.dispose();
  101479. this._material.dispose();
  101480. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101481. };
  101482. return PhotoDome;
  101483. }(BABYLON.Node));
  101484. BABYLON.PhotoDome = PhotoDome;
  101485. })(BABYLON || (BABYLON = {}));
  101486. //# sourceMappingURL=babylon.photoDome.js.map
  101487. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nvec3 worldPos=position+alignedCorner; \ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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 vec3 size;\nin vec4 color;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\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);\nvec2 cornerPos=offset*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\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 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\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 coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\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=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\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.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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 (coneAngle == 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;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,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"};
  101488. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  101489. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  101490. globalObject["BABYLON"] = BABYLON;
  101491. //backwards compatibility
  101492. if(typeof earcut !== 'undefined') {
  101493. globalObject["Earcut"] = {
  101494. earcut: earcut
  101495. };
  101496. }
  101497. return BABYLON;
  101498. });
  101499. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  101500. /***/ }),
  101501. /* 1 */
  101502. /***/ (function(module, exports, __webpack_require__) {
  101503. "use strict";
  101504. Object.defineProperty(exports, "__esModule", { value: true });
  101505. var deepmerge = __webpack_require__(21);
  101506. var expDm = deepmerge['default'];
  101507. exports.deepmerge = expDm;
  101508. /**
  101509. * Is the provided string a URL?
  101510. *
  101511. * @param urlToCheck the url to inspect
  101512. */
  101513. function isUrl(urlToCheck) {
  101514. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  101515. return true;
  101516. }
  101517. return false;
  101518. }
  101519. exports.isUrl = isUrl;
  101520. /**
  101521. * Convert a string from kebab-case to camelCase
  101522. * @param s string to convert
  101523. */
  101524. function kebabToCamel(s) {
  101525. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  101526. }
  101527. exports.kebabToCamel = kebabToCamel;
  101528. //https://gist.github.com/youssman/745578062609e8acac9f
  101529. /**
  101530. * Convert a string from camelCase to kebab-case
  101531. * @param str string to convert
  101532. */
  101533. function camelToKebab(str) {
  101534. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  101535. }
  101536. exports.camelToKebab = camelToKebab;
  101537. /**
  101538. * This will extend an object with configuration values.
  101539. * What it practically does it take the keys from the configuration and set them on the object.
  101540. * I the configuration is a tree, it will traverse into the tree.
  101541. * @param object the object to extend
  101542. * @param config the configuration object that will extend the object
  101543. */
  101544. function extendClassWithConfig(object, config) {
  101545. if (!config)
  101546. return;
  101547. Object.keys(config).forEach(function (key) {
  101548. if (key in object && typeof object[key] !== 'function') {
  101549. // if (typeof object[key] === 'function') return;
  101550. // if it is an object, iterate internally until reaching basic types
  101551. if (typeof object[key] === 'object') {
  101552. extendClassWithConfig(object[key], config[key]);
  101553. }
  101554. else {
  101555. if (config[key] !== undefined) {
  101556. object[key] = config[key];
  101557. }
  101558. }
  101559. }
  101560. });
  101561. }
  101562. exports.extendClassWithConfig = extendClassWithConfig;
  101563. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSw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UZELG9DQUVDO0FBRUQ7Ozs7OztHQU1HO0FBQ0gsK0JBQXNDLE1BQVcsRUFBRSxNQUFXO0lBQzFELElBQUksQ0FBQyxNQUFNO1FBQUUsT0FBTztJQUNwQixNQUFNLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDM0IsSUFBSSxHQUFHLElBQUksTUFBTSxJQUFJLE9BQU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  101564. /***/ }),
  101565. /* 2 */
  101566. /***/ (function(module, exports, __webpack_require__) {
  101567. "use strict";
  101568. function __export(m) {
  101569. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  101570. }
  101571. Object.defineProperty(exports, "__esModule", { value: true });
  101572. __export(__webpack_require__(31));
  101573. __export(__webpack_require__(33));
  101574. __export(__webpack_require__(39));
  101575. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  101576. /***/ }),
  101577. /* 3 */
  101578. /***/ (function(module, exports, __webpack_require__) {
  101579. "use strict";
  101580. Object.defineProperty(exports, "__esModule", { value: true });
  101581. var babylonjs_1 = __webpack_require__(0);
  101582. var _1 = __webpack_require__(1);
  101583. /**
  101584. * This is a simple HTML mapper.
  101585. * This mapper parses a single HTML element and returns the configuration from its attributes.
  101586. * it parses numbers and boolean values to the corresponding variable types.
  101587. * The following HTML element:
  101588. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  101589. *
  101590. * {
  101591. * test: 1, //a number!
  101592. * randomFlag: boolean, //camelCase and boolean
  101593. * a: {
  101594. * string: {
  101595. * object: "test" //dot-separated object levels
  101596. * }
  101597. * }
  101598. * }
  101599. */
  101600. var HTMLMapper = /** @class */ (function () {
  101601. function HTMLMapper() {
  101602. }
  101603. /**
  101604. * Map a specific element and get configuration from it
  101605. * @param element the HTML element to analyze.
  101606. */
  101607. HTMLMapper.prototype.map = function (element) {
  101608. var config = {};
  101609. var _loop_1 = function (attrIdx) {
  101610. var attr = element.attributes.item(attrIdx);
  101611. if (!attr) {
  101612. return "continue";
  101613. }
  101614. // map "object.property" to the right configuration place.
  101615. var split = attr.nodeName.split('.');
  101616. split.reduce(function (currentConfig, key, idx) {
  101617. //convert html-style to json-style
  101618. var camelKey = _1.kebabToCamel(key);
  101619. if (idx === split.length - 1) {
  101620. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  101621. if (val === "true") {
  101622. val = true;
  101623. }
  101624. else if (val === "false") {
  101625. val = false;
  101626. }
  101627. else {
  101628. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  101629. if (isnum) {
  101630. var number = parseFloat(val);
  101631. if (!isNaN(number)) {
  101632. val = number;
  101633. }
  101634. }
  101635. }
  101636. currentConfig[camelKey] = val;
  101637. }
  101638. else {
  101639. currentConfig[camelKey] = currentConfig[camelKey] || {};
  101640. }
  101641. return currentConfig[camelKey];
  101642. }, config);
  101643. };
  101644. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  101645. _loop_1(attrIdx);
  101646. }
  101647. return config;
  101648. };
  101649. return HTMLMapper;
  101650. }());
  101651. /**
  101652. * A simple string-to-JSON mapper.
  101653. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  101654. */
  101655. var JSONMapper = /** @class */ (function () {
  101656. function JSONMapper() {
  101657. }
  101658. JSONMapper.prototype.map = function (rawSource) {
  101659. return JSON.parse(rawSource);
  101660. };
  101661. return JSONMapper;
  101662. }());
  101663. /**
  101664. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  101665. * DOM elements and attributes.
  101666. */
  101667. var DOMMapper = /** @class */ (function () {
  101668. function DOMMapper() {
  101669. }
  101670. /**
  101671. * The mapping function that will convert HTML data to a viewer configuration object
  101672. * @param baseElement the baseElement from which to start traversing
  101673. * @returns a ViewerCOnfiguration object from the provided HTML Element
  101674. */
  101675. DOMMapper.prototype.map = function (baseElement) {
  101676. var htmlMapper = new HTMLMapper();
  101677. var config = htmlMapper.map(baseElement);
  101678. var traverseChildren = function (element, partConfig) {
  101679. var children = element.children;
  101680. if (children.length) {
  101681. for (var i = 0; i < children.length; ++i) {
  101682. var item = children.item(i);
  101683. // use the HTML Mapper to read configuration from a single element
  101684. var configMapped = htmlMapper.map(item);
  101685. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  101686. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  101687. partConfig[key] = [];
  101688. }
  101689. else {
  101690. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  101691. partConfig.push(configMapped);
  101692. }
  101693. else if (partConfig[key]) {
  101694. //exists already! probably an array
  101695. element.setAttribute('array', 'true');
  101696. var oldItem = partConfig[key];
  101697. partConfig = [oldItem, configMapped];
  101698. }
  101699. else {
  101700. partConfig[key] = configMapped;
  101701. }
  101702. }
  101703. traverseChildren(item, partConfig[key] || configMapped);
  101704. }
  101705. }
  101706. return partConfig;
  101707. };
  101708. traverseChildren(baseElement, config);
  101709. return config;
  101710. };
  101711. return DOMMapper;
  101712. }());
  101713. /**
  101714. * The MapperManager manages the different implemented mappers.
  101715. * It allows the user to register new mappers as well and use them to parse their own configuration data
  101716. */
  101717. var MapperManager = /** @class */ (function () {
  101718. function MapperManager() {
  101719. this._mappers = {
  101720. "html": new HTMLMapper(),
  101721. "json": new JSONMapper(),
  101722. "dom": new DOMMapper()
  101723. };
  101724. }
  101725. /**
  101726. * Get a specific configuration mapper.
  101727. *
  101728. * @param type the name of the mapper to load
  101729. */
  101730. MapperManager.prototype.getMapper = function (type) {
  101731. if (!this._mappers[type]) {
  101732. babylonjs_1.Tools.Error("No mapper defined for " + type);
  101733. }
  101734. return this._mappers[type];
  101735. };
  101736. /**
  101737. * Use this functio to register your own configuration mapper.
  101738. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  101739. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  101740. * @param mapper The implemented mapper
  101741. */
  101742. MapperManager.prototype.registerMapper = function (type, mapper) {
  101743. this._mappers[type] = mapper;
  101744. };
  101745. /**
  101746. * Dispose the mapper manager and all of its mappers.
  101747. */
  101748. MapperManager.prototype.dispose = function () {
  101749. this._mappers = {};
  101750. };
  101751. /**
  101752. * The default mapper is the JSON mapper.
  101753. */
  101754. MapperManager.DefaultMapper = 'json';
  101755. return MapperManager;
  101756. }());
  101757. exports.MapperManager = MapperManager;
  101758. /**
  101759. * mapperManager is a singleton of the type MapperManager.
  101760. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  101761. * or indirectly with using BabylonViewer.disposeAll()
  101762. */
  101763. exports.mapperManager = new Map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UFBTSxFQUFFLElBQUksVUFBVSxFQUFFO1lBQ3hCLEtBQUssRUFBRSxJQUFJLFNBQVMsRUFBRTtTQUN6QixDQUFBO0lBQ0wsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSxpQ0FBUyxHQUFoQixVQUFpQixJQUFZO1FBQ3pCLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  101765. /***/ }),
  101766. /* 4 */
  101767. /***/ (function(module, exports, __webpack_require__) {
  101768. "use strict";
  101769. Object.defineProperty(exports, "__esModule", { value: true });
  101770. var babylonjs_1 = __webpack_require__(0);
  101771. var ViewerGlobals = /** @class */ (function () {
  101772. function ViewerGlobals() {
  101773. this.disableInit = false;
  101774. this.disableWebGL2Support = false;
  101775. }
  101776. Object.defineProperty(ViewerGlobals.prototype, "version", {
  101777. get: function () {
  101778. return babylonjs_1.Engine.Version;
  101779. },
  101780. enumerable: true,
  101781. configurable: true
  101782. });
  101783. return ViewerGlobals;
  101784. }());
  101785. exports.ViewerGlobals = ViewerGlobals;
  101786. exports.viewerGlobals = new ViewerGlobals();
  101787. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  101788. /***/ }),
  101789. /* 5 */
  101790. /***/ (function(module, exports, __webpack_require__) {
  101791. "use strict";
  101792. Object.defineProperty(exports, "__esModule", { value: true });
  101793. var babylonjs_1 = __webpack_require__(0);
  101794. var modelAnimation_1 = __webpack_require__(23);
  101795. var _1 = __webpack_require__(1);
  101796. /**
  101797. * The current state of the model
  101798. */
  101799. var ModelState;
  101800. (function (ModelState) {
  101801. ModelState[ModelState["INIT"] = 0] = "INIT";
  101802. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  101803. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  101804. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  101805. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  101806. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  101807. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  101808. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  101809. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  101810. /**
  101811. * The viewer model is a container for all assets representing a sngle loaded model.
  101812. */
  101813. var ViewerModel = /** @class */ (function () {
  101814. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  101815. var _this = this;
  101816. this._observablesManager = _observablesManager;
  101817. this._configurationContainer = _configurationContainer;
  101818. /**
  101819. * the list of meshes that are a part of this model
  101820. */
  101821. this._meshes = [];
  101822. /**
  101823. * ParticleSystems connected to this model
  101824. */
  101825. this.particleSystems = [];
  101826. /**
  101827. * Skeletons defined in this model
  101828. */
  101829. this.skeletons = [];
  101830. this._loaderDone = false;
  101831. this._animatables = [];
  101832. this._frameRate = 60;
  101833. this._shadowsRenderedAfterLoad = false;
  101834. this.onLoadedObservable = new babylonjs_1.Observable();
  101835. this.onLoadErrorObservable = new babylonjs_1.Observable();
  101836. this.onLoadProgressObservable = new babylonjs_1.Observable();
  101837. this.onCompleteObservable = new babylonjs_1.Observable();
  101838. this.onAfterConfigure = new babylonjs_1.Observable();
  101839. this.state = ModelState.INIT;
  101840. var scene = this._configurationContainer && this._configurationContainer.scene;
  101841. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  101842. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  101843. this._pivotMesh.parent = this.rootMesh;
  101844. // rotate 180, gltf fun
  101845. this._pivotMesh.rotation.y += Math.PI;
  101846. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101847. this._animations = [];
  101848. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  101849. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  101850. if (this._observablesManager) {
  101851. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  101852. }
  101853. if (this._modelConfiguration.entryAnimation) {
  101854. this.rootMesh.setEnabled(false);
  101855. }
  101856. this.onLoadedObservable.add(function () {
  101857. _this.updateConfiguration(_this._modelConfiguration);
  101858. if (_this._observablesManager) {
  101859. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  101860. }
  101861. _this._initAnimations();
  101862. });
  101863. this.onCompleteObservable.add(function () {
  101864. _this.state = ModelState.COMPLETE;
  101865. });
  101866. }
  101867. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  101868. get: function () {
  101869. return this._shadowsRenderedAfterLoad;
  101870. },
  101871. set: function (rendered) {
  101872. if (!rendered) {
  101873. throw new Error("can only be enabled");
  101874. }
  101875. else {
  101876. this._shadowsRenderedAfterLoad = rendered;
  101877. }
  101878. },
  101879. enumerable: true,
  101880. configurable: true
  101881. });
  101882. ViewerModel.prototype.getViewerId = function () {
  101883. return this._configurationContainer && this._configurationContainer.viewerId;
  101884. };
  101885. Object.defineProperty(ViewerModel.prototype, "enabled", {
  101886. /**
  101887. * Is this model enabled?
  101888. */
  101889. get: function () {
  101890. return this.rootMesh.isEnabled();
  101891. },
  101892. /**
  101893. * Set whether this model is enabled or not.
  101894. */
  101895. set: function (enable) {
  101896. this.rootMesh.setEnabled(enable);
  101897. },
  101898. enumerable: true,
  101899. configurable: true
  101900. });
  101901. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  101902. set: function (done) {
  101903. this._loaderDone = done;
  101904. this._checkCompleteState();
  101905. },
  101906. enumerable: true,
  101907. configurable: true
  101908. });
  101909. ViewerModel.prototype._checkCompleteState = function () {
  101910. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  101911. this._modelComplete();
  101912. }
  101913. };
  101914. /**
  101915. * Add a mesh to this model.
  101916. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  101917. *
  101918. * @param mesh the new mesh to add
  101919. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  101920. */
  101921. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  101922. if (!mesh.parent) {
  101923. mesh.parent = this._pivotMesh;
  101924. }
  101925. mesh.receiveShadows = !!this.configuration.receiveShadows;
  101926. this._meshes.push(mesh);
  101927. if (triggerLoaded) {
  101928. return this.onLoadedObservable.notifyObserversWithPromise(this);
  101929. }
  101930. };
  101931. Object.defineProperty(ViewerModel.prototype, "meshes", {
  101932. /**
  101933. * get the list of meshes (excluding the root mesh)
  101934. */
  101935. get: function () {
  101936. return this._meshes;
  101937. },
  101938. enumerable: true,
  101939. configurable: true
  101940. });
  101941. Object.defineProperty(ViewerModel.prototype, "configuration", {
  101942. /**
  101943. * Get the model's configuration
  101944. */
  101945. get: function () {
  101946. return this._modelConfiguration;
  101947. },
  101948. /**
  101949. * (Re-)set the model's entire configuration
  101950. * @param newConfiguration the new configuration to replace the new one
  101951. */
  101952. set: function (newConfiguration) {
  101953. this._modelConfiguration = newConfiguration;
  101954. this._configureModel();
  101955. },
  101956. enumerable: true,
  101957. configurable: true
  101958. });
  101959. /**
  101960. * Update the current configuration with new values.
  101961. * Configuration will not be overwritten, but merged with the new configuration.
  101962. * Priority is to the new configuration
  101963. * @param newConfiguration the configuration to be merged into the current configuration;
  101964. */
  101965. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  101966. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  101967. this._configureModel();
  101968. };
  101969. ViewerModel.prototype._initAnimations = function () {
  101970. var _this = this;
  101971. // check if this is not a gltf loader and init the animations
  101972. if (this.skeletons.length) {
  101973. this.skeletons.forEach(function (skeleton, idx) {
  101974. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  101975. var add = false;
  101976. skeleton.getAnimatables().forEach(function (a) {
  101977. if (a.animations[0]) {
  101978. ag.addTargetedAnimation(a.animations[0], a);
  101979. add = true;
  101980. }
  101981. });
  101982. if (add) {
  101983. _this.addAnimationGroup(ag);
  101984. }
  101985. });
  101986. }
  101987. var completeCallback = function () {
  101988. };
  101989. if (this._modelConfiguration.animation) {
  101990. if (this._modelConfiguration.animation.playOnce) {
  101991. this._animations.forEach(function (a) {
  101992. a.playMode = 0 /* ONCE */;
  101993. });
  101994. }
  101995. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  101996. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  101997. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  101998. completeCallback = function () {
  101999. _this.playAnimation(animationName_1);
  102000. };
  102001. }
  102002. }
  102003. this._enterScene(completeCallback);
  102004. };
  102005. /**
  102006. * Animates the model from the current position to the default position
  102007. * @param completeCallback A function to call when the animation has completed
  102008. */
  102009. ViewerModel.prototype._enterScene = function (completeCallback) {
  102010. var _this = this;
  102011. var scene = this.rootMesh.getScene();
  102012. var previousValue = scene.animationPropertiesOverride.enableBlending;
  102013. var callback = function () {
  102014. _this.state = ModelState.ENTRYDONE;
  102015. scene.animationPropertiesOverride.enableBlending = previousValue;
  102016. _this._checkCompleteState();
  102017. if (completeCallback)
  102018. completeCallback();
  102019. };
  102020. if (!this._entryAnimation) {
  102021. callback();
  102022. return;
  102023. }
  102024. this.rootMesh.setEnabled(true);
  102025. // disable blending for the sake of the entry animation;
  102026. scene.animationPropertiesOverride.enableBlending = false;
  102027. this._applyAnimation(this._entryAnimation, true, callback);
  102028. };
  102029. /**
  102030. * Animates the model from the current position to the exit-screen position
  102031. * @param completeCallback A function to call when the animation has completed
  102032. */
  102033. ViewerModel.prototype._exitScene = function (completeCallback) {
  102034. if (!this._exitAnimation) {
  102035. completeCallback();
  102036. return;
  102037. }
  102038. this._applyAnimation(this._exitAnimation, false, completeCallback);
  102039. };
  102040. ViewerModel.prototype._modelComplete = function () {
  102041. var _this = this;
  102042. //reapply material defines to be sure:
  102043. var meshes = this._pivotMesh.getChildMeshes(false);
  102044. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102045. _this._applyModelMaterialConfiguration(mesh.material);
  102046. });
  102047. this.state = ModelState.COMPLETE;
  102048. this.onCompleteObservable.notifyObservers(this);
  102049. };
  102050. /**
  102051. * Add a new animation group to this model.
  102052. * @param animationGroup the new animation group to be added
  102053. */
  102054. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  102055. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  102056. };
  102057. /**
  102058. * Get the ModelAnimation array
  102059. */
  102060. ViewerModel.prototype.getAnimations = function () {
  102061. return this._animations;
  102062. };
  102063. /**
  102064. * Get the animations' names. Using the names you can play a specific animation.
  102065. */
  102066. ViewerModel.prototype.getAnimationNames = function () {
  102067. return this._animations.map(function (a) { return a.name; });
  102068. };
  102069. /**
  102070. * Get an animation by the provided name. Used mainly when playing n animation.
  102071. * @param name the name of the animation to find
  102072. */
  102073. ViewerModel.prototype._getAnimationByName = function (name) {
  102074. // can't use .find, noe available on IE
  102075. var filtered = this._animations.filter(function (a) { return a.name === name; });
  102076. // what the next line means - if two animations have the same name, they will not be returned!
  102077. if (filtered.length === 1) {
  102078. return filtered[0];
  102079. }
  102080. else {
  102081. return null;
  102082. }
  102083. };
  102084. /**
  102085. * Choose an initialized animation using its name and start playing it
  102086. * @param name the name of the animation to play
  102087. * @returns The model aniamtion to be played.
  102088. */
  102089. ViewerModel.prototype.playAnimation = function (name) {
  102090. var animation = this.setCurrentAnimationByName(name);
  102091. if (animation) {
  102092. animation.start();
  102093. }
  102094. return animation;
  102095. };
  102096. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  102097. var animation = this._getAnimationByName(name);
  102098. if (animation) {
  102099. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  102100. this.currentAnimation.stop();
  102101. }
  102102. this.currentAnimation = animation;
  102103. return animation;
  102104. }
  102105. else {
  102106. throw new Error("animation not found - " + name);
  102107. }
  102108. };
  102109. ViewerModel.prototype._configureModel = function () {
  102110. var _this = this;
  102111. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  102112. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  102113. var updateMeshesWithNoParent = function (variable, value, param) {
  102114. meshesWithNoParent.forEach(function (mesh) {
  102115. if (param) {
  102116. mesh[variable][param] = value;
  102117. }
  102118. else {
  102119. mesh[variable] = value;
  102120. }
  102121. });
  102122. };
  102123. var updateXYZ = function (variable, configValues) {
  102124. if (configValues.x !== undefined) {
  102125. updateMeshesWithNoParent(variable, configValues.x, 'x');
  102126. }
  102127. if (configValues.y !== undefined) {
  102128. updateMeshesWithNoParent(variable, configValues.y, 'y');
  102129. }
  102130. if (configValues.z !== undefined) {
  102131. updateMeshesWithNoParent(variable, configValues.z, 'z');
  102132. }
  102133. if (configValues.w !== undefined) {
  102134. updateMeshesWithNoParent(variable, configValues.w, 'w');
  102135. }
  102136. };
  102137. if (this._modelConfiguration.normalize) {
  102138. var center = false;
  102139. var unitSize = false;
  102140. var parentIndex = void 0;
  102141. if (this._modelConfiguration.normalize === true) {
  102142. center = true;
  102143. unitSize = true;
  102144. }
  102145. else {
  102146. center = !!this._modelConfiguration.normalize.center;
  102147. unitSize = !!this._modelConfiguration.normalize.unitSize;
  102148. parentIndex = this._modelConfiguration.normalize.parentIndex;
  102149. }
  102150. var meshesToNormalize = [];
  102151. if (parentIndex !== undefined) {
  102152. meshesToNormalize.push(this._meshes[parentIndex]);
  102153. }
  102154. else {
  102155. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  102156. }
  102157. if (unitSize) {
  102158. meshesToNormalize.forEach(function (mesh) {
  102159. mesh.normalizeToUnitCube(true);
  102160. mesh.computeWorldMatrix(true);
  102161. });
  102162. }
  102163. if (center) {
  102164. meshesToNormalize.forEach(function (mesh) {
  102165. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  102166. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  102167. var halfSizeVec = sizeVec.scale(0.5);
  102168. var center = boundingInfo.min.add(halfSizeVec);
  102169. mesh.position = center.scale(-1);
  102170. mesh.position.y += halfSizeVec.y;
  102171. // Recompute Info.
  102172. mesh.computeWorldMatrix(true);
  102173. });
  102174. }
  102175. }
  102176. else {
  102177. // if centered, should be done here
  102178. }
  102179. // position?
  102180. if (this._modelConfiguration.position) {
  102181. updateXYZ('position', this._modelConfiguration.position);
  102182. }
  102183. if (this._modelConfiguration.rotation) {
  102184. //quaternion?
  102185. if (this._modelConfiguration.rotation.w) {
  102186. meshesWithNoParent.forEach(function (mesh) {
  102187. if (!mesh.rotationQuaternion) {
  102188. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  102189. }
  102190. });
  102191. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  102192. }
  102193. else {
  102194. updateXYZ('rotation', this._modelConfiguration.rotation);
  102195. }
  102196. }
  102197. if (this._modelConfiguration.rotationOffsetAxis) {
  102198. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  102199. meshesWithNoParent.forEach(function (m) {
  102200. if (_this._modelConfiguration.rotationOffsetAngle) {
  102201. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  102202. }
  102203. });
  102204. }
  102205. if (this._modelConfiguration.scaling) {
  102206. updateXYZ('scaling', this._modelConfiguration.scaling);
  102207. }
  102208. if (this._modelConfiguration.castShadow) {
  102209. this._meshes.forEach(function (mesh) {
  102210. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  102211. });
  102212. }
  102213. var meshes = this._pivotMesh.getChildMeshes(false);
  102214. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  102215. _this._applyModelMaterialConfiguration(mesh.material);
  102216. });
  102217. if (this._modelConfiguration.entryAnimation) {
  102218. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  102219. }
  102220. if (this._modelConfiguration.exitAnimation) {
  102221. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  102222. }
  102223. this.onAfterConfigure.notifyObservers(this);
  102224. };
  102225. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  102226. var anim = {
  102227. time: 0.5
  102228. };
  102229. if (animConfig.scaling) {
  102230. anim.scaling = babylonjs_1.Vector3.Zero();
  102231. }
  102232. if (animConfig.easingFunction !== undefined) {
  102233. anim.easingFunction = animConfig.easingFunction;
  102234. }
  102235. if (animConfig.easingMode !== undefined) {
  102236. anim.easingMode = animConfig.easingMode;
  102237. }
  102238. _1.extendClassWithConfig(anim, animConfig);
  102239. return anim;
  102240. };
  102241. /**
  102242. * Apply a material configuration to a material
  102243. * @param material Material to apply configuration to
  102244. */
  102245. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  102246. if (!this._modelConfiguration.material)
  102247. return;
  102248. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  102249. if (material instanceof babylonjs_1.PBRMaterial) {
  102250. if (this._modelConfiguration.material.directIntensity !== undefined) {
  102251. material.directIntensity = this._modelConfiguration.material.directIntensity;
  102252. }
  102253. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  102254. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  102255. }
  102256. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  102257. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  102258. }
  102259. if (this._modelConfiguration.material.directEnabled !== undefined) {
  102260. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  102261. }
  102262. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  102263. material.reflectionColor = this._configurationContainer.reflectionColor;
  102264. }
  102265. }
  102266. else if (material instanceof babylonjs_1.MultiMaterial) {
  102267. for (var i = 0; i < material.subMaterials.length; i++) {
  102268. var subMaterial = material.subMaterials[i];
  102269. if (subMaterial) {
  102270. this._applyModelMaterialConfiguration(subMaterial);
  102271. }
  102272. }
  102273. }
  102274. };
  102275. /**
  102276. * Start entry/exit animation given an animation configuration
  102277. * @param animationConfiguration Entry/Exit animation configuration
  102278. * @param isEntry Pass true if the animation is an entry animation
  102279. * @param completeCallback Callback to execute when the animation completes
  102280. */
  102281. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  102282. var animations = [];
  102283. //scale
  102284. if (animationConfiguration.scaling) {
  102285. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  102286. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  102287. if (!scaleStart.equals(scaleEnd)) {
  102288. this.rootMesh.scaling = scaleStart;
  102289. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  102290. animations.push(this._scaleTransition);
  102291. }
  102292. }
  102293. //Start the animation(s)
  102294. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  102295. completeCallback(); });
  102296. };
  102297. /**
  102298. * Begin @animations with the specified @easingFunction
  102299. * @param animations The BABYLON Animations to begin
  102300. * @param duration of transition, in seconds
  102301. * @param easingFunction An easing function to apply
  102302. * @param easingMode A easing mode to apply to the easingFunction
  102303. * @param onAnimationEnd Call back trigger at the end of the animation.
  102304. */
  102305. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  102306. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  102307. if (easingFunction) {
  102308. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  102309. var animation = animations_1[_i];
  102310. easingFunction.setEasingMode(easingMode);
  102311. animation.setEasingFunction(easingFunction);
  102312. }
  102313. }
  102314. //Stop any current animations before starting the new one - merging not yet supported.
  102315. this.stopAllAnimations();
  102316. this.rootMesh.animations = animations;
  102317. if (this.rootMesh.getScene().beginAnimation) {
  102318. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  102319. if (onAnimationEnd) {
  102320. onAnimationEnd();
  102321. }
  102322. });
  102323. this._animatables.push(animatable);
  102324. }
  102325. };
  102326. /**
  102327. * Sets key values on an Animation from first to last frame.
  102328. * @param animation The Babylon animation object to set keys on
  102329. * @param startValue The value of the first key
  102330. * @param endValue The value of the last key
  102331. * @param duration The duration of the animation, used to determine the end frame
  102332. */
  102333. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  102334. animation.setKeys([
  102335. {
  102336. frame: 0,
  102337. value: startValue
  102338. },
  102339. {
  102340. frame: this._frameRate * duration,
  102341. value: endValue
  102342. }
  102343. ]);
  102344. };
  102345. /**
  102346. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  102347. * @param easingFunctionID The enum of the easing funtion to create
  102348. * @return The newly created Babylon easing function object
  102349. */
  102350. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  102351. var easingFunction;
  102352. switch (easingFunctionID) {
  102353. case 1 /* CircleEase */:
  102354. easingFunction = new babylonjs_1.CircleEase();
  102355. break;
  102356. case 2 /* BackEase */:
  102357. easingFunction = new babylonjs_1.BackEase(0.3);
  102358. break;
  102359. case 3 /* BounceEase */:
  102360. easingFunction = new babylonjs_1.BounceEase();
  102361. break;
  102362. case 4 /* CubicEase */:
  102363. easingFunction = new babylonjs_1.CubicEase();
  102364. break;
  102365. case 5 /* ElasticEase */:
  102366. easingFunction = new babylonjs_1.ElasticEase();
  102367. break;
  102368. case 6 /* ExponentialEase */:
  102369. easingFunction = new babylonjs_1.ExponentialEase();
  102370. break;
  102371. case 7 /* PowerEase */:
  102372. easingFunction = new babylonjs_1.PowerEase();
  102373. break;
  102374. case 8 /* QuadraticEase */:
  102375. easingFunction = new babylonjs_1.QuadraticEase();
  102376. break;
  102377. case 9 /* QuarticEase */:
  102378. easingFunction = new babylonjs_1.QuarticEase();
  102379. break;
  102380. case 10 /* QuinticEase */:
  102381. easingFunction = new babylonjs_1.QuinticEase();
  102382. break;
  102383. case 11 /* SineEase */:
  102384. easingFunction = new babylonjs_1.SineEase();
  102385. break;
  102386. default:
  102387. babylonjs_1.Tools.Log("No ease function found");
  102388. break;
  102389. }
  102390. return easingFunction;
  102391. };
  102392. /**
  102393. * Stops and removes all animations that have been applied to the model
  102394. */
  102395. ViewerModel.prototype.stopAllAnimations = function () {
  102396. if (this.rootMesh) {
  102397. this.rootMesh.animations = [];
  102398. }
  102399. if (this.currentAnimation) {
  102400. this.currentAnimation.stop();
  102401. }
  102402. while (this._animatables.length) {
  102403. this._animatables[0].onAnimationEnd = null;
  102404. this._animatables[0].stop();
  102405. this._animatables.shift();
  102406. }
  102407. };
  102408. /**
  102409. * Will remove this model from the viewer (but NOT dispose it).
  102410. */
  102411. ViewerModel.prototype.remove = function () {
  102412. this.stopAllAnimations();
  102413. // hide it
  102414. this.rootMesh.isVisible = false;
  102415. if (this._observablesManager) {
  102416. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  102417. }
  102418. };
  102419. /**
  102420. * Dispose this model, including all of its associated assets.
  102421. */
  102422. ViewerModel.prototype.dispose = function () {
  102423. this.remove();
  102424. this.onAfterConfigure.clear();
  102425. this.onLoadedObservable.clear();
  102426. this.onLoadErrorObservable.clear();
  102427. this.onLoadProgressObservable.clear();
  102428. if (this.loader && this.loader.name === "gltf") {
  102429. this.loader.dispose();
  102430. }
  102431. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  102432. this.particleSystems.length = 0;
  102433. this.skeletons.forEach(function (s) { return s.dispose(); });
  102434. this.skeletons.length = 0;
  102435. this._animations.forEach(function (ag) { return ag.dispose(); });
  102436. this._animations.length = 0;
  102437. this.rootMesh.dispose(false, true);
  102438. };
  102439. return ViewerModel;
  102440. }());
  102441. exports.ViewerModel = ViewerModel;
  102442. //# sourceMappingUR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FBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  102443. /***/ }),
  102444. /* 6 */
  102445. /***/ (function(module, exports, __webpack_require__) {
  102446. "use strict";
  102447. Object.defineProperty(exports, "__esModule", { value: true });
  102448. var babylonjs_1 = __webpack_require__(0);
  102449. /**
  102450. * Receives Telemetry events and raises events to the API
  102451. */
  102452. var TelemetryManager = /** @class */ (function () {
  102453. function TelemetryManager() {
  102454. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  102455. this._event = this._eventEnabled;
  102456. }
  102457. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  102458. /**
  102459. * Receives a telemetry event
  102460. * @param event The name of the Telemetry event
  102461. * @param details An additional value, or an object containing a list of property/value pairs
  102462. */
  102463. get: function () {
  102464. return this._event;
  102465. },
  102466. enumerable: true,
  102467. configurable: true
  102468. });
  102469. /**
  102470. * Log a Telemetry event for errors raised on the WebGL context.
  102471. * @param engine The Babylon engine with the WebGL context.
  102472. */
  102473. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  102474. if (!engine) {
  102475. return;
  102476. }
  102477. var logErrors = true;
  102478. while (logErrors) {
  102479. var gl = engine._gl;
  102480. if (gl && gl.getError) {
  102481. var error = gl.getError();
  102482. if (error === gl.NO_ERROR) {
  102483. logErrors = false;
  102484. }
  102485. else {
  102486. this.broadcast("WebGL Error", viewerId, { error: error });
  102487. }
  102488. }
  102489. else {
  102490. logErrors = false;
  102491. }
  102492. }
  102493. };
  102494. Object.defineProperty(TelemetryManager.prototype, "enable", {
  102495. /**
  102496. * Enable or disable telemetry events
  102497. * @param enabled Boolan, true if events are enabled
  102498. */
  102499. set: function (enabled) {
  102500. if (enabled) {
  102501. this._event = this._eventEnabled;
  102502. }
  102503. else {
  102504. this._event = this._eventDisabled;
  102505. }
  102506. },
  102507. enumerable: true,
  102508. configurable: true
  102509. });
  102510. /**
  102511. * Called on event when disabled, typically do nothing here
  102512. */
  102513. TelemetryManager.prototype._eventDisabled = function () {
  102514. // nothing to do
  102515. };
  102516. /**
  102517. * Called on event when enabled
  102518. * @param event - The name of the Telemetry event
  102519. * @param details An additional value, or an object containing a list of property/value pairs
  102520. */
  102521. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  102522. var telemetryData = {
  102523. viewerId: viewerId,
  102524. event: event,
  102525. session: this.session,
  102526. date: new Date(),
  102527. now: window.performance ? window.performance.now() : Date.now(),
  102528. detail: null
  102529. };
  102530. if (typeof details === "object") {
  102531. for (var attr in details) {
  102532. if (details.hasOwnProperty(attr)) {
  102533. telemetryData[attr] = details[attr];
  102534. }
  102535. }
  102536. }
  102537. else if (details) {
  102538. telemetryData.detail = details;
  102539. }
  102540. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  102541. };
  102542. Object.defineProperty(TelemetryManager.prototype, "session", {
  102543. /**
  102544. * Returns the current session ID or creates one if it doesn't exixt
  102545. * @return The current session ID
  102546. */
  102547. get: function () {
  102548. if (!this._currentSessionId) {
  102549. //String + Timestamp + Random Integer
  102550. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  102551. }
  102552. return this._currentSessionId;
  102553. },
  102554. enumerable: true,
  102555. configurable: true
  102556. });
  102557. /**
  102558. * Disposes the telemetry manager
  102559. */
  102560. TelemetryManager.prototype.dispose = function () {
  102561. this.onEventBroadcastedObservable.clear();
  102562. delete this.onEventBroadcastedObservable;
  102563. };
  102564. return TelemetryManager;
  102565. }());
  102566. exports.TelemetryManager = TelemetryManager;
  102567. exports.telemetry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UU7b0JBQzlCLGFBQWEsQ0FBQyxJQUFJLENBQUMsR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7aUJBQ3ZDO2FBQ0o7U0FDSjthQUFNLElBQUksT0FBTyxFQUFFO1lBQ2hCLGFBQWEsQ0FBQyxNQUFNLEdBQUcsT0FBTyxDQUFDO1NBQ2xDO1FBRUQsSUFBSSxDQUFDLDRCQUE0QixDQUFDLGVBQWUsQ0FBQyxhQUFhLENBQUMsQ0FBQztJQUNyRSxDQUFDO0lBTUQsc0JBQVcscUNBQU87UUFKbEI7OztXQUdHO2FBQ0g7WUFDSSxJQUFJLENBQUMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  102569. /***/ }),
  102570. /* 7 */
  102571. /***/ (function(module, exports, __webpack_require__) {
  102572. "use strict";
  102573. Object.defineProperty(exports, "__esModule", { value: true });
  102574. var babylonjs_1 = __webpack_require__(0);
  102575. /**
  102576. * The viewer manager is the container for all viewers currently registered on this page.
  102577. * It is possible to have more than one viewer on a single page.
  102578. */
  102579. var ViewerManager = /** @class */ (function () {
  102580. function ViewerManager() {
  102581. this._viewers = {};
  102582. this.onViewerAddedObservable = new babylonjs_1.Observable();
  102583. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  102584. }
  102585. /**
  102586. * Adding a new viewer to the viewer manager and start tracking it.
  102587. * @param viewer the viewer to add
  102588. */
  102589. ViewerManager.prototype.addViewer = function (viewer) {
  102590. this._viewers[viewer.getBaseId()] = viewer;
  102591. this._onViewerAdded(viewer);
  102592. };
  102593. /**
  102594. * remove a viewer from the viewer manager
  102595. * @param viewer the viewer to remove
  102596. */
  102597. ViewerManager.prototype.removeViewer = function (viewer) {
  102598. var id = viewer.getBaseId();
  102599. delete this._viewers[id];
  102600. this.onViewerRemovedObservable.notifyObservers(id);
  102601. };
  102602. /**
  102603. * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned)
  102604. * @param id the id of the HTMl element (or the viewer's, if none provided)
  102605. */
  102606. ViewerManager.prototype.getViewerById = function (id) {
  102607. return this._viewers[id];
  102608. };
  102609. /**
  102610. * Get a viewer using a container element
  102611. * @param element the HTML element to search viewers associated with
  102612. */
  102613. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  102614. for (var id in this._viewers) {
  102615. if (this._viewers[id].containerElement === element) {
  102616. return this.getViewerById(id);
  102617. }
  102618. }
  102619. };
  102620. /**
  102621. * Get a promise that will fullfil when this viewer was initialized.
  102622. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  102623. * you will get the viewer after everything was already configured.
  102624. * @param id the viewer id to find
  102625. */
  102626. ViewerManager.prototype.getViewerPromiseById = function (id) {
  102627. var _this = this;
  102628. return new Promise(function (resolve, reject) {
  102629. var localViewer = _this.getViewerById(id);
  102630. if (localViewer) {
  102631. return resolve(localViewer);
  102632. }
  102633. var viewerFunction = function (viewer) {
  102634. if (viewer.getBaseId() === id) {
  102635. resolve(viewer);
  102636. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  102637. }
  102638. };
  102639. _this.onViewerAddedObservable.add(viewerFunction);
  102640. });
  102641. };
  102642. ViewerManager.prototype._onViewerAdded = function (viewer) {
  102643. this.onViewerAdded && this.onViewerAdded(viewer);
  102644. this.onViewerAddedObservable.notifyObservers(viewer);
  102645. };
  102646. /**
  102647. * dispose the manager and all of its associated viewers
  102648. */
  102649. ViewerManager.prototype.dispose = function () {
  102650. delete this._onViewerAdded;
  102651. for (var id in this._viewers) {
  102652. this._viewers[id].dispose();
  102653. }
  102654. this.onViewerAddedObservable.clear();
  102655. this.onViewerRemovedObservable.clear();
  102656. };
  102657. return ViewerManager;
  102658. }());
  102659. exports.ViewerManager = ViewerManager;
  102660. exports.viewerManager = new ViewerManager();
  102661. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQUFDLEN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strict";
  102666. var __extends = (this && this.__extends) || (function () {
  102667. var extendStatics = Object.setPrototypeOf ||
  102668. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  102669. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  102670. return function (d, b) {
  102671. extendStatics(d, b);
  102672. function __() { this.constructor = d; }
  102673. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  102674. };
  102675. })();
  102676. Object.defineProperty(exports, "__esModule", { value: true });
  102677. var viewer_1 = __webpack_require__(9);
  102678. var babylonjs_1 = __webpack_require__(0);
  102679. /**
  102680. * The Default viewer is the default implementation of the AbstractViewer.
  102681. * It uses the templating system to render a new canvas and controls.
  102682. */
  102683. var DefaultViewer = /** @class */ (function (_super) {
  102684. __extends(DefaultViewer, _super);
  102685. /**
  102686. * Create a new default viewer
  102687. * @param containerElement the element in which the templates will be rendered
  102688. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  102689. */
  102690. function DefaultViewer(containerElement, initialConfiguration) {
  102691. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  102692. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  102693. _this.containerElement = containerElement;
  102694. _this._handlePointerDown = function (event) {
  102695. var pointerDown = event.event;
  102696. if (pointerDown.button !== 0)
  102697. return;
  102698. var element = event.event.target;
  102699. if (!element) {
  102700. return;
  102701. }
  102702. var parentClasses = element.parentElement.classList;
  102703. var elementClasses = element.classList;
  102704. var elementName = "";
  102705. 0;
  102706. for (var i = 0; i < elementClasses.length; ++i) {
  102707. var className = elementClasses[i];
  102708. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  102709. elementName = className;
  102710. break;
  102711. }
  102712. }
  102713. switch (elementName) {
  102714. case "speed-button":
  102715. case "types-button":
  102716. if (parentClasses.contains("open")) {
  102717. parentClasses.remove("open");
  102718. }
  102719. else {
  102720. parentClasses.add("open");
  102721. }
  102722. break;
  102723. case "play-pause-button":
  102724. _this._togglePlayPause();
  102725. break;
  102726. case "label-option-button":
  102727. var label = element.dataset["value"];
  102728. if (label) {
  102729. _this._updateAnimationType(label);
  102730. }
  102731. break;
  102732. case "speed-option-button":
  102733. if (!_this._currentAnimation) {
  102734. return;
  102735. }
  102736. var speed = element.dataset["value"];
  102737. if (speed)
  102738. _this._updateAnimationSpeed(speed);
  102739. break;
  102740. case "progress-wrapper":
  102741. _this._resumePlay = !_this._isAnimationPaused;
  102742. if (_this._resumePlay) {
  102743. _this._togglePlayPause(true);
  102744. }
  102745. break;
  102746. case "fullscreen-button":
  102747. _this.toggleFullscreen();
  102748. break;
  102749. case "hd-button":
  102750. _this.toggleHD();
  102751. break;
  102752. default:
  102753. return;
  102754. }
  102755. };
  102756. /**
  102757. * Plays or Pauses animation
  102758. */
  102759. _this._togglePlayPause = function (noUiUpdate) {
  102760. if (!_this._currentAnimation) {
  102761. return;
  102762. }
  102763. if (_this._isAnimationPaused) {
  102764. _this._currentAnimation.restart();
  102765. }
  102766. else {
  102767. _this._currentAnimation.pause();
  102768. }
  102769. _this._isAnimationPaused = !_this._isAnimationPaused;
  102770. if (noUiUpdate)
  102771. return;
  102772. var navbar = _this.templateManager.getTemplate('navBar');
  102773. if (!navbar)
  102774. return;
  102775. navbar.updateParams({
  102776. paused: _this._isAnimationPaused,
  102777. });
  102778. };
  102779. /**
  102780. * Control progress bar position based on animation current frame
  102781. */
  102782. _this._updateProgressBar = function () {
  102783. var navbar = _this.templateManager.getTemplate('navBar');
  102784. if (!navbar)
  102785. return;
  102786. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  102787. if (progressSlider && _this._currentAnimation) {
  102788. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  102789. var currentValue = progressSlider.valueAsNumber;
  102790. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  102791. progressSlider.value = '' + progress;
  102792. }
  102793. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  102794. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  102795. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  102796. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  102797. }
  102798. }
  102799. else {
  102800. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  102801. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  102802. _this._oldIdleRotationValue = 0;
  102803. }
  102804. }
  102805. }
  102806. };
  102807. /**
  102808. * Update Current Animation Speed
  102809. */
  102810. _this._updateAnimationSpeed = function (speed, paramsObject) {
  102811. var navbar = _this.templateManager.getTemplate('navBar');
  102812. if (!navbar)
  102813. return;
  102814. if (speed && _this._currentAnimation) {
  102815. _this._currentAnimation.speedRatio = parseFloat(speed);
  102816. if (!_this._isAnimationPaused) {
  102817. _this._currentAnimation.restart();
  102818. }
  102819. if (paramsObject) {
  102820. paramsObject.selectedSpeed = speed + "x";
  102821. }
  102822. else {
  102823. navbar.updateParams({
  102824. selectedSpeed: speed + "x",
  102825. });
  102826. }
  102827. }
  102828. };
  102829. /**
  102830. * Update Current Animation Type
  102831. */
  102832. _this._updateAnimationType = function (label, paramsObject) {
  102833. var navbar = _this.templateManager.getTemplate('navBar');
  102834. if (!navbar)
  102835. return;
  102836. if (label) {
  102837. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  102838. }
  102839. if (paramsObject) {
  102840. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  102841. paramsObject.selectedAnimationName = label;
  102842. }
  102843. else {
  102844. navbar.updateParams({
  102845. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  102846. selectedAnimationName: label
  102847. });
  102848. }
  102849. _this._updateAnimationSpeed("1.0", paramsObject);
  102850. };
  102851. /**
  102852. * Toggle fullscreen of the entire viewer
  102853. */
  102854. _this.toggleFullscreen = function () {
  102855. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  102856. var viewerElement = viewerTemplate && viewerTemplate.parent;
  102857. if (viewerElement) {
  102858. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  102859. if (!fullscreenElement) {
  102860. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  102861. requestFullScreen.call(viewerElement);
  102862. }
  102863. else {
  102864. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  102865. exitFullscreen.call(document);
  102866. }
  102867. }
  102868. };
  102869. _this._onModelLoaded = function (model) {
  102870. _this._configureTemplate(model);
  102871. // with a short timeout, making sure everything is there already.
  102872. var hideLoadingDelay = 20;
  102873. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  102874. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  102875. }
  102876. setTimeout(function () {
  102877. _this.sceneManager.scene.executeWhenReady(function () {
  102878. _this.hideLoadingScreen();
  102879. });
  102880. }, hideLoadingDelay);
  102881. return;
  102882. };
  102883. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  102884. _this.onModelRemovedObservable.add(function () {
  102885. _this._configureTemplate();
  102886. });
  102887. _this.onEngineInitObservable.add(function () {
  102888. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  102889. _this._configureLights(data.newConfiguration, data.model);
  102890. });
  102891. });
  102892. return _this;
  102893. }
  102894. /**
  102895. * This will be executed when the templates initialize.
  102896. */
  102897. DefaultViewer.prototype._onTemplatesLoaded = function () {
  102898. var _this = this;
  102899. this.showLoadingScreen();
  102900. // navbar
  102901. this._initNavbar();
  102902. // close overlay button
  102903. var template = this.templateManager.getTemplate('overlay');
  102904. if (template) {
  102905. var closeButton = template.parent.querySelector('.close-button');
  102906. if (closeButton) {
  102907. closeButton.addEventListener('pointerdown', function () {
  102908. _this.hideOverlayScreen();
  102909. });
  102910. }
  102911. }
  102912. if (this.configuration.templates && this.configuration.templates.viewer) {
  102913. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  102914. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  102915. }, function () {
  102916. }, function () {
  102917. }, function () {
  102918. }, function () {
  102919. }, function (file) {
  102920. _this.loadModel(file);
  102921. }, function () {
  102922. });
  102923. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  102924. }
  102925. }
  102926. return _super.prototype._onTemplatesLoaded.call(this);
  102927. };
  102928. DefaultViewer.prototype._dropped = function (evt) {
  102929. };
  102930. DefaultViewer.prototype._initNavbar = function () {
  102931. var _this = this;
  102932. var navbar = this.templateManager.getTemplate('navBar');
  102933. if (navbar) {
  102934. this.onFrameRenderedObservable.add(this._updateProgressBar);
  102935. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  102936. // an example how to trigger the help button. publiclly available
  102937. this.templateManager.eventManager.registerCallback("navBar", function () {
  102938. // do your thing
  102939. }, "pointerdown", ".help-button");
  102940. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  102941. var evt = event.event;
  102942. var element = (evt.target);
  102943. if (!_this._currentAnimation)
  102944. return;
  102945. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  102946. if (isNaN(gotoFrame))
  102947. return;
  102948. _this._currentAnimation.goToFrame(gotoFrame);
  102949. }, "input");
  102950. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  102951. if (_this._resumePlay) {
  102952. _this._togglePlayPause(true);
  102953. }
  102954. _this._resumePlay = false;
  102955. }, "pointerup", ".progress-wrapper");
  102956. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  102957. navbar.updateParams({
  102958. hideHdButton: true
  102959. });
  102960. }
  102961. }
  102962. };
  102963. DefaultViewer.prototype.toggleHD = function () {
  102964. _super.prototype.toggleHD.call(this);
  102965. // update UI element
  102966. var navbar = this.templateManager.getTemplate('navBar');
  102967. if (!navbar)
  102968. return;
  102969. if (navbar.configuration.params) {
  102970. navbar.configuration.params.hdEnabled = this._hdToggled;
  102971. }
  102972. var span = navbar.parent.querySelector("button.hd-button span");
  102973. if (span) {
  102974. span.classList.remove(this._hdToggled ? "hd-icon" : "sd-icon");
  102975. span.classList.add(!this._hdToggled ? "hd-icon" : "sd-icon");
  102976. }
  102977. };
  102978. /**
  102979. * Preparing the container element to present the viewer
  102980. */
  102981. DefaultViewer.prototype._prepareContainerElement = function () {
  102982. this.containerElement.style.position = 'relative';
  102983. this.containerElement.style.height = '100%';
  102984. this.containerElement.style.display = 'flex';
  102985. };
  102986. /**
  102987. * This function will configure the templates and update them after a model was loaded
  102988. * It is mainly responsible to changing the title and subtitle etc'.
  102989. * @param model the model to be used to configure the templates by
  102990. */
  102991. DefaultViewer.prototype._configureTemplate = function (model) {
  102992. var navbar = this.templateManager.getTemplate('navBar');
  102993. if (!navbar)
  102994. return;
  102995. var newParams = navbar.configuration.params || {};
  102996. if (!model) {
  102997. newParams.animations = null;
  102998. }
  102999. else {
  103000. var animationNames = model.getAnimationNames();
  103001. newParams.animations = animationNames;
  103002. if (animationNames.length) {
  103003. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  103004. this._animationList = animationNames;
  103005. newParams.paused = this._isAnimationPaused;
  103006. var animationIndex = 0;
  103007. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  103008. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  103009. if (animationIndex === -1) {
  103010. animationIndex = 0;
  103011. }
  103012. }
  103013. this._updateAnimationType(animationNames[animationIndex], newParams);
  103014. }
  103015. else {
  103016. newParams.animations = null;
  103017. }
  103018. if (model.configuration.thumbnail) {
  103019. newParams.logoImage = model.configuration.thumbnail;
  103020. }
  103021. }
  103022. navbar.updateParams(newParams, false);
  103023. };
  103024. /**
  103025. * This will load a new model to the default viewer
  103026. * overriding the AbstractViewer's loadModel.
  103027. * The scene will automatically be cleared of the old models, if exist.
  103028. * @param model the configuration object (or URL) to load.
  103029. */
  103030. DefaultViewer.prototype.loadModel = function (model) {
  103031. var _this = this;
  103032. if (!model) {
  103033. model = this.configuration.model;
  103034. }
  103035. this.showLoadingScreen();
  103036. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  103037. console.log(error);
  103038. _this.hideLoadingScreen();
  103039. _this.showOverlayScreen('error');
  103040. return Promise.reject(error);
  103041. });
  103042. };
  103043. /**
  103044. * Show the overlay and the defined sub-screen.
  103045. * Mainly used for help and errors
  103046. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  103047. */
  103048. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  103049. var _this = this;
  103050. var template = this.templateManager.getTemplate('overlay');
  103051. if (!template)
  103052. return Promise.resolve('Overlay template not found');
  103053. return template.show((function (template) {
  103054. var canvasRect = _this.containerElement.getBoundingClientRect();
  103055. template.parent.style.display = 'flex';
  103056. template.parent.style.width = canvasRect.width + "px";
  103057. template.parent.style.height = canvasRect.height + "px";
  103058. template.parent.style.opacity = "1";
  103059. var subTemplate = _this.templateManager.getTemplate(subScreen);
  103060. if (!subTemplate) {
  103061. return Promise.reject(subScreen + ' template not found');
  103062. }
  103063. return subTemplate.show((function (template) {
  103064. template.parent.style.display = 'flex';
  103065. return Promise.resolve(template);
  103066. }));
  103067. }));
  103068. };
  103069. /**
  103070. * Hide the overlay screen.
  103071. */
  103072. DefaultViewer.prototype.hideOverlayScreen = function () {
  103073. var template = this.templateManager.getTemplate('overlay');
  103074. if (!template)
  103075. return Promise.resolve('Overlay template not found');
  103076. return template.hide((function (template) {
  103077. template.parent.style.opacity = "0";
  103078. var onTransitionEnd = function () {
  103079. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103080. template.parent.style.display = 'none';
  103081. };
  103082. template.parent.addEventListener("transitionend", onTransitionEnd);
  103083. var overlays = template.parent.querySelectorAll('.overlay');
  103084. if (overlays) {
  103085. for (var i = 0; i < overlays.length; ++i) {
  103086. var htmlElement = overlays.item(i);
  103087. htmlElement.style.display = 'none';
  103088. }
  103089. }
  103090. return Promise.resolve(template);
  103091. }));
  103092. };
  103093. /**
  103094. * show the viewer (in case it was hidden)
  103095. *
  103096. * @param visibilityFunction an optional function to execute in order to show the container
  103097. */
  103098. DefaultViewer.prototype.show = function (visibilityFunction) {
  103099. var template = this.templateManager.getTemplate('main');
  103100. //not possible, but yet:
  103101. if (!template)
  103102. return Promise.reject('Main template not found');
  103103. return template.show(visibilityFunction);
  103104. };
  103105. /**
  103106. * hide the viewer (in case it is visible)
  103107. *
  103108. * @param visibilityFunction an optional function to execute in order to hide the container
  103109. */
  103110. DefaultViewer.prototype.hide = function (visibilityFunction) {
  103111. var template = this.templateManager.getTemplate('main');
  103112. //not possible, but yet:
  103113. if (!template)
  103114. return Promise.reject('Main template not found');
  103115. return template.hide(visibilityFunction);
  103116. };
  103117. /**
  103118. * Show the loading screen.
  103119. * The loading screen can be configured using the configuration object
  103120. */
  103121. DefaultViewer.prototype.showLoadingScreen = function () {
  103122. var _this = this;
  103123. var template = this.templateManager.getTemplate('loadingScreen');
  103124. if (!template)
  103125. return Promise.resolve('Loading Screen template not found');
  103126. return template.show((function (template) {
  103127. var canvasRect = _this.containerElement.getBoundingClientRect();
  103128. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  103129. template.parent.style.display = 'flex';
  103130. template.parent.style.width = canvasRect.width + "px";
  103131. template.parent.style.height = canvasRect.height + "px";
  103132. template.parent.style.opacity = "1";
  103133. // from the configuration!!!
  103134. var color = "black";
  103135. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  103136. color = (_this.configuration.templates.loadingScreen.params &&
  103137. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  103138. }
  103139. template.parent.style.backgroundColor = color;
  103140. return Promise.resolve(template);
  103141. }));
  103142. };
  103143. /**
  103144. * Hide the loading screen
  103145. */
  103146. DefaultViewer.prototype.hideLoadingScreen = function () {
  103147. var template = this.templateManager.getTemplate('loadingScreen');
  103148. if (!template)
  103149. return Promise.resolve('Loading Screen template not found');
  103150. return template.hide((function (template) {
  103151. template.parent.style.opacity = "0";
  103152. var onTransitionEnd = function () {
  103153. template.parent.removeEventListener("transitionend", onTransitionEnd);
  103154. template.parent.style.display = 'none';
  103155. };
  103156. template.parent.addEventListener("transitionend", onTransitionEnd);
  103157. return Promise.resolve(template);
  103158. }));
  103159. };
  103160. DefaultViewer.prototype.dispose = function () {
  103161. this.templateManager.dispose();
  103162. _super.prototype.dispose.call(this);
  103163. };
  103164. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  103165. var _this = this;
  103166. _super.prototype._onConfigurationLoaded.call(this, configuration);
  103167. // initialize the templates
  103168. var templateConfiguration = this.configuration.templates || {};
  103169. this.templateManager.initTemplate(templateConfiguration);
  103170. // when done, execute onTemplatesLoaded()
  103171. this.templateManager.onAllLoaded.add(function () {
  103172. var canvas = _this.templateManager.getCanvas();
  103173. if (canvas) {
  103174. _this._canvas = canvas;
  103175. }
  103176. _this._onTemplateLoaded();
  103177. });
  103178. };
  103179. /**
  103180. * An extension of the light configuration of the abstract viewer.
  103181. * @param lightsConfiguration the light configuration to use
  103182. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  103183. */
  103184. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  103185. var _this = this;
  103186. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  103187. // labs feature - flashlight
  103188. if (this.configuration.lab && this.configuration.lab.flashlight) {
  103189. var pointerPosition = babylonjs_1.Vector3.Zero();
  103190. var lightTarget_1;
  103191. var angle = 0.5;
  103192. var exponent = Math.PI / 2;
  103193. if (typeof this.configuration.lab.flashlight === "object") {
  103194. exponent = this.configuration.lab.flashlight.exponent || exponent;
  103195. angle = this.configuration.lab.flashlight.angle || angle;
  103196. }
  103197. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  103198. if (typeof this.configuration.lab.flashlight === "object") {
  103199. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  103200. if (this.configuration.lab.flashlight.diffuse) {
  103201. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  103202. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  103203. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  103204. }
  103205. if (this.configuration.lab.flashlight.specular) {
  103206. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  103207. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  103208. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  103209. }
  103210. }
  103211. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  103212. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  103213. if (eventData.type === 4 && eventData.pickInfo) {
  103214. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  103215. }
  103216. else {
  103217. lightTarget_1 = undefined;
  103218. }
  103219. });
  103220. var updateFlashlightFunction = function () {
  103221. if (_this.sceneManager.camera && flashlight) {
  103222. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  103223. if (lightTarget_1) {
  103224. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  103225. }
  103226. }
  103227. };
  103228. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  103229. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  103230. }
  103231. };
  103232. return DefaultViewer;
  103233. }(viewer_1.AbstractViewer));
  103234. exports.DefaultViewer = DefaultViewer;
  103235. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3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UFBSSxVQUFVLEVBQUU7b0JBQ3hDLFVBQVUsQ0FBQyxRQUFRLENBQUMsUUFBUSxDQUFDLEtBQUksQ0FBQyxZQUFZLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxDQUFDO29CQUNoRSxJQUFJLGFBQVcsRUFBRTt3QkFDYixhQUFXLENBQUMsYUFBYSxDQUFDLFVBQVUsQ0FBQyxRQUFRLEVBQUUsVUFBVSxDQUFDLFNBQVMsQ0FBQyxDQUFDO3FCQUN4RTtpQkFDSjtZQUNMLENBQUMsQ0FBQTtZQUNELElBQUksQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixDQUFDLHdCQUF3QixDQUFDLENBQUM7WUFDdkUsSUFBSSxDQUFDLGtDQUFrQyxDQUFDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO1NBQzFFO0lBQ0wsQ0FBQztJQUNMLG9CQUFDO0FBQUQsQ0FBQyxBQXJsQkQsQ0FBbUMsdUJBQWMsR0FxbEJoRDtBQXJsQlksc0NBQWEifQ==
  103236. /***/ }),
  103237. /* 9 */
  103238. /***/ (function(module, exports, __webpack_require__) {
  103239. "use strict";
  103240. Object.defineProperty(exports, "__esModule", { value: true });
  103241. var viewerManager_1 = __webpack_require__(7);
  103242. var sceneManager_1 = __webpack_require__(22);
  103243. var loader_1 = __webpack_require__(28);
  103244. var babylonjs_1 = __webpack_require__(0);
  103245. var modelLoader_1 = __webpack_require__(13);
  103246. var globals_1 = __webpack_require__(4);
  103247. var telemetryManager_1 = __webpack_require__(6);
  103248. var _1 = __webpack_require__(1);
  103249. var observablesManager_1 = __webpack_require__(59);
  103250. var configurationContainer_1 = __webpack_require__(60);
  103251. var templateManager_1 = __webpack_require__(61);
  103252. /**
  103253. * The AbstractViewr is the center of Babylon's viewer.
  103254. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  103255. */
  103256. var AbstractViewer = /** @class */ (function () {
  103257. function AbstractViewer(containerElement, initialConfiguration) {
  103258. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  103259. var _this = this;
  103260. this.containerElement = containerElement;
  103261. /**
  103262. * A flag that controls whether or not the render loop should be executed
  103263. */
  103264. this.runRenderLoop = true;
  103265. /**
  103266. * is this viewer disposed?
  103267. */
  103268. this._isDisposed = false;
  103269. this._hdToggled = false;
  103270. /**
  103271. * The resize function that will be registered with the window object
  103272. */
  103273. this._resize = function () {
  103274. // Only resize if Canvas is in the DOM
  103275. if (!_this.isCanvasInDOM()) {
  103276. return;
  103277. }
  103278. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  103279. return;
  103280. }
  103281. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  103282. return;
  103283. }
  103284. _this.engine.resize();
  103285. };
  103286. /**
  103287. * render loop that will be executed by the engine
  103288. */
  103289. this._render = function (force) {
  103290. if (force === void 0) { force = false; }
  103291. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  103292. if (_this.runRenderLoop || force) {
  103293. _this.engine.performanceMonitor.enable();
  103294. _this.sceneManager.scene.render();
  103295. _this.onFrameRenderedObservable.notifyObservers(_this);
  103296. }
  103297. else {
  103298. _this.engine.performanceMonitor.disable();
  103299. // update camera instead of rendering
  103300. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  103301. }
  103302. }
  103303. };
  103304. // if exists, use the container id. otherwise, generate a random string.
  103305. if (containerElement.id) {
  103306. this.baseId = containerElement.id;
  103307. }
  103308. else {
  103309. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  103310. }
  103311. this._registeredOnBeforeRenderFunctions = [];
  103312. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  103313. // add this viewer to the viewer manager
  103314. viewerManager_1.viewerManager.addViewer(this);
  103315. this.observablesManager = new observablesManager_1.ObservablesManager();
  103316. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  103317. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  103318. // extend the configuration
  103319. this._configurationLoader = new loader_1.ConfigurationLoader();
  103320. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  103321. _this._onConfigurationLoaded(configuration);
  103322. });
  103323. this.onSceneInitObservable.add(function () {
  103324. _this.updateConfiguration();
  103325. });
  103326. this.onInitDoneObservable.add(function () {
  103327. _this._isInit = true;
  103328. _this.engine.runRenderLoop(_this._render);
  103329. });
  103330. this._prepareContainerElement();
  103331. }
  103332. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  103333. // observables
  103334. /**
  103335. * Will notify when the scene was initialized
  103336. */
  103337. get: function () {
  103338. return this.observablesManager.onSceneInitObservable;
  103339. },
  103340. enumerable: true,
  103341. configurable: true
  103342. });
  103343. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  103344. /**
  103345. * will notify when the engine was initialized
  103346. */
  103347. get: function () {
  103348. return this.observablesManager.onEngineInitObservable;
  103349. },
  103350. enumerable: true,
  103351. configurable: true
  103352. });
  103353. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  103354. /**
  103355. * Will notify when a new model was added to the scene.
  103356. * Note that added does not neccessarily mean loaded!
  103357. */
  103358. get: function () {
  103359. return this.observablesManager.onModelAddedObservable;
  103360. },
  103361. enumerable: true,
  103362. configurable: true
  103363. });
  103364. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  103365. /**
  103366. * will notify after every model load
  103367. */
  103368. get: function () {
  103369. return this.observablesManager.onModelLoadedObservable;
  103370. },
  103371. enumerable: true,
  103372. configurable: true
  103373. });
  103374. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  103375. /**
  103376. * will notify when any model notify of progress
  103377. */
  103378. get: function () {
  103379. return this.observablesManager.onModelLoadProgressObservable;
  103380. },
  103381. enumerable: true,
  103382. configurable: true
  103383. });
  103384. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  103385. /**
  103386. * will notify when any model load failed.
  103387. */
  103388. get: function () {
  103389. return this.observablesManager.onModelLoadErrorObservable;
  103390. },
  103391. enumerable: true,
  103392. configurable: true
  103393. });
  103394. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  103395. /**
  103396. * Will notify when a model was removed from the scene;
  103397. */
  103398. get: function () {
  103399. return this.observablesManager.onModelRemovedObservable;
  103400. },
  103401. enumerable: true,
  103402. configurable: true
  103403. });
  103404. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  103405. /**
  103406. * will notify when a new loader was initialized.
  103407. * Used mainly to know when a model starts loading.
  103408. */
  103409. get: function () {
  103410. return this.observablesManager.onLoaderInitObservable;
  103411. },
  103412. enumerable: true,
  103413. configurable: true
  103414. });
  103415. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  103416. /**
  103417. * Observers registered here will be executed when the entire load process has finished.
  103418. */
  103419. get: function () {
  103420. return this.observablesManager.onViewerInitDoneObservable;
  103421. },
  103422. enumerable: true,
  103423. configurable: true
  103424. });
  103425. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  103426. /**
  103427. * Functions added to this observable will be executed on each frame rendered.
  103428. */
  103429. get: function () {
  103430. return this.observablesManager.onFrameRenderedObservable;
  103431. },
  103432. enumerable: true,
  103433. configurable: true
  103434. });
  103435. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  103436. /**
  103437. * The (single) canvas of this viewer
  103438. */
  103439. get: function () {
  103440. return this._canvas;
  103441. },
  103442. enumerable: true,
  103443. configurable: true
  103444. });
  103445. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  103446. get: function () {
  103447. return this._configurationContainer;
  103448. },
  103449. enumerable: true,
  103450. configurable: true
  103451. });
  103452. /**
  103453. * get the baseId of this viewer
  103454. */
  103455. AbstractViewer.prototype.getBaseId = function () {
  103456. return this.baseId;
  103457. };
  103458. /**
  103459. * Do we have a canvas to render on, and is it a part of the scene
  103460. */
  103461. AbstractViewer.prototype.isCanvasInDOM = function () {
  103462. return !!this._canvas && !!this._canvas.parentElement;
  103463. };
  103464. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  103465. /**
  103466. * Is the engine currently set to rende even when the page is in background
  103467. */
  103468. get: function () {
  103469. return this.engine && this.engine.renderEvenInBackground;
  103470. },
  103471. /**
  103472. * Set the viewer's background rendering flag.
  103473. */
  103474. set: function (value) {
  103475. if (this.engine) {
  103476. this.engine.renderEvenInBackground = value;
  103477. }
  103478. },
  103479. enumerable: true,
  103480. configurable: true
  103481. });
  103482. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  103483. /**
  103484. * Get the configuration object. This is a reference only.
  103485. * The configuration can ONLY be updated using the updateConfiguration function.
  103486. * changing this object will have no direct effect on the scene.
  103487. */
  103488. get: function () {
  103489. return this._configurationContainer.configuration;
  103490. },
  103491. enumerable: true,
  103492. configurable: true
  103493. });
  103494. /**
  103495. * force resizing the engine.
  103496. */
  103497. AbstractViewer.prototype.forceResize = function () {
  103498. this._resize();
  103499. };
  103500. AbstractViewer.prototype.toggleHD = function () {
  103501. this._hdToggled = !this._hdToggled;
  103502. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  103503. this.engine.setHardwareScalingLevel(scale);
  103504. };
  103505. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  103506. var _this = this;
  103507. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  103508. if (this.configuration.observers) {
  103509. this._configureObservers(this.configuration.observers);
  103510. }
  103511. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  103512. if (this.configuration.loaderPlugins) {
  103513. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  103514. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  103515. _this.modelLoader.addPlugin(name);
  103516. }
  103517. }));
  103518. }
  103519. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  103520. };
  103521. /**
  103522. * Force a single render loop execution.
  103523. */
  103524. AbstractViewer.prototype.forceRender = function () {
  103525. this._render(true);
  103526. };
  103527. /**
  103528. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  103529. * @param callback optional callback that will be triggered when screenshot is done.
  103530. * @param width Optional screenshot width (default to 512).
  103531. * @param height Optional screenshot height (default to 512).
  103532. * @returns a promise with the screenshot data
  103533. */
  103534. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  103535. var _this = this;
  103536. if (width === void 0) { width = 0; }
  103537. if (height === void 0) { height = 0; }
  103538. width = width || this.canvas.clientWidth;
  103539. height = height || this.canvas.clientHeight;
  103540. // Create the screenshot
  103541. return new Promise(function (resolve, reject) {
  103542. try {
  103543. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  103544. if (callback) {
  103545. callback(data);
  103546. }
  103547. resolve(data);
  103548. });
  103549. }
  103550. catch (e) {
  103551. reject(e);
  103552. }
  103553. });
  103554. };
  103555. /**
  103556. * Update the current viewer configuration with new values.
  103557. * Only provided information will be updated, old configuration values will be kept.
  103558. * If this.configuration was manually changed, you can trigger this function with no parameters,
  103559. * and the entire configuration will be updated.
  103560. * @param newConfiguration the partial configuration to update
  103561. *
  103562. */
  103563. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  103564. var _this = this;
  103565. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  103566. // update this.configuration with the new data
  103567. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  103568. this.sceneManager.updateConfiguration(newConfiguration);
  103569. // observers in configuration
  103570. if (newConfiguration.observers) {
  103571. this._configureObservers(newConfiguration.observers);
  103572. }
  103573. if (newConfiguration.loaderPlugins) {
  103574. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  103575. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  103576. _this.modelLoader.addPlugin(name);
  103577. }
  103578. }));
  103579. }
  103580. };
  103581. /**
  103582. * this is used to register native functions using the configuration object.
  103583. * This will configure the observers.
  103584. * @param observersConfiguration observers configuration
  103585. */
  103586. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  103587. if (observersConfiguration.onEngineInit) {
  103588. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  103589. }
  103590. else {
  103591. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  103592. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  103593. }
  103594. }
  103595. if (observersConfiguration.onSceneInit) {
  103596. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  103597. }
  103598. else {
  103599. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  103600. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  103601. }
  103602. }
  103603. if (observersConfiguration.onModelLoaded) {
  103604. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  103605. }
  103606. else {
  103607. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  103608. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  103609. }
  103610. }
  103611. };
  103612. /**
  103613. * Dispoe the entire viewer including the scene and the engine
  103614. */
  103615. AbstractViewer.prototype.dispose = function () {
  103616. if (this._isDisposed) {
  103617. return;
  103618. }
  103619. window.removeEventListener('resize', this._resize);
  103620. if (this.sceneManager) {
  103621. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  103622. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  103623. }
  103624. this.sceneManager.dispose();
  103625. }
  103626. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  103627. this.observablesManager.dispose();
  103628. this.modelLoader.dispose();
  103629. if (this.engine) {
  103630. this.engine.dispose();
  103631. }
  103632. viewerManager_1.viewerManager.removeViewer(this);
  103633. this._isDisposed = true;
  103634. };
  103635. /**
  103636. * This function will execute when the HTML templates finished initializing.
  103637. * It should initialize the engine and continue execution.
  103638. *
  103639. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  103640. */
  103641. AbstractViewer.prototype._onTemplatesLoaded = function () {
  103642. return Promise.resolve(this);
  103643. };
  103644. /**
  103645. * This will force the creation of an engine and a scene.
  103646. * It will also load a model if preconfigured.
  103647. * But first - it will load the extendible onTemplateLoaded()!
  103648. */
  103649. AbstractViewer.prototype._onTemplateLoaded = function () {
  103650. var _this = this;
  103651. // check if viewer was disposed right after created
  103652. if (this._isDisposed) {
  103653. return Promise.reject("viewer was disposed");
  103654. }
  103655. return this._onTemplatesLoaded().then(function () {
  103656. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  103657. return _this._initEngine().then(function (engine) {
  103658. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  103659. }).then(function () {
  103660. _this._initTelemetryEvents();
  103661. if (autoLoad) {
  103662. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  103663. }
  103664. else {
  103665. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  103666. }
  103667. }).then(function () {
  103668. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  103669. }).catch(function (e) {
  103670. babylonjs_1.Tools.Warn(e.toString());
  103671. return _this;
  103672. });
  103673. });
  103674. };
  103675. /**
  103676. * Initialize the engine. Retruns a promise in case async calls are needed.
  103677. *
  103678. * @protected
  103679. * @returns {Promise<Engine>}
  103680. * @memberof Viewer
  103681. */
  103682. AbstractViewer.prototype._initEngine = function () {
  103683. // init custom shaders
  103684. this._injectCustomShaders();
  103685. //let canvasElement = this.templateManager.getCanvas();
  103686. if (!this.canvas) {
  103687. return Promise.reject('Canvas element not found!');
  103688. }
  103689. var config = this.configuration.engine || {};
  103690. // TDO enable further configuration
  103691. // check for webgl2 support, force-disable if needed.
  103692. if (globals_1.viewerGlobals.disableWebGL2Support) {
  103693. config.engineOptions = config.engineOptions || {};
  103694. config.engineOptions.disableWebGL2Support = true;
  103695. }
  103696. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  103697. // Disable manifest checking
  103698. babylonjs_1.Database.IDBStorageEnabled = false;
  103699. if (!config.disableResize) {
  103700. window.addEventListener('resize', this._resize);
  103701. }
  103702. if (this.configuration.engine) {
  103703. if (this.configuration.engine.adaptiveQuality) {
  103704. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  103705. this.engine.setHardwareScalingLevel(scale);
  103706. }
  103707. if (this.configuration.engine.hdEnabled) {
  103708. this.toggleHD();
  103709. }
  103710. }
  103711. // create a new template manager for this viewer
  103712. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  103713. return Promise.resolve(this.engine);
  103714. };
  103715. /**
  103716. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  103717. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  103718. *
  103719. * @param modelConfig model configuration to use when loading the model.
  103720. * @param clearScene should the scene be cleared before loading this model
  103721. * @returns a ViewerModel object that is not yet fully loaded.
  103722. */
  103723. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  103724. var _this = this;
  103725. if (clearScene === void 0) { clearScene = true; }
  103726. var configuration;
  103727. if (typeof modelConfig === 'string') {
  103728. configuration = {
  103729. url: modelConfig
  103730. };
  103731. }
  103732. else if (modelConfig instanceof File) {
  103733. configuration = {
  103734. file: modelConfig,
  103735. root: "file:"
  103736. };
  103737. }
  103738. else {
  103739. configuration = modelConfig;
  103740. }
  103741. if (!configuration.url && !configuration.file) {
  103742. throw new Error("no model provided");
  103743. }
  103744. if (clearScene) {
  103745. this.sceneManager.clearScene(true, false);
  103746. }
  103747. //merge the configuration for future models:
  103748. if (this.configuration.model && typeof this.configuration.model === 'object') {
  103749. var globalConfig = _1.deepmerge({}, this.configuration.model);
  103750. configuration = _1.deepmerge(globalConfig, configuration);
  103751. if (modelConfig instanceof File) {
  103752. configuration.file = modelConfig;
  103753. }
  103754. }
  103755. else {
  103756. this.configuration.model = configuration;
  103757. }
  103758. this._isLoading = true;
  103759. var model = this.modelLoader.load(configuration);
  103760. this.lastUsedLoader = model.loader;
  103761. model.onLoadErrorObservable.add(function (errorObject) {
  103762. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  103763. });
  103764. model.onLoadProgressObservable.add(function (progressEvent) {
  103765. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  103766. });
  103767. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  103768. model.onLoadedObservable.add(function () {
  103769. _this._isLoading = false;
  103770. });
  103771. return model;
  103772. };
  103773. /**
  103774. * load a model using the provided configuration.
  103775. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  103776. * If you want to attach to the observables of the model, use initModle instead.
  103777. *
  103778. * @param modelConfig the model configuration or URL to load.
  103779. * @param clearScene Should the scene be cleared before loading the model
  103780. * @returns a Promise the fulfills when the model finished loading successfully.
  103781. */
  103782. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  103783. var _this = this;
  103784. if (clearScene === void 0) { clearScene = true; }
  103785. if (this._isLoading) {
  103786. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  103787. return Promise.reject("another model is curently being loaded.");
  103788. }
  103789. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  103790. if (!scene)
  103791. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  103792. return scene;
  103793. }).then(function () {
  103794. var model = _this.initModel(modelConfig, clearScene);
  103795. return new Promise(function (resolve, reject) {
  103796. // at this point, configuration.model is an object, not a string
  103797. model.onLoadedObservable.add(function () {
  103798. resolve(model);
  103799. });
  103800. model.onLoadErrorObservable.add(function (error) {
  103801. reject(error);
  103802. });
  103803. });
  103804. });
  103805. };
  103806. AbstractViewer.prototype._initTelemetryEvents = function () {
  103807. var _this = this;
  103808. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  103809. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  103810. userAgent: navigator.userAgent,
  103811. platform: navigator.platform
  103812. });
  103813. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  103814. var trackFPS = function () {
  103815. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  103816. };
  103817. trackFPS();
  103818. // Track the FPS again after 60 seconds
  103819. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  103820. };
  103821. /**
  103822. * Injects all the spectre shader in the babylon shader store
  103823. */
  103824. AbstractViewer.prototype._injectCustomShaders = function () {
  103825. var customShaders = this.configuration.customShaders;
  103826. // Inject all the spectre shader in the babylon shader store.
  103827. if (!customShaders) {
  103828. return;
  103829. }
  103830. if (customShaders.shaders) {
  103831. Object.keys(customShaders.shaders).forEach(function (key) {
  103832. // typescript considers a callback "unsafe", so... '!'
  103833. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  103834. });
  103835. }
  103836. if (customShaders.includes) {
  103837. Object.keys(customShaders.includes).forEach(function (key) {
  103838. // typescript considers a callback "unsafe", so... '!'
  103839. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  103840. });
  103841. }
  103842. };
  103843. return AbstractViewer;
  103844. }());
  103845. exports.AbstractViewer = AbstractViewer;
  103846. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1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QUE3b0JELElBNm9CQztBQTdvQnFCLHdDQUFjIn0=
  103847. /***/ }),
  103848. /* 10 */
  103849. /***/ (function(module, exports, __webpack_require__) {
  103850. "use strict";
  103851. function __export(m) {
  103852. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  103853. }
  103854. Object.defineProperty(exports, "__esModule", { value: true });
  103855. __export(__webpack_require__(11));
  103856. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  103857. /***/ }),
  103858. /* 11 */
  103859. /***/ (function(module, exports, __webpack_require__) {
  103860. "use strict";
  103861. Object.defineProperty(exports, "__esModule", { value: true });
  103862. function getConfigurationKey(key, configObject) {
  103863. var splits = key.split('.');
  103864. if (splits.length === 0 || !configObject)
  103865. return;
  103866. else if (splits.length === 1) {
  103867. if (configObject[key] !== undefined) {
  103868. return configObject[key];
  103869. }
  103870. }
  103871. else {
  103872. var firstKey = splits.shift();
  103873. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  103874. }
  103875. }
  103876. exports.getConfigurationKey = getConfigurationKey;
  103877. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  103878. /***/ }),
  103879. /* 12 */
  103880. /***/ (function(module, exports, __webpack_require__) {
  103881. "use strict";
  103882. Object.defineProperty(exports, "__esModule", { value: true });
  103883. var babylonjs_1 = __webpack_require__(0);
  103884. /**
  103885. * A minimal WebGL cubemap descriptor
  103886. */
  103887. var TextureCube = /** @class */ (function () {
  103888. /**
  103889. * constructor
  103890. * @param internalFormat WebGL pixel format for the texture on the GPU
  103891. * @param type WebGL pixel type of the supplied data and texture on the GPU
  103892. * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object
  103893. */
  103894. function TextureCube(internalFormat, type, source) {
  103895. if (source === void 0) { source = []; }
  103896. this.internalFormat = internalFormat;
  103897. this.type = type;
  103898. this.source = source;
  103899. }
  103900. Object.defineProperty(TextureCube.prototype, "Width", {
  103901. /**
  103902. * Returns the width of a face of the texture or 0 if not available
  103903. */
  103904. get: function () {
  103905. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  103906. },
  103907. enumerable: true,
  103908. configurable: true
  103909. });
  103910. Object.defineProperty(TextureCube.prototype, "Height", {
  103911. /**
  103912. * Returns the height of a face of the texture or 0 if not available
  103913. */
  103914. get: function () {
  103915. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  103916. },
  103917. enumerable: true,
  103918. configurable: true
  103919. });
  103920. return TextureCube;
  103921. }());
  103922. exports.TextureCube = TextureCube;
  103923. /**
  103924. * A static class providing methods to aid working with Bablyon textures.
  103925. */
  103926. var TextureUtils = /** @class */ (function () {
  103927. function TextureUtils() {
  103928. }
  103929. /**
  103930. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  103931. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  103932. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  103933. * @param scene A Babylon Scene instance
  103934. * @param textureCube A Spectre TextureCube object
  103935. * @param parameters WebGL texture sampling parameters
  103936. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  103937. * @param environment Specifies that the texture will be used as an environment
  103938. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  103939. * @return Babylon cube texture
  103940. */
  103941. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  103942. if (environment === void 0) { environment = false; }
  103943. if (singleLod === void 0) { singleLod = false; }
  103944. if (!textureCube)
  103945. throw new Error("no texture cube provided");
  103946. var parameters;
  103947. if (environment) {
  103948. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  103949. }
  103950. else {
  103951. parameters = {
  103952. magFilter: 9728 /* NEAREST */,
  103953. minFilter: 9728 /* NEAREST */,
  103954. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103955. wrapT: 33071 /* CLAMP_TO_EDGE */
  103956. };
  103957. }
  103958. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  103959. var babylonTexture = textureCube[key];
  103960. if (!babylonTexture) {
  103961. //initialize babylon texture
  103962. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  103963. if (environment) {
  103964. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  103965. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  103966. }
  103967. babylonTexture.gammaSpace = false;
  103968. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  103969. var glTexture_1 = internalTexture_1._webGLTexture;
  103970. //babylon properties
  103971. internalTexture_1.isCube = true;
  103972. internalTexture_1.generateMipMaps = false;
  103973. babylonTexture._texture = internalTexture_1;
  103974. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  103975. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  103976. var texturesUploaded_1 = 0;
  103977. var textureComplete = function () {
  103978. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  103979. };
  103980. var uploadFace = function (i, level, face) {
  103981. if (!glTexture_1)
  103982. return;
  103983. if (i === 0 && level === 0) {
  103984. internalTexture_1.width = face.width;
  103985. internalTexture_1.height = face.height;
  103986. }
  103987. var gl = (scene.getEngine())._gl;
  103988. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  103989. scene.getEngine()._unpackFlipY(false);
  103990. if (face instanceof HTMLElement || face instanceof ImageData) {
  103991. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  103992. }
  103993. else {
  103994. var textureData = face;
  103995. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  103996. }
  103997. texturesUploaded_1++;
  103998. if (textureComplete()) {
  103999. //generate mipmaps
  104000. if (automaticMipmaps) {
  104001. var w = face.width;
  104002. var h = face.height;
  104003. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  104004. if (isPot) {
  104005. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  104006. }
  104007. }
  104008. // Upload Separate lods in case there is no support for texture lod.
  104009. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  104010. var mipSlices = 3;
  104011. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  104012. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  104013. var lod = textureCube[lodKey];
  104014. //initialize lod texture if it doesn't already exist
  104015. if (lod == null && textureCube.Width) {
  104016. //compute LOD from even spacing in smoothness (matching shader calculation)
  104017. var smoothness = i_1 / (mipSlices - 1);
  104018. var roughness = 1 - smoothness;
  104019. var kMinimumVariance = 0.0005;
  104020. var alphaG = roughness * roughness + kMinimumVariance;
  104021. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  104022. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  104023. var maxLODIndex = textureCube.source.length - 1;
  104024. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  104025. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  104026. if (i_1 === 0) {
  104027. internalTexture_1._lodTextureLow = lod;
  104028. }
  104029. else if (i_1 === 1) {
  104030. internalTexture_1._lodTextureMid = lod;
  104031. }
  104032. else {
  104033. internalTexture_1._lodTextureHigh = lod;
  104034. }
  104035. textureCube[lodKey] = lod;
  104036. }
  104037. }
  104038. }
  104039. internalTexture_1.isReady = true;
  104040. }
  104041. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  104042. scene.getEngine().resetTextureCache();
  104043. };
  104044. var _loop_1 = function (i) {
  104045. var faces = textureCube.source[i];
  104046. var _loop_2 = function (j) {
  104047. var face = faces[j];
  104048. if (face instanceof HTMLImageElement && !face.complete) {
  104049. face.addEventListener('load', function () {
  104050. uploadFace(j, i, face);
  104051. }, false);
  104052. }
  104053. else {
  104054. uploadFace(j, i, face);
  104055. }
  104056. };
  104057. for (var j = 0; j < faces.length; j++) {
  104058. _loop_2(j);
  104059. }
  104060. };
  104061. for (var i = 0; i <= maxMipLevel_1; i++) {
  104062. _loop_1(i);
  104063. }
  104064. scene.getEngine().resetTextureCache();
  104065. babylonTexture.isReady = function () {
  104066. return textureComplete();
  104067. };
  104068. textureCube[key] = babylonTexture;
  104069. }
  104070. return babylonTexture;
  104071. };
  104072. /**
  104073. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  104074. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  104075. * @param parameters Spectre SamplingParameters to apply
  104076. */
  104077. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  104078. var scene = babylonTexture.getScene();
  104079. if (!scene)
  104080. return;
  104081. var gl = (scene.getEngine())._gl;
  104082. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  104083. var internalTexture = babylonTexture._texture;
  104084. if (!internalTexture)
  104085. return;
  104086. var glTexture = internalTexture._webGLTexture;
  104087. gl.bindTexture(target, glTexture);
  104088. if (parameters.magFilter != null)
  104089. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  104090. if (parameters.minFilter != null)
  104091. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  104092. if (parameters.wrapS != null)
  104093. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  104094. if (parameters.wrapT != null)
  104095. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  104096. //set babylon wrap modes from sampling parameter
  104097. switch (parameters.wrapS) {
  104098. case 10497 /* REPEAT */:
  104099. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104100. break;
  104101. case 33071 /* CLAMP_TO_EDGE */:
  104102. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104103. break;
  104104. case 33648 /* MIRRORED_REPEAT */:
  104105. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104106. break;
  104107. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104108. }
  104109. switch (parameters.wrapT) {
  104110. case 10497 /* REPEAT */:
  104111. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  104112. break;
  104113. case 33071 /* CLAMP_TO_EDGE */:
  104114. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104115. break;
  104116. case 33648 /* MIRRORED_REPEAT */:
  104117. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  104118. break;
  104119. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  104120. }
  104121. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  104122. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  104123. if (anisotropicExt) {
  104124. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  104125. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  104126. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  104127. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  104128. }
  104129. }
  104130. gl.bindTexture(target, null);
  104131. scene.getEngine().resetTextureCache();
  104132. };
  104133. /**
  104134. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  104135. */
  104136. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  104137. /**
  104138. * Controls anisotropic filtering for deserialized textures.
  104139. */
  104140. TextureUtils.MaxAnisotropy = 4;
  104141. TextureUtils._EnvironmentSampling = {
  104142. magFilter: 9729 /* LINEAR */,
  104143. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  104144. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104145. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104146. maxAnisotropy: 1
  104147. };
  104148. TextureUtils._EnvironmentSingleMipSampling = {
  104149. magFilter: 9729 /* LINEAR */,
  104150. minFilter: 9729 /* LINEAR */,
  104151. wrapS: 33071 /* CLAMP_TO_EDGE */,
  104152. wrapT: 33071 /* CLAMP_TO_EDGE */,
  104153. maxAnisotropy: 1
  104154. };
  104155. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  104156. /**
  104157. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  104158. */
  104159. TextureUtils.EnvironmentLODScale = 0.8;
  104160. /**
  104161. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  104162. */
  104163. TextureUtils.EnvironmentLODOffset = 1.0;
  104164. return TextureUtils;
  104165. }());
  104166. exports.TextureUtils = TextureUtils;
  104167. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3QjtRQUFwRixtQkFBYyxHQUFkLGNBQWMsQ0FBYTtRQUFTLFNBQUksR0FBSixJQUFJLENBQVc7UUFBUyxXQUFNLEdBQU4sTUFBTSxDQUFr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sRUFBRSxJQUFJLENBQUMsQ0FBQztRQUM3QixLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsaUJBQWlCLEVBQUUsQ0FBQztJQUMxQyxDQUFDO0lBN05EOztPQUVHO0lBQ1csb0NBQXVCLEdBQUcsbUJBQW1CLENBQUM7SUFFNUQ7O09BRUc7SUFDVywwQkFBYSxHQUFHLENBQUMsQ0FBQztJQXVOakIsaUNBQW9CLEdBQXVCO1FBQ3RELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsaUNBQXVDO1FBQ2hELEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFYSwwQ0FBNkIsR0FBdUI7UUFDL0QsU0FBUyxtQkFBeUI7UUFDbEMsU0FBUyxtQkFBeUI7UUFDbEMsS0FBSywyQkFBK0I7UUFDcEMsS0FBSywyQkFBK0I7UUFDcEMsYUFBYSxFQUFFLENBQUM7S0FDbkIsQ0FBQztJQUVGLGdGQUFnRjtJQUNoRjs7T0FFRztJQUNXLGdDQUFtQixHQUFHLEdBQUcsQ0FBQztJQUN4Qzs7T0FFRztJQUNXLGlDQUFvQixHQUFHLEdBQUcsQ0FBQztJQUM3QyxtQkFBQztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  104168. /***/ }),
  104169. /* 13 */
  104170. /***/ (function(module, exports, __webpack_require__) {
  104171. "use strict";
  104172. Object.defineProperty(exports, "__esModule", { value: true });
  104173. var babylonjs_1 = __webpack_require__(0);
  104174. var babylonjs_loaders_1 = __webpack_require__(14);
  104175. var viewerModel_1 = __webpack_require__(5);
  104176. var _1 = __webpack_require__(54);
  104177. /**
  104178. * An instance of the class is in charge of loading the model correctly.
  104179. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  104180. *
  104181. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  104182. */
  104183. var ModelLoader = /** @class */ (function () {
  104184. /**
  104185. * Create a new Model loader
  104186. * @param _viewer the viewer using this model loader
  104187. */
  104188. function ModelLoader(_observablesManager, _configurationContainer) {
  104189. this._observablesManager = _observablesManager;
  104190. this._configurationContainer = _configurationContainer;
  104191. this._disposed = false;
  104192. this._loaders = [];
  104193. this._loadId = 0;
  104194. this._plugins = [];
  104195. }
  104196. /**
  104197. * Adds a new plugin to the loader process.
  104198. *
  104199. * @param plugin the plugin name or the plugin itself
  104200. */
  104201. ModelLoader.prototype.addPlugin = function (plugin) {
  104202. var actualPlugin = {};
  104203. if (typeof plugin === 'string') {
  104204. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  104205. if (loadedPlugin) {
  104206. actualPlugin = loadedPlugin;
  104207. }
  104208. }
  104209. else {
  104210. actualPlugin = plugin;
  104211. }
  104212. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  104213. this._plugins.push(actualPlugin);
  104214. }
  104215. };
  104216. /**
  104217. * Load a model using predefined configuration
  104218. * @param modelConfiguration the modelConfiguration to use to load the model
  104219. */
  104220. ModelLoader.prototype.load = function (modelConfiguration) {
  104221. var _this = this;
  104222. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  104223. model.loadId = this._loadId++;
  104224. if (!modelConfiguration.url) {
  104225. model.state = viewerModel_1.ModelState.ERROR;
  104226. babylonjs_1.Tools.Error("No URL provided");
  104227. return model;
  104228. }
  104229. var base;
  104230. var filename;
  104231. if (modelConfiguration.file) {
  104232. base = "file:";
  104233. filename = modelConfiguration.file;
  104234. }
  104235. else {
  104236. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  104237. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  104238. }
  104239. var plugin = modelConfiguration.loader;
  104240. var scene = model.rootMesh.getScene();
  104241. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  104242. meshes.forEach(function (mesh) {
  104243. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104244. model.addMesh(mesh);
  104245. });
  104246. model.particleSystems = particleSystems;
  104247. model.skeletons = skeletons;
  104248. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  104249. var animationGroup = animationGroups_1[_i];
  104250. model.addAnimationGroup(animationGroup);
  104251. }
  104252. _this._checkAndRun("onLoaded", model);
  104253. scene.executeWhenReady(function () {
  104254. model.onLoadedObservable.notifyObservers(model);
  104255. });
  104256. }, function (progressEvent) {
  104257. _this._checkAndRun("onProgress", progressEvent);
  104258. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104259. }, function (scene, m, exception) {
  104260. model.state = viewerModel_1.ModelState.ERROR;
  104261. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  104262. _this._checkAndRun("onError", m, exception);
  104263. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104264. }, plugin);
  104265. if (model.loader.name === "gltf") {
  104266. var gltfLoader_1 = model.loader;
  104267. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  104268. gltfLoader_1.compileMaterials = true;
  104269. if (!modelConfiguration.file) {
  104270. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  104271. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  104272. };
  104273. }
  104274. // if ground is set to "mirror":
  104275. if (this._configurationContainer
  104276. && this._configurationContainer.configuration
  104277. && this._configurationContainer.configuration.ground
  104278. && typeof this._configurationContainer.configuration.ground === 'object'
  104279. && this._configurationContainer.configuration.ground.mirror) {
  104280. gltfLoader_1.useClipPlane = true;
  104281. }
  104282. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  104283. gltfLoader_1[functionName].add(function (payload) {
  104284. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  104285. });
  104286. });
  104287. gltfLoader_1.onParsedObservable.add(function (data) {
  104288. if (data && data.json && data.json['asset']) {
  104289. model.loadInfo = data.json['asset'];
  104290. }
  104291. });
  104292. gltfLoader_1.onCompleteObservable.add(function () {
  104293. model.loaderDone = true;
  104294. });
  104295. }
  104296. else {
  104297. model.loaderDone = true;
  104298. }
  104299. this._checkAndRun("onInit", model.loader, model);
  104300. this._loaders.push(model.loader);
  104301. return model;
  104302. };
  104303. ModelLoader.prototype.cancelLoad = function (model) {
  104304. var loader = model.loader || this._loaders[model.loadId];
  104305. // ATM only available in the GLTF Loader
  104306. if (loader && loader.name === "gltf") {
  104307. var gltfLoader = loader;
  104308. gltfLoader.dispose();
  104309. model.state = viewerModel_1.ModelState.CANCELED;
  104310. }
  104311. else {
  104312. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  104313. }
  104314. };
  104315. /**
  104316. * dispose the model loader.
  104317. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  104318. */
  104319. ModelLoader.prototype.dispose = function () {
  104320. this._loaders.forEach(function (loader) {
  104321. if (loader.name === "gltf") {
  104322. loader.dispose();
  104323. }
  104324. });
  104325. this._loaders.length = 0;
  104326. this._disposed = true;
  104327. };
  104328. ModelLoader.prototype._checkAndRun = function (functionName) {
  104329. var _this = this;
  104330. var payload = [];
  104331. for (var _i = 1; _i < arguments.length; _i++) {
  104332. payload[_i - 1] = arguments[_i];
  104333. }
  104334. if (this._disposed)
  104335. return;
  104336. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  104337. try {
  104338. plugin[functionName].apply(_this, payload);
  104339. }
  104340. catch (e) { }
  104341. });
  104342. };
  104343. return ModelLoader;
  104344. }());
  104345. exports.ModelLoader = ModelLoader;
  104346. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6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UMsT0FBTyxFQUFFLENBQUM7YUFDdEM7UUFDTCxDQUFDLENBQUMsQ0FBQztRQUNILElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUN6QixJQUFJLENBQUMsU0FBUyxHQUFHLElBQUksQ0FBQztJQUMxQixDQUFDO0lBRU8sa0NBQVksR0FBcEIsVUFBcUIsWUFBb0I7UUFBekMsaUJBT0M7UUFQMEMsaUJBQXNCO2FBQXRCLFVBQXNCLEVBQXRCLHFCQUFzQixFQUF0QixJQUFzQjtZQUF0QixnQ0FBc0I7O1FBQzdELElBQUksSUFBSSxDQUFDLFNBQVM7WUFBRSxPQUFPO1FBQzNCLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFVBQUEsQ0FBQyxJQUFJLE9BQUEsQ0FBQyxDQUFDLFlBQVksQ0FBQyxFQUFmLENBQWUsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLE1BQU07WUFDckQsSUFBSTtnQkFDQSxNQUFNLENBQUMsWUFBWSxDQUFDLENBQUMsS0FBSyxDQUFDLEtBQUksRUFBRSxPQUFPLENBQUMsQ0FBQzthQUM3QztZQUFDLE9BQU8sQ0FBQyxFQUFFLEdBQUc7UUFDbkIsQ0FBQyxDQUFDLENBQUE7SUFDTixDQUFDO0lBQ0wsa0JBQUM7QUFBRCxDQUFDLEFBaExELElBZ0xDO0FBaExZLGtDQUFXIn0=
  104347. /***/ }),
  104348. /* 14 */
  104349. /***/ (function(module, exports, __webpack_require__) {
  104350. (function universalModuleDefinition(root, factory) {
  104351. var amdDependencies = [];
  104352. var BABYLON = root.BABYLON || this.BABYLON;
  104353. if(true) {
  104354. BABYLON = BABYLON || __webpack_require__(0);
  104355. module.exports = factory(BABYLON);
  104356. } else if(typeof define === 'function' && define.amd) {
  104357. amdDependencies.push("babylonjs");
  104358. define("babylonjs-loaders", amdDependencies, factory);
  104359. } else if(typeof exports === 'object') {
  104360. BABYLON = BABYLON || require("babylonjs");
  104361. exports["babylonjs-loaders"] = factory(BABYLON);
  104362. } else {
  104363. root["BABYLON"] = factory(BABYLON);
  104364. }
  104365. })(this, function(BABYLON) {
  104366. BABYLON = BABYLON || this.BABYLON;
  104367. 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};
  104368. 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)}}();
  104369. var BABYLON;
  104370. (function (BABYLON) {
  104371. var STLFileLoader = /** @class */ (function () {
  104372. function STLFileLoader() {
  104373. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104374. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104375. 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;
  104376. 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;
  104377. this.name = "stl";
  104378. // force data to come in as an ArrayBuffer
  104379. // we'll convert to string if it looks like it's an ASCII .stl
  104380. this.extensions = {
  104381. ".stl": { isBinary: true },
  104382. };
  104383. }
  104384. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104385. var matches;
  104386. if (typeof data !== "string") {
  104387. if (this.isBinary(data)) {
  104388. // binary .stl
  104389. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104390. this.parseBinary(babylonMesh, data);
  104391. if (meshes) {
  104392. meshes.push(babylonMesh);
  104393. }
  104394. return true;
  104395. }
  104396. // ASCII .stl
  104397. // convert to string
  104398. var array_buffer = new Uint8Array(data);
  104399. var str = '';
  104400. for (var i = 0; i < data.byteLength; i++) {
  104401. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104402. }
  104403. data = str;
  104404. }
  104405. //if arrived here, data is a string, containing the STLA data.
  104406. while (matches = this.solidPattern.exec(data)) {
  104407. var meshName = matches[1];
  104408. var meshNameFromEnd = matches[3];
  104409. if (meshName != meshNameFromEnd) {
  104410. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104411. return false;
  104412. }
  104413. // check meshesNames
  104414. if (meshesNames && meshName) {
  104415. if (meshesNames instanceof Array) {
  104416. if (!meshesNames.indexOf(meshName)) {
  104417. continue;
  104418. }
  104419. }
  104420. else {
  104421. if (meshName !== meshesNames) {
  104422. continue;
  104423. }
  104424. }
  104425. }
  104426. // stl mesh name can be empty as well
  104427. meshName = meshName || "stlmesh";
  104428. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104429. this.parseASCII(babylonMesh, matches[2]);
  104430. if (meshes) {
  104431. meshes.push(babylonMesh);
  104432. }
  104433. }
  104434. return true;
  104435. };
  104436. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104437. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104438. if (result) {
  104439. scene.createDefaultCameraOrLight();
  104440. }
  104441. return result;
  104442. };
  104443. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104444. var container = new BABYLON.AssetContainer(scene);
  104445. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104446. container.removeAllFromScene();
  104447. return container;
  104448. };
  104449. STLFileLoader.prototype.isBinary = function (data) {
  104450. // check if file size is correct for binary stl
  104451. var faceSize, nFaces, reader;
  104452. reader = new DataView(data);
  104453. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104454. nFaces = reader.getUint32(80, true);
  104455. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104456. return true;
  104457. }
  104458. // check characters higher than ASCII to confirm binary
  104459. var fileLength = reader.byteLength;
  104460. for (var index = 0; index < fileLength; index++) {
  104461. if (reader.getUint8(index) > 127) {
  104462. return true;
  104463. }
  104464. }
  104465. return false;
  104466. };
  104467. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104468. var reader = new DataView(data);
  104469. var faces = reader.getUint32(80, true);
  104470. var dataOffset = 84;
  104471. var faceLength = 12 * 4 + 2;
  104472. var offset = 0;
  104473. var positions = new Float32Array(faces * 3 * 3);
  104474. var normals = new Float32Array(faces * 3 * 3);
  104475. var indices = new Uint32Array(faces * 3);
  104476. var indicesCount = 0;
  104477. for (var face = 0; face < faces; face++) {
  104478. var start = dataOffset + face * faceLength;
  104479. var normalX = reader.getFloat32(start, true);
  104480. var normalY = reader.getFloat32(start + 4, true);
  104481. var normalZ = reader.getFloat32(start + 8, true);
  104482. for (var i = 1; i <= 3; i++) {
  104483. var vertexstart = start + i * 12;
  104484. // ordering is intentional to match ascii import
  104485. positions[offset] = reader.getFloat32(vertexstart, true);
  104486. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104487. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104488. normals[offset] = normalX;
  104489. normals[offset + 2] = normalY;
  104490. normals[offset + 1] = normalZ;
  104491. offset += 3;
  104492. }
  104493. indices[indicesCount] = indicesCount++;
  104494. indices[indicesCount] = indicesCount++;
  104495. indices[indicesCount] = indicesCount++;
  104496. }
  104497. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104498. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104499. mesh.setIndices(indices);
  104500. mesh.computeWorldMatrix(true);
  104501. };
  104502. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104503. var positions = [];
  104504. var normals = [];
  104505. var indices = [];
  104506. var indicesCount = 0;
  104507. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104508. var matches;
  104509. while (matches = this.facetsPattern.exec(solidData)) {
  104510. var facet = matches[1];
  104511. //one normal per face
  104512. var normalMatches = this.normalPattern.exec(facet);
  104513. this.normalPattern.lastIndex = 0;
  104514. if (!normalMatches) {
  104515. continue;
  104516. }
  104517. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104518. var vertexMatch;
  104519. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104520. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104521. normals.push(normal[0], normal[1], normal[2]);
  104522. }
  104523. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104524. this.vertexPattern.lastIndex = 0;
  104525. }
  104526. this.facetsPattern.lastIndex = 0;
  104527. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104528. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104529. mesh.setIndices(indices);
  104530. mesh.computeWorldMatrix(true);
  104531. };
  104532. return STLFileLoader;
  104533. }());
  104534. BABYLON.STLFileLoader = STLFileLoader;
  104535. if (BABYLON.SceneLoader) {
  104536. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104537. }
  104538. })(BABYLON || (BABYLON = {}));
  104539. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104540. var BABYLON;
  104541. (function (BABYLON) {
  104542. /**
  104543. * Class reading and parsing the MTL file bundled with the obj file.
  104544. */
  104545. var MTLFileLoader = /** @class */ (function () {
  104546. function MTLFileLoader() {
  104547. // All material loaded from the mtl will be set here
  104548. this.materials = [];
  104549. }
  104550. /**
  104551. * This function will read the mtl file and create each material described inside
  104552. * This function could be improve by adding :
  104553. * -some component missing (Ni, Tf...)
  104554. * -including the specific options available
  104555. *
  104556. * @param scene
  104557. * @param data
  104558. * @param rootUrl
  104559. */
  104560. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104561. if (data instanceof ArrayBuffer) {
  104562. return;
  104563. }
  104564. //Split the lines from the file
  104565. var lines = data.split('\n');
  104566. //Space char
  104567. var delimiter_pattern = /\s+/;
  104568. //Array with RGB colors
  104569. var color;
  104570. //New material
  104571. var material = null;
  104572. //Look at each line
  104573. for (var i = 0; i < lines.length; i++) {
  104574. var line = lines[i].trim();
  104575. // Blank line or comment
  104576. if (line.length === 0 || line.charAt(0) === '#') {
  104577. continue;
  104578. }
  104579. //Get the first parameter (keyword)
  104580. var pos = line.indexOf(' ');
  104581. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104582. key = key.toLowerCase();
  104583. //Get the data following the key
  104584. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104585. //This mtl keyword will create the new material
  104586. if (key === "newmtl") {
  104587. //Check if it is the first material.
  104588. // Materials specifications are described after this keyword.
  104589. if (material) {
  104590. //Add the previous material in the material array.
  104591. this.materials.push(material);
  104592. }
  104593. //Create a new material.
  104594. // value is the name of the material read in the mtl file
  104595. material = new BABYLON.StandardMaterial(value, scene);
  104596. }
  104597. else if (key === "kd" && material) {
  104598. // Diffuse color (color under white light) using RGB values
  104599. //value = "r g b"
  104600. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104601. //color = [r,g,b]
  104602. //Set tghe color into the material
  104603. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104604. }
  104605. else if (key === "ka" && material) {
  104606. // Ambient color (color under shadow) using RGB values
  104607. //value = "r g b"
  104608. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104609. //color = [r,g,b]
  104610. //Set tghe color into the material
  104611. material.ambientColor = BABYLON.Color3.FromArray(color);
  104612. }
  104613. else if (key === "ks" && material) {
  104614. // Specular color (color when light is reflected from shiny surface) using RGB values
  104615. //value = "r g b"
  104616. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104617. //color = [r,g,b]
  104618. //Set the color into the material
  104619. material.specularColor = BABYLON.Color3.FromArray(color);
  104620. }
  104621. else if (key === "ke" && material) {
  104622. // Emissive color using RGB values
  104623. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104624. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104625. }
  104626. else if (key === "ns" && material) {
  104627. //value = "Integer"
  104628. material.specularPower = parseFloat(value);
  104629. }
  104630. else if (key === "d" && material) {
  104631. //d is dissolve for current material. It mean alpha for BABYLON
  104632. material.alpha = parseFloat(value);
  104633. //Texture
  104634. //This part can be improved by adding the possible options of texture
  104635. }
  104636. else if (key === "map_ka" && material) {
  104637. // ambient texture map with a loaded image
  104638. //We must first get the folder of the image
  104639. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104640. }
  104641. else if (key === "map_kd" && material) {
  104642. // Diffuse texture map with a loaded image
  104643. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104644. }
  104645. else if (key === "map_ks" && material) {
  104646. // Specular texture map with a loaded image
  104647. //We must first get the folder of the image
  104648. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104649. }
  104650. else if (key === "map_ns") {
  104651. //Specular
  104652. //Specular highlight component
  104653. //We must first get the folder of the image
  104654. //
  104655. //Not supported by BABYLON
  104656. //
  104657. // continue;
  104658. }
  104659. else if (key === "map_bump" && material) {
  104660. //The bump texture
  104661. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104662. }
  104663. else if (key === "map_d" && material) {
  104664. // The dissolve of the material
  104665. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104666. //Options for illumination
  104667. }
  104668. else if (key === "illum") {
  104669. //Illumination
  104670. if (value === "0") {
  104671. //That mean Kd == Kd
  104672. }
  104673. else if (value === "1") {
  104674. //Color on and Ambient on
  104675. }
  104676. else if (value === "2") {
  104677. //Highlight on
  104678. }
  104679. else if (value === "3") {
  104680. //Reflection on and Ray trace on
  104681. }
  104682. else if (value === "4") {
  104683. //Transparency: Glass on, Reflection: Ray trace on
  104684. }
  104685. else if (value === "5") {
  104686. //Reflection: Fresnel on and Ray trace on
  104687. }
  104688. else if (value === "6") {
  104689. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  104690. }
  104691. else if (value === "7") {
  104692. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  104693. }
  104694. else if (value === "8") {
  104695. //Reflection on and Ray trace off
  104696. }
  104697. else if (value === "9") {
  104698. //Transparency: Glass on, Reflection: Ray trace off
  104699. }
  104700. else if (value === "10") {
  104701. //Casts shadows onto invisible surfaces
  104702. }
  104703. }
  104704. else {
  104705. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  104706. }
  104707. }
  104708. //At the end of the file, add the last material
  104709. if (material) {
  104710. this.materials.push(material);
  104711. }
  104712. };
  104713. /**
  104714. * Gets the texture for the material.
  104715. *
  104716. * If the material is imported from input file,
  104717. * We sanitize the url to ensure it takes the textre from aside the material.
  104718. *
  104719. * @param rootUrl The root url to load from
  104720. * @param value The value stored in the mtl
  104721. * @return The Texture
  104722. */
  104723. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  104724. if (!value) {
  104725. return null;
  104726. }
  104727. var url = rootUrl;
  104728. // Load from input file.
  104729. if (rootUrl === "file:") {
  104730. var lastDelimiter = value.lastIndexOf("\\");
  104731. if (lastDelimiter === -1) {
  104732. lastDelimiter = value.lastIndexOf("/");
  104733. }
  104734. if (lastDelimiter > -1) {
  104735. url += value.substr(lastDelimiter + 1);
  104736. }
  104737. else {
  104738. url += value;
  104739. }
  104740. }
  104741. // Not from input file.
  104742. else {
  104743. url += value;
  104744. }
  104745. return new BABYLON.Texture(url, scene);
  104746. };
  104747. return MTLFileLoader;
  104748. }());
  104749. BABYLON.MTLFileLoader = MTLFileLoader;
  104750. var OBJFileLoader = /** @class */ (function () {
  104751. function OBJFileLoader() {
  104752. this.name = "obj";
  104753. this.extensions = ".obj";
  104754. this.obj = /^o/;
  104755. this.group = /^g/;
  104756. this.mtllib = /^mtllib /;
  104757. this.usemtl = /^usemtl /;
  104758. this.smooth = /^s /;
  104759. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104760. // vn float float float
  104761. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104762. // vt float float
  104763. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104764. // f vertex vertex vertex ...
  104765. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  104766. // f vertex/uvs vertex/uvs vertex/uvs ...
  104767. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104768. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  104769. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104770. // f vertex//normal vertex//normal vertex//normal ...
  104771. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  104772. }
  104773. /**
  104774. * Calls synchronously the MTL file attached to this obj.
  104775. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  104776. * Without this function materials are not displayed in the first frame (but displayed after).
  104777. * In consequence it is impossible to get material information in your HTML file
  104778. *
  104779. * @param url The URL of the MTL file
  104780. * @param rootUrl
  104781. * @param onSuccess Callback function to be called when the MTL file is loaded
  104782. * @private
  104783. */
  104784. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  104785. //The complete path to the mtl file
  104786. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  104787. // Loads through the babylon tools to allow fileInput search.
  104788. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  104789. };
  104790. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104791. //get the meshes from OBJ file
  104792. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  104793. //Push meshes from OBJ file into the variable mesh of this function
  104794. if (meshes) {
  104795. loadedMeshes.forEach(function (mesh) {
  104796. meshes.push(mesh);
  104797. });
  104798. }
  104799. return true;
  104800. };
  104801. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  104802. //Get the 3D model
  104803. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  104804. };
  104805. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104806. var container = new BABYLON.AssetContainer(scene);
  104807. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104808. container.removeAllFromScene();
  104809. return container;
  104810. };
  104811. /**
  104812. * Read the OBJ file and create an Array of meshes.
  104813. * Each mesh contains all information given by the OBJ and the MTL file.
  104814. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  104815. *
  104816. * @param meshesNames
  104817. * @param scene BABYLON.Scene The scene where are displayed the data
  104818. * @param data String The content of the obj file
  104819. * @param rootUrl String The path to the folder
  104820. * @returns Array<AbstractMesh>
  104821. * @private
  104822. */
  104823. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  104824. var positions = []; //values for the positions of vertices
  104825. var normals = []; //Values for the normals
  104826. var uvs = []; //Values for the textures
  104827. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  104828. var handledMesh; //The current mesh of meshes array
  104829. var indicesForBabylon = []; //The list of indices for VertexData
  104830. var wrappedPositionForBabylon = []; //The list of position in vectors
  104831. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  104832. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  104833. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  104834. var curPositionInIndices = 0;
  104835. var hasMeshes = false; //Meshes are defined in the file
  104836. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  104837. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  104838. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  104839. var triangles = []; //Indices from new triangles coming from polygons
  104840. var materialNameFromObj = ""; //The name of the current material
  104841. var fileToLoad = ""; //The name of the mtlFile to load
  104842. var materialsFromMTLFile = new MTLFileLoader();
  104843. var objMeshName = ""; //The name of the current obj mesh
  104844. var increment = 1; //Id for meshes created by the multimaterial
  104845. var isFirstMaterial = true;
  104846. /**
  104847. * Search for obj in the given array.
  104848. * This function is called to check if a couple of data already exists in an array.
  104849. *
  104850. * If found, returns the index of the founded tuple index. Returns -1 if not found
  104851. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  104852. * @param obj Array<number>
  104853. * @returns {boolean}
  104854. */
  104855. var isInArray = function (arr, obj) {
  104856. if (!arr[obj[0]])
  104857. arr[obj[0]] = { normals: [], idx: [] };
  104858. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104859. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  104860. };
  104861. var isInArrayUV = function (arr, obj) {
  104862. if (!arr[obj[0]])
  104863. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  104864. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104865. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  104866. return arr[obj[0]].idx[idx];
  104867. }
  104868. return -1;
  104869. };
  104870. /**
  104871. * This function set the data for each triangle.
  104872. * Data are position, normals and uvs
  104873. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  104874. * If the tuple already exist, add only their indice
  104875. *
  104876. * @param indicePositionFromObj Integer The index in positions array
  104877. * @param indiceUvsFromObj Integer The index in uvs array
  104878. * @param indiceNormalFromObj Integer The index in normals array
  104879. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  104880. * @param textureVectorFromOBJ Vector3 The value of uvs
  104881. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  104882. */
  104883. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  104884. //Check if this tuple already exists in the list of tuples
  104885. var _index;
  104886. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  104887. _index = isInArrayUV(tuplePosNorm, [
  104888. indicePositionFromObj,
  104889. indiceNormalFromObj,
  104890. indiceUvsFromObj
  104891. ]);
  104892. }
  104893. else {
  104894. _index = isInArray(tuplePosNorm, [
  104895. indicePositionFromObj,
  104896. indiceNormalFromObj
  104897. ]);
  104898. }
  104899. //If it not exists
  104900. if (_index == -1) {
  104901. //Add an new indice.
  104902. //The array of indices is only an array with his length equal to the number of triangles - 1.
  104903. //We add vertices data in this order
  104904. indicesForBabylon.push(wrappedPositionForBabylon.length);
  104905. //Push the position of vertice for Babylon
  104906. //Each element is a BABYLON.Vector3(x,y,z)
  104907. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  104908. //Push the uvs for Babylon
  104909. //Each element is a BABYLON.Vector3(u,v)
  104910. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  104911. //Push the normals for Babylon
  104912. //Each element is a BABYLON.Vector3(x,y,z)
  104913. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  104914. //Add the tuple in the comparison list
  104915. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  104916. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  104917. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  104918. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  104919. }
  104920. else {
  104921. //The tuple already exists
  104922. //Add the index of the already existing tuple
  104923. //At this index we can get the value of position, normal and uvs of vertex
  104924. indicesForBabylon.push(_index);
  104925. }
  104926. };
  104927. /**
  104928. * Transform BABYLON.Vector() object onto 3 digits in an array
  104929. */
  104930. var unwrapData = function () {
  104931. //Every array has the same length
  104932. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  104933. //Push the x, y, z values of each element in the unwrapped array
  104934. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  104935. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  104936. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  104937. }
  104938. // Reset arrays for the next new meshes
  104939. wrappedPositionForBabylon = [];
  104940. wrappedNormalsForBabylon = [];
  104941. wrappedUvsForBabylon = [];
  104942. tuplePosNorm = [];
  104943. curPositionInIndices = 0;
  104944. };
  104945. /**
  104946. * Create triangles from polygons by recursion
  104947. * The best to understand how it works is to draw it in the same time you get the recursion.
  104948. * It is important to notice that a triangle is a polygon
  104949. * We get 4 patterns of face defined in OBJ File :
  104950. * facePattern1 = ["1","2","3","4","5","6"]
  104951. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  104952. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  104953. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  104954. * Each pattern is divided by the same method
  104955. * @param face Array[String] The indices of elements
  104956. * @param v Integer The variable to increment
  104957. */
  104958. var getTriangles = function (face, v) {
  104959. //Work for each element of the array
  104960. if (v + 1 < face.length) {
  104961. //Add on the triangle variable the indexes to obtain triangles
  104962. triangles.push(face[0], face[v], face[v + 1]);
  104963. //Incrementation for recursion
  104964. v += 1;
  104965. //Recursion
  104966. getTriangles(face, v);
  104967. }
  104968. //Result obtained after 2 iterations:
  104969. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  104970. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  104971. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  104972. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  104973. };
  104974. /**
  104975. * Create triangles and push the data for each polygon for the pattern 1
  104976. * In this pattern we get vertice positions
  104977. * @param face
  104978. * @param v
  104979. */
  104980. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  104981. //Get the indices of triangles for each polygon
  104982. getTriangles(face, v);
  104983. //For each element in the triangles array.
  104984. //This var could contains 1 to an infinity of triangles
  104985. for (var k = 0; k < triangles.length; k++) {
  104986. // Set position indice
  104987. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104988. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104989. positions[indicePositionFromObj], //Get the vectors data
  104990. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104991. );
  104992. }
  104993. //Reset variable for the next line
  104994. triangles = [];
  104995. };
  104996. /**
  104997. * Create triangles and push the data for each polygon for the pattern 2
  104998. * In this pattern we get vertice positions and uvsu
  104999. * @param face
  105000. * @param v
  105001. */
  105002. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105003. //Get the indices of triangles for each polygon
  105004. getTriangles(face, v);
  105005. for (var k = 0; k < triangles.length; k++) {
  105006. //triangle[k] = "1/1"
  105007. //Split the data for getting position and uv
  105008. var point = triangles[k].split("/"); // ["1", "1"]
  105009. //Set position indice
  105010. var indicePositionFromObj = parseInt(point[0]) - 1;
  105011. //Set uv indice
  105012. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105013. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105014. positions[indicePositionFromObj], //Get the values for each element
  105015. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105016. );
  105017. }
  105018. //Reset variable for the next line
  105019. triangles = [];
  105020. };
  105021. /**
  105022. * Create triangles and push the data for each polygon for the pattern 3
  105023. * In this pattern we get vertice positions, uvs and normals
  105024. * @param face
  105025. * @param v
  105026. */
  105027. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105028. //Get the indices of triangles for each polygon
  105029. getTriangles(face, v);
  105030. for (var k = 0; k < triangles.length; k++) {
  105031. //triangle[k] = "1/1/1"
  105032. //Split the data for getting position, uv, and normals
  105033. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105034. // Set position indice
  105035. var indicePositionFromObj = parseInt(point[0]) - 1;
  105036. // Set uv indice
  105037. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105038. // Set normal indice
  105039. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105040. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105041. );
  105042. }
  105043. //Reset variable for the next line
  105044. triangles = [];
  105045. };
  105046. /**
  105047. * Create triangles and push the data for each polygon for the pattern 4
  105048. * In this pattern we get vertice positions and normals
  105049. * @param face
  105050. * @param v
  105051. */
  105052. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105053. getTriangles(face, v);
  105054. for (var k = 0; k < triangles.length; k++) {
  105055. //triangle[k] = "1//1"
  105056. //Split the data for getting position and normals
  105057. var point = triangles[k].split("//"); // ["1", "1"]
  105058. // We check indices, and normals
  105059. var indicePositionFromObj = parseInt(point[0]) - 1;
  105060. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105061. setData(indicePositionFromObj, 1, //Default value for uv
  105062. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105063. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105064. }
  105065. //Reset variable for the next line
  105066. triangles = [];
  105067. };
  105068. var addPreviousObjMesh = function () {
  105069. //Check if it is not the first mesh. Otherwise we don't have data.
  105070. if (meshesFromObj.length > 0) {
  105071. //Get the previous mesh for applying the data about the faces
  105072. //=> in obj file, faces definition append after the name of the mesh
  105073. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105074. //Set the data into Array for the mesh
  105075. unwrapData();
  105076. // Reverse tab. Otherwise face are displayed in the wrong sens
  105077. indicesForBabylon.reverse();
  105078. //Set the information for the mesh
  105079. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105080. handledMesh.indices = indicesForBabylon.slice();
  105081. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105082. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105083. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105084. //Reset the array for the next mesh
  105085. indicesForBabylon = [];
  105086. unwrappedPositionsForBabylon = [];
  105087. unwrappedNormalsForBabylon = [];
  105088. unwrappedUVForBabylon = [];
  105089. }
  105090. };
  105091. //Main function
  105092. //Split the file into lines
  105093. var lines = data.split('\n');
  105094. //Look at each line
  105095. for (var i = 0; i < lines.length; i++) {
  105096. var line = lines[i].trim();
  105097. var result;
  105098. //Comment or newLine
  105099. if (line.length === 0 || line.charAt(0) === '#') {
  105100. continue;
  105101. //Get information about one position possible for the vertices
  105102. }
  105103. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105104. //Create a Vector3 with the position x, y, z
  105105. //Value of result:
  105106. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105107. //Add the Vector in the list of positions
  105108. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105109. }
  105110. else if ((result = this.normalPattern.exec(line)) !== null) {
  105111. //Create a Vector3 with the normals x, y, z
  105112. //Value of result
  105113. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105114. //Add the Vector in the list of normals
  105115. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105116. }
  105117. else if ((result = this.uvPattern.exec(line)) !== null) {
  105118. //Create a Vector2 with the normals u, v
  105119. //Value of result
  105120. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105121. //Add the Vector in the list of uvs
  105122. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105123. //Identify patterns of faces
  105124. //Face could be defined in different type of pattern
  105125. }
  105126. else if ((result = this.facePattern3.exec(line)) !== null) {
  105127. //Value of result:
  105128. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105129. //Set the data for this face
  105130. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105131. 1);
  105132. }
  105133. else if ((result = this.facePattern4.exec(line)) !== null) {
  105134. //Value of result:
  105135. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105136. //Set the data for this face
  105137. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105138. 1);
  105139. }
  105140. else if ((result = this.facePattern2.exec(line)) !== null) {
  105141. //Value of result:
  105142. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105143. //Set the data for this face
  105144. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105145. 1);
  105146. }
  105147. else if ((result = this.facePattern1.exec(line)) !== null) {
  105148. //Value of result
  105149. //["f 1 2 3", "1 2 3"...]
  105150. //Set the data for this face
  105151. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105152. 1);
  105153. //Define a mesh or an object
  105154. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105155. }
  105156. else if (this.group.test(line) || this.obj.test(line)) {
  105157. //Create a new mesh corresponding to the name of the group.
  105158. //Definition of the mesh
  105159. var objMesh =
  105160. //Set the name of the current obj mesh
  105161. {
  105162. name: line.substring(2).trim(),
  105163. indices: undefined,
  105164. positions: undefined,
  105165. normals: undefined,
  105166. uvs: undefined,
  105167. materialName: ""
  105168. };
  105169. addPreviousObjMesh();
  105170. //Push the last mesh created with only the name
  105171. meshesFromObj.push(objMesh);
  105172. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105173. hasMeshes = true;
  105174. isFirstMaterial = true;
  105175. increment = 1;
  105176. //Keyword for applying a material
  105177. }
  105178. else if (this.usemtl.test(line)) {
  105179. //Get the name of the material
  105180. materialNameFromObj = line.substring(7).trim();
  105181. //If this new material is in the same mesh
  105182. if (!isFirstMaterial) {
  105183. //Set the data for the previous mesh
  105184. addPreviousObjMesh();
  105185. //Create a new mesh
  105186. var objMesh =
  105187. //Set the name of the current obj mesh
  105188. {
  105189. name: objMeshName + "_mm" + increment.toString(),
  105190. indices: undefined,
  105191. positions: undefined,
  105192. normals: undefined,
  105193. uvs: undefined,
  105194. materialName: materialNameFromObj
  105195. };
  105196. increment++;
  105197. //If meshes are already defined
  105198. meshesFromObj.push(objMesh);
  105199. }
  105200. //Set the material name if the previous line define a mesh
  105201. if (hasMeshes && isFirstMaterial) {
  105202. //Set the material name to the previous mesh (1 material per mesh)
  105203. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105204. isFirstMaterial = false;
  105205. }
  105206. //Keyword for loading the mtl file
  105207. }
  105208. else if (this.mtllib.test(line)) {
  105209. //Get the name of mtl file
  105210. fileToLoad = line.substring(7).trim();
  105211. //Apply smoothing
  105212. }
  105213. else if (this.smooth.test(line)) {
  105214. // smooth shading => apply smoothing
  105215. //Toda y I don't know it work with babylon and with obj.
  105216. //With the obj file an integer is set
  105217. }
  105218. else {
  105219. //If there is another possibility
  105220. console.log("Unhandled expression at line : " + line);
  105221. }
  105222. }
  105223. //At the end of the file, add the last mesh into the meshesFromObj array
  105224. if (hasMeshes) {
  105225. //Set the data for the last mesh
  105226. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105227. //Reverse indices for displaying faces in the good sens
  105228. indicesForBabylon.reverse();
  105229. //Get the good array
  105230. unwrapData();
  105231. //Set array
  105232. handledMesh.indices = indicesForBabylon;
  105233. handledMesh.positions = unwrappedPositionsForBabylon;
  105234. handledMesh.normals = unwrappedNormalsForBabylon;
  105235. handledMesh.uvs = unwrappedUVForBabylon;
  105236. }
  105237. //If any o or g keyword found, create a mesj with a random id
  105238. if (!hasMeshes) {
  105239. // reverse tab of indices
  105240. indicesForBabylon.reverse();
  105241. //Get positions normals uvs
  105242. unwrapData();
  105243. //Set data for one mesh
  105244. meshesFromObj.push({
  105245. name: BABYLON.Geometry.RandomId(),
  105246. indices: indicesForBabylon,
  105247. positions: unwrappedPositionsForBabylon,
  105248. normals: unwrappedNormalsForBabylon,
  105249. uvs: unwrappedUVForBabylon,
  105250. materialName: materialNameFromObj
  105251. });
  105252. }
  105253. //Create a BABYLON.Mesh list
  105254. var babylonMeshesArray = []; //The mesh for babylon
  105255. var materialToUse = new Array();
  105256. //Set data for each mesh
  105257. for (var j = 0; j < meshesFromObj.length; j++) {
  105258. //check meshesNames (stlFileLoader)
  105259. if (meshesNames && meshesFromObj[j].name) {
  105260. if (meshesNames instanceof Array) {
  105261. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105262. continue;
  105263. }
  105264. }
  105265. else {
  105266. if (meshesFromObj[j].name !== meshesNames) {
  105267. continue;
  105268. }
  105269. }
  105270. }
  105271. //Get the current mesh
  105272. //Set the data with VertexBuffer for each mesh
  105273. handledMesh = meshesFromObj[j];
  105274. //Create a BABYLON.Mesh with the name of the obj mesh
  105275. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105276. //Push the name of the material to an array
  105277. //This is indispensable for the importMesh function
  105278. materialToUse.push(meshesFromObj[j].materialName);
  105279. var vertexData = new BABYLON.VertexData(); //The container for the values
  105280. //Set the data for the babylonMesh
  105281. vertexData.positions = handledMesh.positions;
  105282. vertexData.normals = handledMesh.normals;
  105283. vertexData.uvs = handledMesh.uvs;
  105284. vertexData.indices = handledMesh.indices;
  105285. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105286. vertexData.applyToMesh(babylonMesh);
  105287. if (OBJFileLoader.INVERT_Y) {
  105288. babylonMesh.scaling.y *= -1;
  105289. }
  105290. //Push the mesh into an array
  105291. babylonMeshesArray.push(babylonMesh);
  105292. }
  105293. //load the materials
  105294. //Check if we have a file to load
  105295. if (fileToLoad !== "") {
  105296. //Load the file synchronously
  105297. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105298. //Create materials thanks MTLLoader function
  105299. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105300. //Look at each material loaded in the mtl file
  105301. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105302. //Three variables to get all meshes with the same material
  105303. var startIndex = 0;
  105304. var _indices = [];
  105305. var _index;
  105306. //The material from MTL file is used in the meshes loaded
  105307. //Push the indice in an array
  105308. //Check if the material is not used for another mesh
  105309. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105310. _indices.push(_index);
  105311. startIndex = _index + 1;
  105312. }
  105313. //If the material is not used dispose it
  105314. if (_index == -1 && _indices.length == 0) {
  105315. //If the material is not needed, remove it
  105316. materialsFromMTLFile.materials[n].dispose();
  105317. }
  105318. else {
  105319. for (var o = 0; o < _indices.length; o++) {
  105320. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105321. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105322. }
  105323. }
  105324. }
  105325. });
  105326. }
  105327. //Return an array with all BABYLON.Mesh
  105328. return babylonMeshesArray;
  105329. };
  105330. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105331. OBJFileLoader.INVERT_Y = false;
  105332. return OBJFileLoader;
  105333. }());
  105334. BABYLON.OBJFileLoader = OBJFileLoader;
  105335. if (BABYLON.SceneLoader) {
  105336. //Add this loader into the register plugin
  105337. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105338. }
  105339. })(BABYLON || (BABYLON = {}));
  105340. //# sourceMappingURL=babylon.objFileLoader.js.map
  105341. var BABYLON;
  105342. (function (BABYLON) {
  105343. /**
  105344. * Mode that determines the coordinate system to use.
  105345. */
  105346. var GLTFLoaderCoordinateSystemMode;
  105347. (function (GLTFLoaderCoordinateSystemMode) {
  105348. /**
  105349. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105350. */
  105351. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105352. /**
  105353. * Sets the useRightHandedSystem flag on the scene.
  105354. */
  105355. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105356. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105357. /**
  105358. * Mode that determines what animations will start.
  105359. */
  105360. var GLTFLoaderAnimationStartMode;
  105361. (function (GLTFLoaderAnimationStartMode) {
  105362. /**
  105363. * No animation will start.
  105364. */
  105365. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105366. /**
  105367. * The first animation will start.
  105368. */
  105369. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105370. /**
  105371. * All animations will start.
  105372. */
  105373. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105374. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105375. /**
  105376. * Loader state.
  105377. */
  105378. var GLTFLoaderState;
  105379. (function (GLTFLoaderState) {
  105380. /**
  105381. * The asset is loading.
  105382. */
  105383. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  105384. /**
  105385. * The asset is ready for rendering.
  105386. */
  105387. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  105388. /**
  105389. * The asset is completely loaded.
  105390. */
  105391. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  105392. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105393. /**
  105394. * File loader for loading glTF files into a scene.
  105395. */
  105396. var GLTFFileLoader = /** @class */ (function () {
  105397. function GLTFFileLoader() {
  105398. // #region Common options
  105399. /**
  105400. * Raised when the asset has been parsed
  105401. */
  105402. this.onParsedObservable = new BABYLON.Observable();
  105403. // #endregion
  105404. // #region V2 options
  105405. /**
  105406. * The coordinate system mode. Defaults to AUTO.
  105407. */
  105408. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105409. /**
  105410. * The animation start mode. Defaults to FIRST.
  105411. */
  105412. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105413. /**
  105414. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  105415. */
  105416. this.compileMaterials = false;
  105417. /**
  105418. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  105419. */
  105420. this.useClipPlane = false;
  105421. /**
  105422. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  105423. */
  105424. this.compileShadowGenerators = false;
  105425. /**
  105426. * Defines if the Alpha blended materials are only applied as coverage.
  105427. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  105428. * If true, no extra effects are applied to transparent pixels.
  105429. */
  105430. this.transparencyAsCoverage = false;
  105431. /** @hidden */
  105432. this._normalizeAnimationGroupsToBeginAtZero = true;
  105433. /**
  105434. * Function called before loading a url referenced by the asset.
  105435. */
  105436. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105437. /**
  105438. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105439. */
  105440. this.onMeshLoadedObservable = new BABYLON.Observable();
  105441. /**
  105442. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  105443. */
  105444. this.onTextureLoadedObservable = new BABYLON.Observable();
  105445. /**
  105446. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  105447. */
  105448. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105449. /**
  105450. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  105451. */
  105452. this.onCameraLoadedObservable = new BABYLON.Observable();
  105453. /**
  105454. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  105455. * For assets with LODs, raised when all of the LODs are complete.
  105456. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  105457. */
  105458. this.onCompleteObservable = new BABYLON.Observable();
  105459. /**
  105460. * Observable raised after the loader is disposed.
  105461. */
  105462. this.onDisposeObservable = new BABYLON.Observable();
  105463. /**
  105464. * Observable raised after a loader extension is created.
  105465. * Set additional options for a loader extension in this event.
  105466. */
  105467. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105468. // #endregion
  105469. this._loader = null;
  105470. /**
  105471. * Name of the loader ("gltf")
  105472. */
  105473. this.name = "gltf";
  105474. /**
  105475. * Supported file extensions of the loader (.gltf, .glb)
  105476. */
  105477. this.extensions = {
  105478. ".gltf": { isBinary: false },
  105479. ".glb": { isBinary: true }
  105480. };
  105481. this._logIndentLevel = 0;
  105482. this._loggingEnabled = false;
  105483. /** @hidden */
  105484. this._log = this._logDisabled;
  105485. this._capturePerformanceCounters = false;
  105486. /** @hidden */
  105487. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  105488. /** @hidden */
  105489. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  105490. }
  105491. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105492. /**
  105493. * Raised when the asset has been parsed
  105494. */
  105495. set: function (callback) {
  105496. if (this._onParsedObserver) {
  105497. this.onParsedObservable.remove(this._onParsedObserver);
  105498. }
  105499. this._onParsedObserver = this.onParsedObservable.add(callback);
  105500. },
  105501. enumerable: true,
  105502. configurable: true
  105503. });
  105504. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105505. /**
  105506. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105507. */
  105508. set: function (callback) {
  105509. if (this._onMeshLoadedObserver) {
  105510. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105511. }
  105512. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105513. },
  105514. enumerable: true,
  105515. configurable: true
  105516. });
  105517. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105518. /**
  105519. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  105520. */
  105521. set: function (callback) {
  105522. if (this._onTextureLoadedObserver) {
  105523. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105524. }
  105525. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105526. },
  105527. enumerable: true,
  105528. configurable: true
  105529. });
  105530. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105531. /**
  105532. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  105533. */
  105534. set: function (callback) {
  105535. if (this._onMaterialLoadedObserver) {
  105536. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105537. }
  105538. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105539. },
  105540. enumerable: true,
  105541. configurable: true
  105542. });
  105543. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  105544. /**
  105545. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  105546. */
  105547. set: function (callback) {
  105548. if (this._onCameraLoadedObserver) {
  105549. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  105550. }
  105551. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  105552. },
  105553. enumerable: true,
  105554. configurable: true
  105555. });
  105556. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105557. /**
  105558. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  105559. */
  105560. set: function (callback) {
  105561. if (this._onCompleteObserver) {
  105562. this.onCompleteObservable.remove(this._onCompleteObserver);
  105563. }
  105564. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105565. },
  105566. enumerable: true,
  105567. configurable: true
  105568. });
  105569. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105570. /**
  105571. * Callback raised after the loader is disposed.
  105572. */
  105573. set: function (callback) {
  105574. if (this._onDisposeObserver) {
  105575. this.onDisposeObservable.remove(this._onDisposeObserver);
  105576. }
  105577. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105578. },
  105579. enumerable: true,
  105580. configurable: true
  105581. });
  105582. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105583. /**
  105584. * Callback raised after a loader extension is created.
  105585. */
  105586. set: function (callback) {
  105587. if (this._onExtensionLoadedObserver) {
  105588. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105589. }
  105590. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105591. },
  105592. enumerable: true,
  105593. configurable: true
  105594. });
  105595. /**
  105596. * Returns a promise that resolves when the asset is completely loaded.
  105597. * @returns a promise that resolves when the asset is completely loaded.
  105598. */
  105599. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105600. var _this = this;
  105601. return new Promise(function (resolve) {
  105602. _this.onCompleteObservable.addOnce(function () {
  105603. resolve();
  105604. });
  105605. });
  105606. };
  105607. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105608. /**
  105609. * The loader state or null if the loader is not active.
  105610. */
  105611. get: function () {
  105612. return this._loader ? this._loader.state : null;
  105613. },
  105614. enumerable: true,
  105615. configurable: true
  105616. });
  105617. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  105618. /**
  105619. * Defines if the loader logging is enabled.
  105620. */
  105621. get: function () {
  105622. return this._loggingEnabled;
  105623. },
  105624. set: function (value) {
  105625. if (this._loggingEnabled === value) {
  105626. return;
  105627. }
  105628. this._loggingEnabled = value;
  105629. if (this._loggingEnabled) {
  105630. this._log = this._logEnabled;
  105631. }
  105632. else {
  105633. this._log = this._logDisabled;
  105634. }
  105635. },
  105636. enumerable: true,
  105637. configurable: true
  105638. });
  105639. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  105640. /**
  105641. * Defines if the loader should capture performance counters.
  105642. */
  105643. get: function () {
  105644. return this._capturePerformanceCounters;
  105645. },
  105646. set: function (value) {
  105647. if (this._capturePerformanceCounters === value) {
  105648. return;
  105649. }
  105650. this._capturePerformanceCounters = value;
  105651. if (this._capturePerformanceCounters) {
  105652. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  105653. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  105654. }
  105655. else {
  105656. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  105657. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  105658. }
  105659. },
  105660. enumerable: true,
  105661. configurable: true
  105662. });
  105663. /**
  105664. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105665. */
  105666. GLTFFileLoader.prototype.dispose = function () {
  105667. if (this._loader) {
  105668. this._loader.dispose();
  105669. this._loader = null;
  105670. }
  105671. this._clear();
  105672. this.onDisposeObservable.notifyObservers(undefined);
  105673. this.onDisposeObservable.clear();
  105674. };
  105675. /** @hidden */
  105676. GLTFFileLoader.prototype._clear = function () {
  105677. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105678. this.onMeshLoadedObservable.clear();
  105679. this.onTextureLoadedObservable.clear();
  105680. this.onMaterialLoadedObservable.clear();
  105681. this.onCameraLoadedObservable.clear();
  105682. this.onCompleteObservable.clear();
  105683. this.onExtensionLoadedObservable.clear();
  105684. };
  105685. /**
  105686. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  105687. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  105688. * @param scene the scene the meshes should be added to
  105689. * @param data the glTF data to load
  105690. * @param rootUrl root url to load from
  105691. * @param onProgress event that fires when loading progress has occured
  105692. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  105693. */
  105694. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105695. var _this = this;
  105696. return Promise.resolve().then(function () {
  105697. var loaderData = _this._parse(data);
  105698. _this._loader = _this._getLoader(loaderData);
  105699. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105700. });
  105701. };
  105702. /**
  105703. * Imports all objects from the loaded glTF data and adds them to the scene
  105704. * @param scene the scene the objects should be added to
  105705. * @param data the glTF data to load
  105706. * @param rootUrl root url to load from
  105707. * @param onProgress event that fires when loading progress has occured
  105708. * @returns a promise which completes when objects have been loaded to the scene
  105709. */
  105710. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105711. var _this = this;
  105712. return Promise.resolve().then(function () {
  105713. var loaderData = _this._parse(data);
  105714. _this._loader = _this._getLoader(loaderData);
  105715. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105716. });
  105717. };
  105718. /**
  105719. * Load into an asset container.
  105720. * @param scene The scene to load into
  105721. * @param data The data to import
  105722. * @param rootUrl The root url for scene and resources
  105723. * @param onProgress The callback when the load progresses
  105724. * @returns The loaded asset container
  105725. */
  105726. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105727. var _this = this;
  105728. return Promise.resolve().then(function () {
  105729. var loaderData = _this._parse(data);
  105730. _this._loader = _this._getLoader(loaderData);
  105731. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105732. var container = new BABYLON.AssetContainer(scene);
  105733. Array.prototype.push.apply(container.meshes, result.meshes);
  105734. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105735. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105736. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  105737. container.removeAllFromScene();
  105738. return container;
  105739. });
  105740. });
  105741. };
  105742. /**
  105743. * If the data string can be loaded directly.
  105744. * @param data string contianing the file data
  105745. * @returns if the data can be loaded directly
  105746. */
  105747. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105748. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105749. };
  105750. /**
  105751. * Instantiates a glTF file loader plugin.
  105752. * @returns the created plugin
  105753. */
  105754. GLTFFileLoader.prototype.createPlugin = function () {
  105755. return new GLTFFileLoader();
  105756. };
  105757. GLTFFileLoader.prototype._parse = function (data) {
  105758. this._startPerformanceCounter("Parse");
  105759. var parsedData;
  105760. if (data instanceof ArrayBuffer) {
  105761. this._log("Parsing binary");
  105762. parsedData = this._parseBinary(data);
  105763. }
  105764. else {
  105765. this._log("Parsing JSON");
  105766. this._log("JSON length: " + data.length);
  105767. parsedData = {
  105768. json: JSON.parse(data),
  105769. bin: null
  105770. };
  105771. }
  105772. this.onParsedObservable.notifyObservers(parsedData);
  105773. this.onParsedObservable.clear();
  105774. this._endPerformanceCounter("Parse");
  105775. return parsedData;
  105776. };
  105777. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105778. var asset = loaderData.json.asset || {};
  105779. this._log("Asset version: " + asset.version);
  105780. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  105781. asset.generator && this._log("Asset generator: " + asset.generator);
  105782. var version = GLTFFileLoader._parseVersion(asset.version);
  105783. if (!version) {
  105784. throw new Error("Invalid version: " + asset.version);
  105785. }
  105786. if (asset.minVersion !== undefined) {
  105787. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105788. if (!minVersion) {
  105789. throw new Error("Invalid minimum version: " + asset.minVersion);
  105790. }
  105791. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  105792. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105793. }
  105794. }
  105795. var createLoaders = {
  105796. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  105797. 2: GLTFFileLoader._CreateGLTFLoaderV2
  105798. };
  105799. var createLoader = createLoaders[version.major];
  105800. if (!createLoader) {
  105801. throw new Error("Unsupported version: " + asset.version);
  105802. }
  105803. return createLoader(this);
  105804. };
  105805. GLTFFileLoader.prototype._parseBinary = function (data) {
  105806. var Binary = {
  105807. Magic: 0x46546C67
  105808. };
  105809. this._log("Binary length: " + data.byteLength);
  105810. var binaryReader = new BinaryReader(data);
  105811. var magic = binaryReader.readUint32();
  105812. if (magic !== Binary.Magic) {
  105813. throw new Error("Unexpected magic: " + magic);
  105814. }
  105815. var version = binaryReader.readUint32();
  105816. if (this.loggingEnabled) {
  105817. this._log("Binary version: " + version);
  105818. }
  105819. switch (version) {
  105820. case 1: return this._parseV1(binaryReader);
  105821. case 2: return this._parseV2(binaryReader);
  105822. }
  105823. throw new Error("Unsupported version: " + version);
  105824. };
  105825. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  105826. var ContentFormat = {
  105827. JSON: 0
  105828. };
  105829. var length = binaryReader.readUint32();
  105830. if (length != binaryReader.getLength()) {
  105831. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105832. }
  105833. var contentLength = binaryReader.readUint32();
  105834. var contentFormat = binaryReader.readUint32();
  105835. var content;
  105836. switch (contentFormat) {
  105837. case ContentFormat.JSON: {
  105838. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105839. break;
  105840. }
  105841. default: {
  105842. throw new Error("Unexpected content format: " + contentFormat);
  105843. }
  105844. }
  105845. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  105846. var body = binaryReader.readUint8Array(bytesRemaining);
  105847. return {
  105848. json: content,
  105849. bin: body
  105850. };
  105851. };
  105852. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  105853. var ChunkFormat = {
  105854. JSON: 0x4E4F534A,
  105855. BIN: 0x004E4942
  105856. };
  105857. var length = binaryReader.readUint32();
  105858. if (length !== binaryReader.getLength()) {
  105859. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105860. }
  105861. // JSON chunk
  105862. var chunkLength = binaryReader.readUint32();
  105863. var chunkFormat = binaryReader.readUint32();
  105864. if (chunkFormat !== ChunkFormat.JSON) {
  105865. throw new Error("First chunk format is not JSON");
  105866. }
  105867. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  105868. // Look for BIN chunk
  105869. var bin = null;
  105870. while (binaryReader.getPosition() < binaryReader.getLength()) {
  105871. var chunkLength_1 = binaryReader.readUint32();
  105872. var chunkFormat_1 = binaryReader.readUint32();
  105873. switch (chunkFormat_1) {
  105874. case ChunkFormat.JSON: {
  105875. throw new Error("Unexpected JSON chunk");
  105876. }
  105877. case ChunkFormat.BIN: {
  105878. bin = binaryReader.readUint8Array(chunkLength_1);
  105879. break;
  105880. }
  105881. default: {
  105882. // ignore unrecognized chunkFormat
  105883. binaryReader.skipBytes(chunkLength_1);
  105884. break;
  105885. }
  105886. }
  105887. }
  105888. return {
  105889. json: json,
  105890. bin: bin
  105891. };
  105892. };
  105893. GLTFFileLoader._parseVersion = function (version) {
  105894. if (version === "1.0" || version === "1.0.1") {
  105895. return {
  105896. major: 1,
  105897. minor: 0
  105898. };
  105899. }
  105900. var match = (version + "").match(/^(\d+)\.(\d+)/);
  105901. if (!match) {
  105902. return null;
  105903. }
  105904. return {
  105905. major: parseInt(match[1]),
  105906. minor: parseInt(match[2])
  105907. };
  105908. };
  105909. GLTFFileLoader._compareVersion = function (a, b) {
  105910. if (a.major > b.major)
  105911. return 1;
  105912. if (a.major < b.major)
  105913. return -1;
  105914. if (a.minor > b.minor)
  105915. return 1;
  105916. if (a.minor < b.minor)
  105917. return -1;
  105918. return 0;
  105919. };
  105920. GLTFFileLoader._decodeBufferToText = function (buffer) {
  105921. var result = "";
  105922. var length = buffer.byteLength;
  105923. for (var i = 0; i < length; i++) {
  105924. result += String.fromCharCode(buffer[i]);
  105925. }
  105926. return result;
  105927. };
  105928. /** @hidden */
  105929. GLTFFileLoader.prototype._logOpen = function (message) {
  105930. this._log(message);
  105931. this._logIndentLevel++;
  105932. };
  105933. /** @hidden */
  105934. GLTFFileLoader.prototype._logClose = function () {
  105935. --this._logIndentLevel;
  105936. };
  105937. GLTFFileLoader.prototype._logEnabled = function (message) {
  105938. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  105939. BABYLON.Tools.Log("" + spaces + message);
  105940. };
  105941. GLTFFileLoader.prototype._logDisabled = function (message) {
  105942. };
  105943. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  105944. BABYLON.Tools.StartPerformanceCounter(counterName);
  105945. };
  105946. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  105947. };
  105948. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  105949. BABYLON.Tools.EndPerformanceCounter(counterName);
  105950. };
  105951. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  105952. };
  105953. // #endregion
  105954. // #region V1 options
  105955. /**
  105956. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.
  105957. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  105958. * Defaults to true.
  105959. * @hidden
  105960. */
  105961. GLTFFileLoader.IncrementalLoading = true;
  105962. /**
  105963. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  105964. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  105965. * @hidden
  105966. */
  105967. GLTFFileLoader.HomogeneousCoordinates = false;
  105968. GLTFFileLoader._logSpaces = " ";
  105969. return GLTFFileLoader;
  105970. }());
  105971. BABYLON.GLTFFileLoader = GLTFFileLoader;
  105972. var BinaryReader = /** @class */ (function () {
  105973. function BinaryReader(arrayBuffer) {
  105974. this._arrayBuffer = arrayBuffer;
  105975. this._dataView = new DataView(arrayBuffer);
  105976. this._byteOffset = 0;
  105977. }
  105978. BinaryReader.prototype.getPosition = function () {
  105979. return this._byteOffset;
  105980. };
  105981. BinaryReader.prototype.getLength = function () {
  105982. return this._arrayBuffer.byteLength;
  105983. };
  105984. BinaryReader.prototype.readUint32 = function () {
  105985. var value = this._dataView.getUint32(this._byteOffset, true);
  105986. this._byteOffset += 4;
  105987. return value;
  105988. };
  105989. BinaryReader.prototype.readUint8Array = function (length) {
  105990. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  105991. this._byteOffset += length;
  105992. return value;
  105993. };
  105994. BinaryReader.prototype.skipBytes = function (length) {
  105995. this._byteOffset += length;
  105996. };
  105997. return BinaryReader;
  105998. }());
  105999. if (BABYLON.SceneLoader) {
  106000. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106001. }
  106002. })(BABYLON || (BABYLON = {}));
  106003. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106004. var BABYLON;
  106005. (function (BABYLON) {
  106006. var GLTF1;
  106007. (function (GLTF1) {
  106008. /**
  106009. * Enums
  106010. */
  106011. var EComponentType;
  106012. (function (EComponentType) {
  106013. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106014. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106015. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106016. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106017. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106018. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106019. var EShaderType;
  106020. (function (EShaderType) {
  106021. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106022. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106023. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106024. var EParameterType;
  106025. (function (EParameterType) {
  106026. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106027. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106028. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106029. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106030. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106031. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106032. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106033. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106034. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106035. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106036. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106037. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106038. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106039. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106040. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106041. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106042. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106043. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106044. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106045. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106046. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106047. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106048. var ETextureWrapMode;
  106049. (function (ETextureWrapMode) {
  106050. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106051. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106052. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106053. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106054. var ETextureFilterType;
  106055. (function (ETextureFilterType) {
  106056. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106057. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106058. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106059. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106060. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106061. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106062. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106063. var ETextureFormat;
  106064. (function (ETextureFormat) {
  106065. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106066. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106067. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106068. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106069. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106070. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106071. var ECullingType;
  106072. (function (ECullingType) {
  106073. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106074. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106075. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106076. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106077. var EBlendingFunction;
  106078. (function (EBlendingFunction) {
  106079. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106080. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106081. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106082. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106083. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106084. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106085. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106086. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106087. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106088. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106089. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106090. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106091. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106092. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106093. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106094. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106095. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106096. })(BABYLON || (BABYLON = {}));
  106097. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106098. var BABYLON;
  106099. (function (BABYLON) {
  106100. var GLTF1;
  106101. (function (GLTF1) {
  106102. /**
  106103. * Tokenizer. Used for shaders compatibility
  106104. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106105. */
  106106. var ETokenType;
  106107. (function (ETokenType) {
  106108. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106109. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106110. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106111. })(ETokenType || (ETokenType = {}));
  106112. var Tokenizer = /** @class */ (function () {
  106113. function Tokenizer(toParse) {
  106114. this._pos = 0;
  106115. this.currentToken = ETokenType.UNKNOWN;
  106116. this.currentIdentifier = "";
  106117. this.currentString = "";
  106118. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106119. this._toParse = toParse;
  106120. this._maxPos = toParse.length;
  106121. }
  106122. Tokenizer.prototype.getNextToken = function () {
  106123. if (this.isEnd())
  106124. return ETokenType.END_OF_INPUT;
  106125. this.currentString = this.read();
  106126. this.currentToken = ETokenType.UNKNOWN;
  106127. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106128. this.currentToken = ETokenType.IDENTIFIER;
  106129. this.currentIdentifier = this.currentString;
  106130. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106131. this.currentIdentifier += this.currentString;
  106132. this.forward();
  106133. }
  106134. }
  106135. return this.currentToken;
  106136. };
  106137. Tokenizer.prototype.peek = function () {
  106138. return this._toParse[this._pos];
  106139. };
  106140. Tokenizer.prototype.read = function () {
  106141. return this._toParse[this._pos++];
  106142. };
  106143. Tokenizer.prototype.forward = function () {
  106144. this._pos++;
  106145. };
  106146. Tokenizer.prototype.isEnd = function () {
  106147. return this._pos >= this._maxPos;
  106148. };
  106149. return Tokenizer;
  106150. }());
  106151. /**
  106152. * Values
  106153. */
  106154. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106155. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106156. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106157. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106158. /**
  106159. * Parse
  106160. */
  106161. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106162. for (var buf in parsedBuffers) {
  106163. var parsedBuffer = parsedBuffers[buf];
  106164. gltfRuntime.buffers[buf] = parsedBuffer;
  106165. gltfRuntime.buffersCount++;
  106166. }
  106167. };
  106168. var parseShaders = function (parsedShaders, gltfRuntime) {
  106169. for (var sha in parsedShaders) {
  106170. var parsedShader = parsedShaders[sha];
  106171. gltfRuntime.shaders[sha] = parsedShader;
  106172. gltfRuntime.shaderscount++;
  106173. }
  106174. };
  106175. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106176. for (var object in parsedObjects) {
  106177. var parsedObject = parsedObjects[object];
  106178. gltfRuntime[runtimeProperty][object] = parsedObject;
  106179. }
  106180. };
  106181. /**
  106182. * Utils
  106183. */
  106184. var normalizeUVs = function (buffer) {
  106185. if (!buffer) {
  106186. return;
  106187. }
  106188. for (var i = 0; i < buffer.length / 2; i++) {
  106189. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106190. }
  106191. };
  106192. var getAttribute = function (attributeParameter) {
  106193. if (attributeParameter.semantic === "NORMAL") {
  106194. return "normal";
  106195. }
  106196. else if (attributeParameter.semantic === "POSITION") {
  106197. return "position";
  106198. }
  106199. else if (attributeParameter.semantic === "JOINT") {
  106200. return "matricesIndices";
  106201. }
  106202. else if (attributeParameter.semantic === "WEIGHT") {
  106203. return "matricesWeights";
  106204. }
  106205. else if (attributeParameter.semantic === "COLOR") {
  106206. return "color";
  106207. }
  106208. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106209. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106210. return "uv" + (channel === 0 ? "" : channel + 1);
  106211. }
  106212. return null;
  106213. };
  106214. /**
  106215. * Loads and creates animations
  106216. */
  106217. var loadAnimations = function (gltfRuntime) {
  106218. for (var anim in gltfRuntime.animations) {
  106219. var animation = gltfRuntime.animations[anim];
  106220. if (!animation.channels || !animation.samplers) {
  106221. continue;
  106222. }
  106223. var lastAnimation = null;
  106224. for (var i = 0; i < animation.channels.length; i++) {
  106225. // Get parameters and load buffers
  106226. var channel = animation.channels[i];
  106227. var sampler = animation.samplers[channel.sampler];
  106228. if (!sampler) {
  106229. continue;
  106230. }
  106231. var inputData = null;
  106232. var outputData = null;
  106233. if (animation.parameters) {
  106234. inputData = animation.parameters[sampler.input];
  106235. outputData = animation.parameters[sampler.output];
  106236. }
  106237. else {
  106238. inputData = sampler.input;
  106239. outputData = sampler.output;
  106240. }
  106241. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106242. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106243. var targetID = channel.target.id;
  106244. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106245. if (targetNode === null) {
  106246. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106247. }
  106248. if (targetNode === null) {
  106249. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106250. continue;
  106251. }
  106252. var isBone = targetNode instanceof BABYLON.Bone;
  106253. // Get target path (position, rotation or scaling)
  106254. var targetPath = channel.target.path;
  106255. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106256. if (targetPathIndex !== -1) {
  106257. targetPath = babylonAnimationPaths[targetPathIndex];
  106258. }
  106259. // Determine animation type
  106260. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106261. if (!isBone) {
  106262. if (targetPath === "rotationQuaternion") {
  106263. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106264. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106265. }
  106266. else {
  106267. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106268. }
  106269. }
  106270. // Create animation and key frames
  106271. var babylonAnimation = null;
  106272. var keys = [];
  106273. var arrayOffset = 0;
  106274. var modifyKey = false;
  106275. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106276. babylonAnimation = lastAnimation;
  106277. modifyKey = true;
  106278. }
  106279. if (!modifyKey) {
  106280. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106281. }
  106282. // For each frame
  106283. for (var j = 0; j < bufferInput.length; j++) {
  106284. var value = null;
  106285. if (targetPath === "rotationQuaternion") { // VEC4
  106286. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106287. arrayOffset += 4;
  106288. }
  106289. else { // Position and scaling are VEC3
  106290. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106291. arrayOffset += 3;
  106292. }
  106293. if (isBone) {
  106294. var bone = targetNode;
  106295. var translation = BABYLON.Vector3.Zero();
  106296. var rotationQuaternion = new BABYLON.Quaternion();
  106297. var scaling = BABYLON.Vector3.Zero();
  106298. // Warning on decompose
  106299. var mat = bone.getBaseMatrix();
  106300. if (modifyKey && lastAnimation) {
  106301. mat = lastAnimation.getKeys()[j].value;
  106302. }
  106303. mat.decompose(scaling, rotationQuaternion, translation);
  106304. if (targetPath === "position") {
  106305. translation = value;
  106306. }
  106307. else if (targetPath === "rotationQuaternion") {
  106308. rotationQuaternion = value;
  106309. }
  106310. else {
  106311. scaling = value;
  106312. }
  106313. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106314. }
  106315. if (!modifyKey) {
  106316. keys.push({
  106317. frame: bufferInput[j],
  106318. value: value
  106319. });
  106320. }
  106321. else if (lastAnimation) {
  106322. lastAnimation.getKeys()[j].value = value;
  106323. }
  106324. }
  106325. // Finish
  106326. if (!modifyKey && babylonAnimation) {
  106327. babylonAnimation.setKeys(keys);
  106328. targetNode.animations.push(babylonAnimation);
  106329. }
  106330. lastAnimation = babylonAnimation;
  106331. gltfRuntime.scene.stopAnimation(targetNode);
  106332. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106333. }
  106334. }
  106335. };
  106336. /**
  106337. * Returns the bones transformation matrix
  106338. */
  106339. var configureBoneTransformation = function (node) {
  106340. var mat = null;
  106341. if (node.translation || node.rotation || node.scale) {
  106342. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106343. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106344. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106345. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106346. }
  106347. else {
  106348. mat = BABYLON.Matrix.FromArray(node.matrix);
  106349. }
  106350. return mat;
  106351. };
  106352. /**
  106353. * Returns the parent bone
  106354. */
  106355. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106356. // Try to find
  106357. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106358. if (newSkeleton.bones[i].name === jointName) {
  106359. return newSkeleton.bones[i];
  106360. }
  106361. }
  106362. // Not found, search in gltf nodes
  106363. var nodes = gltfRuntime.nodes;
  106364. for (var nde in nodes) {
  106365. var node = nodes[nde];
  106366. if (!node.jointName) {
  106367. continue;
  106368. }
  106369. var children = node.children;
  106370. for (var i = 0; i < children.length; i++) {
  106371. var child = gltfRuntime.nodes[children[i]];
  106372. if (!child.jointName) {
  106373. continue;
  106374. }
  106375. if (child.jointName === jointName) {
  106376. var mat = configureBoneTransformation(node);
  106377. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106378. bone.id = nde;
  106379. return bone;
  106380. }
  106381. }
  106382. }
  106383. return null;
  106384. };
  106385. /**
  106386. * Returns the appropriate root node
  106387. */
  106388. var getNodeToRoot = function (nodesToRoot, id) {
  106389. for (var i = 0; i < nodesToRoot.length; i++) {
  106390. var nodeToRoot = nodesToRoot[i];
  106391. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106392. var child = nodeToRoot.node.children[j];
  106393. if (child === id) {
  106394. return nodeToRoot.bone;
  106395. }
  106396. }
  106397. }
  106398. return null;
  106399. };
  106400. /**
  106401. * Returns the node with the joint name
  106402. */
  106403. var getJointNode = function (gltfRuntime, jointName) {
  106404. var nodes = gltfRuntime.nodes;
  106405. var node = nodes[jointName];
  106406. if (node) {
  106407. return {
  106408. node: node,
  106409. id: jointName
  106410. };
  106411. }
  106412. for (var nde in nodes) {
  106413. node = nodes[nde];
  106414. if (node.jointName === jointName) {
  106415. return {
  106416. node: node,
  106417. id: nde
  106418. };
  106419. }
  106420. }
  106421. return null;
  106422. };
  106423. /**
  106424. * Checks if a nodes is in joints
  106425. */
  106426. var nodeIsInJoints = function (skins, id) {
  106427. for (var i = 0; i < skins.jointNames.length; i++) {
  106428. if (skins.jointNames[i] === id) {
  106429. return true;
  106430. }
  106431. }
  106432. return false;
  106433. };
  106434. /**
  106435. * Fills the nodes to root for bones and builds hierarchy
  106436. */
  106437. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106438. // Creates nodes for root
  106439. for (var nde in gltfRuntime.nodes) {
  106440. var node = gltfRuntime.nodes[nde];
  106441. var id = nde;
  106442. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106443. continue;
  106444. }
  106445. // Create node to root bone
  106446. var mat = configureBoneTransformation(node);
  106447. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106448. bone.id = id;
  106449. nodesToRoot.push({ bone: bone, node: node, id: id });
  106450. }
  106451. // Parenting
  106452. for (var i = 0; i < nodesToRoot.length; i++) {
  106453. var nodeToRoot = nodesToRoot[i];
  106454. var children = nodeToRoot.node.children;
  106455. for (var j = 0; j < children.length; j++) {
  106456. var child = null;
  106457. for (var k = 0; k < nodesToRoot.length; k++) {
  106458. if (nodesToRoot[k].id === children[j]) {
  106459. child = nodesToRoot[k];
  106460. break;
  106461. }
  106462. }
  106463. if (child) {
  106464. child.bone._parent = nodeToRoot.bone;
  106465. nodeToRoot.bone.children.push(child.bone);
  106466. }
  106467. }
  106468. }
  106469. };
  106470. /**
  106471. * Imports a skeleton
  106472. */
  106473. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106474. if (!newSkeleton) {
  106475. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106476. }
  106477. if (!skins.babylonSkeleton) {
  106478. return newSkeleton;
  106479. }
  106480. // Find the root bones
  106481. var nodesToRoot = [];
  106482. var nodesToRootToAdd = [];
  106483. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106484. newSkeleton.bones = [];
  106485. // Joints
  106486. for (var i = 0; i < skins.jointNames.length; i++) {
  106487. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106488. if (!jointNode) {
  106489. continue;
  106490. }
  106491. var node = jointNode.node;
  106492. if (!node) {
  106493. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106494. continue;
  106495. }
  106496. var id = jointNode.id;
  106497. // Optimize, if the bone already exists...
  106498. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106499. if (existingBone) {
  106500. newSkeleton.bones.push(existingBone);
  106501. continue;
  106502. }
  106503. // Search for parent bone
  106504. var foundBone = false;
  106505. var parentBone = null;
  106506. for (var j = 0; j < i; j++) {
  106507. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106508. if (!jointNode_1) {
  106509. continue;
  106510. }
  106511. var joint = jointNode_1.node;
  106512. if (!joint) {
  106513. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106514. continue;
  106515. }
  106516. var children = joint.children;
  106517. if (!children) {
  106518. continue;
  106519. }
  106520. foundBone = false;
  106521. for (var k = 0; k < children.length; k++) {
  106522. if (children[k] === id) {
  106523. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106524. foundBone = true;
  106525. break;
  106526. }
  106527. }
  106528. if (foundBone) {
  106529. break;
  106530. }
  106531. }
  106532. // Create bone
  106533. var mat = configureBoneTransformation(node);
  106534. if (!parentBone && nodesToRoot.length > 0) {
  106535. parentBone = getNodeToRoot(nodesToRoot, id);
  106536. if (parentBone) {
  106537. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106538. nodesToRootToAdd.push(parentBone);
  106539. }
  106540. }
  106541. }
  106542. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106543. bone.id = id;
  106544. }
  106545. // Polish
  106546. var bones = newSkeleton.bones;
  106547. newSkeleton.bones = [];
  106548. for (var i = 0; i < skins.jointNames.length; i++) {
  106549. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106550. if (!jointNode) {
  106551. continue;
  106552. }
  106553. for (var j = 0; j < bones.length; j++) {
  106554. if (bones[j].id === jointNode.id) {
  106555. newSkeleton.bones.push(bones[j]);
  106556. break;
  106557. }
  106558. }
  106559. }
  106560. newSkeleton.prepare();
  106561. // Finish
  106562. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106563. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106564. }
  106565. return newSkeleton;
  106566. };
  106567. /**
  106568. * Imports a mesh and its geometries
  106569. */
  106570. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106571. if (!newMesh) {
  106572. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106573. newMesh.id = id;
  106574. }
  106575. if (!node.babylonNode) {
  106576. return newMesh;
  106577. }
  106578. var subMaterials = [];
  106579. var vertexData = null;
  106580. var verticesStarts = new Array();
  106581. var verticesCounts = new Array();
  106582. var indexStarts = new Array();
  106583. var indexCounts = new Array();
  106584. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106585. var meshID = meshes[meshIndex];
  106586. var mesh = gltfRuntime.meshes[meshID];
  106587. if (!mesh) {
  106588. continue;
  106589. }
  106590. // Positions, normals and UVs
  106591. for (var i = 0; i < mesh.primitives.length; i++) {
  106592. // Temporary vertex data
  106593. var tempVertexData = new BABYLON.VertexData();
  106594. var primitive = mesh.primitives[i];
  106595. if (primitive.mode !== 4) {
  106596. // continue;
  106597. }
  106598. var attributes = primitive.attributes;
  106599. var accessor = null;
  106600. var buffer = null;
  106601. // Set positions, normal and uvs
  106602. for (var semantic in attributes) {
  106603. // Link accessor and buffer view
  106604. accessor = gltfRuntime.accessors[attributes[semantic]];
  106605. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106606. if (semantic === "NORMAL") {
  106607. tempVertexData.normals = new Float32Array(buffer.length);
  106608. tempVertexData.normals.set(buffer);
  106609. }
  106610. else if (semantic === "POSITION") {
  106611. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106612. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106613. for (var j = 0; j < buffer.length; j += 4) {
  106614. tempVertexData.positions[j] = buffer[j];
  106615. tempVertexData.positions[j + 1] = buffer[j + 1];
  106616. tempVertexData.positions[j + 2] = buffer[j + 2];
  106617. }
  106618. }
  106619. else {
  106620. tempVertexData.positions = new Float32Array(buffer.length);
  106621. tempVertexData.positions.set(buffer);
  106622. }
  106623. verticesCounts.push(tempVertexData.positions.length);
  106624. }
  106625. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106626. var channel = Number(semantic.split("_")[1]);
  106627. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106628. var uvs = new Float32Array(buffer.length);
  106629. uvs.set(buffer);
  106630. normalizeUVs(uvs);
  106631. tempVertexData.set(uvs, uvKind);
  106632. }
  106633. else if (semantic === "JOINT") {
  106634. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106635. tempVertexData.matricesIndices.set(buffer);
  106636. }
  106637. else if (semantic === "WEIGHT") {
  106638. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106639. tempVertexData.matricesWeights.set(buffer);
  106640. }
  106641. else if (semantic === "COLOR") {
  106642. tempVertexData.colors = new Float32Array(buffer.length);
  106643. tempVertexData.colors.set(buffer);
  106644. }
  106645. }
  106646. // Indices
  106647. accessor = gltfRuntime.accessors[primitive.indices];
  106648. if (accessor) {
  106649. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106650. tempVertexData.indices = new Int32Array(buffer.length);
  106651. tempVertexData.indices.set(buffer);
  106652. indexCounts.push(tempVertexData.indices.length);
  106653. }
  106654. else {
  106655. // Set indices on the fly
  106656. var indices = [];
  106657. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106658. indices.push(j);
  106659. }
  106660. tempVertexData.indices = new Int32Array(indices);
  106661. indexCounts.push(tempVertexData.indices.length);
  106662. }
  106663. if (!vertexData) {
  106664. vertexData = tempVertexData;
  106665. }
  106666. else {
  106667. vertexData.merge(tempVertexData);
  106668. }
  106669. // Sub material
  106670. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106671. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106672. // Update vertices start and index start
  106673. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106674. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106675. }
  106676. }
  106677. var material;
  106678. if (subMaterials.length > 1) {
  106679. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106680. material.subMaterials = subMaterials;
  106681. }
  106682. else {
  106683. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106684. }
  106685. if (subMaterials.length === 1) {
  106686. material = subMaterials[0];
  106687. }
  106688. if (!newMesh.material) {
  106689. newMesh.material = material;
  106690. }
  106691. // Apply geometry
  106692. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106693. newMesh.computeWorldMatrix(true);
  106694. // Apply submeshes
  106695. newMesh.subMeshes = [];
  106696. var index = 0;
  106697. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106698. var meshID = meshes[meshIndex];
  106699. var mesh = gltfRuntime.meshes[meshID];
  106700. if (!mesh) {
  106701. continue;
  106702. }
  106703. for (var i = 0; i < mesh.primitives.length; i++) {
  106704. if (mesh.primitives[i].mode !== 4) {
  106705. //continue;
  106706. }
  106707. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106708. index++;
  106709. }
  106710. }
  106711. // Finish
  106712. return newMesh;
  106713. };
  106714. /**
  106715. * Configure node transformation from position, rotation and scaling
  106716. */
  106717. var configureNode = function (newNode, position, rotation, scaling) {
  106718. if (newNode.position) {
  106719. newNode.position = position;
  106720. }
  106721. if (newNode.rotationQuaternion || newNode.rotation) {
  106722. newNode.rotationQuaternion = rotation;
  106723. }
  106724. if (newNode.scaling) {
  106725. newNode.scaling = scaling;
  106726. }
  106727. };
  106728. /**
  106729. * Configures node from transformation matrix
  106730. */
  106731. var configureNodeFromMatrix = function (newNode, node, parent) {
  106732. if (node.matrix) {
  106733. var position = new BABYLON.Vector3(0, 0, 0);
  106734. var rotation = new BABYLON.Quaternion();
  106735. var scaling = new BABYLON.Vector3(0, 0, 0);
  106736. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106737. mat.decompose(scaling, rotation, position);
  106738. configureNode(newNode, position, rotation, scaling);
  106739. }
  106740. else if (node.translation && node.rotation && node.scale) {
  106741. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106742. }
  106743. newNode.computeWorldMatrix(true);
  106744. };
  106745. /**
  106746. * Imports a node
  106747. */
  106748. var importNode = function (gltfRuntime, node, id, parent) {
  106749. var lastNode = null;
  106750. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106751. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106752. return null;
  106753. }
  106754. }
  106755. // Meshes
  106756. if (node.skin) {
  106757. if (node.meshes) {
  106758. var skin = gltfRuntime.skins[node.skin];
  106759. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106760. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106761. if (newMesh.skeleton === null) {
  106762. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106763. if (!skin.babylonSkeleton) {
  106764. skin.babylonSkeleton = newMesh.skeleton;
  106765. }
  106766. }
  106767. lastNode = newMesh;
  106768. }
  106769. }
  106770. else if (node.meshes) {
  106771. /**
  106772. * Improve meshes property
  106773. */
  106774. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106775. lastNode = newMesh;
  106776. }
  106777. // Lights
  106778. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106779. var light = gltfRuntime.lights[node.light];
  106780. if (light) {
  106781. if (light.type === "ambient") {
  106782. var ambienLight = light[light.type];
  106783. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106784. hemiLight.name = node.name || "";
  106785. if (ambienLight.color) {
  106786. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106787. }
  106788. lastNode = hemiLight;
  106789. }
  106790. else if (light.type === "directional") {
  106791. var directionalLight = light[light.type];
  106792. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106793. dirLight.name = node.name || "";
  106794. if (directionalLight.color) {
  106795. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106796. }
  106797. lastNode = dirLight;
  106798. }
  106799. else if (light.type === "point") {
  106800. var pointLight = light[light.type];
  106801. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106802. ptLight.name = node.name || "";
  106803. if (pointLight.color) {
  106804. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106805. }
  106806. lastNode = ptLight;
  106807. }
  106808. else if (light.type === "spot") {
  106809. var spotLight = light[light.type];
  106810. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106811. spLight.name = node.name || "";
  106812. if (spotLight.color) {
  106813. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106814. }
  106815. if (spotLight.fallOfAngle) {
  106816. spLight.angle = spotLight.fallOfAngle;
  106817. }
  106818. if (spotLight.fallOffExponent) {
  106819. spLight.exponent = spotLight.fallOffExponent;
  106820. }
  106821. lastNode = spLight;
  106822. }
  106823. }
  106824. }
  106825. // Cameras
  106826. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106827. var camera = gltfRuntime.cameras[node.camera];
  106828. if (camera) {
  106829. if (camera.type === "orthographic") {
  106830. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  106831. orthoCamera.name = node.name || "";
  106832. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106833. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106834. lastNode = orthoCamera;
  106835. }
  106836. else if (camera.type === "perspective") {
  106837. var perspectiveCamera = camera[camera.type];
  106838. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  106839. persCamera.name = node.name || "";
  106840. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106841. if (!perspectiveCamera.aspectRatio) {
  106842. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106843. }
  106844. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106845. persCamera.maxZ = perspectiveCamera.zfar;
  106846. persCamera.minZ = perspectiveCamera.znear;
  106847. }
  106848. lastNode = persCamera;
  106849. }
  106850. }
  106851. }
  106852. // Empty node
  106853. if (!node.jointName) {
  106854. if (node.babylonNode) {
  106855. return node.babylonNode;
  106856. }
  106857. else if (lastNode === null) {
  106858. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106859. node.babylonNode = dummy;
  106860. lastNode = dummy;
  106861. }
  106862. }
  106863. if (lastNode !== null) {
  106864. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106865. configureNodeFromMatrix(lastNode, node, parent);
  106866. }
  106867. else {
  106868. var translation = node.translation || [0, 0, 0];
  106869. var rotation = node.rotation || [0, 0, 0, 1];
  106870. var scale = node.scale || [1, 1, 1];
  106871. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106872. }
  106873. lastNode.updateCache(true);
  106874. node.babylonNode = lastNode;
  106875. }
  106876. return lastNode;
  106877. };
  106878. /**
  106879. * Traverses nodes and creates them
  106880. */
  106881. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106882. if (meshIncluded === void 0) { meshIncluded = false; }
  106883. var node = gltfRuntime.nodes[id];
  106884. var newNode = null;
  106885. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  106886. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  106887. meshIncluded = true;
  106888. }
  106889. else {
  106890. meshIncluded = false;
  106891. }
  106892. }
  106893. else {
  106894. meshIncluded = true;
  106895. }
  106896. if (!node.jointName && meshIncluded) {
  106897. newNode = importNode(gltfRuntime, node, id, parent);
  106898. if (newNode !== null) {
  106899. newNode.id = id;
  106900. newNode.parent = parent;
  106901. }
  106902. }
  106903. if (node.children) {
  106904. for (var i = 0; i < node.children.length; i++) {
  106905. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  106906. }
  106907. }
  106908. };
  106909. /**
  106910. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  106911. */
  106912. var postLoad = function (gltfRuntime) {
  106913. // Nodes
  106914. var currentScene = gltfRuntime.currentScene;
  106915. if (currentScene) {
  106916. for (var i = 0; i < currentScene.nodes.length; i++) {
  106917. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106918. }
  106919. }
  106920. else {
  106921. for (var thing in gltfRuntime.scenes) {
  106922. currentScene = gltfRuntime.scenes[thing];
  106923. for (var i = 0; i < currentScene.nodes.length; i++) {
  106924. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106925. }
  106926. }
  106927. }
  106928. // Set animations
  106929. loadAnimations(gltfRuntime);
  106930. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  106931. var skeleton = gltfRuntime.scene.skeletons[i];
  106932. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  106933. }
  106934. };
  106935. /**
  106936. * onBind shaderrs callback to set uniforms and matrices
  106937. */
  106938. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  106939. var materialValues = material.values || technique.parameters;
  106940. for (var unif in unTreatedUniforms) {
  106941. var uniform = unTreatedUniforms[unif];
  106942. var type = uniform.type;
  106943. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  106944. if (uniform.semantic && !uniform.source && !uniform.node) {
  106945. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  106946. }
  106947. else if (uniform.semantic && (uniform.source || uniform.node)) {
  106948. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  106949. if (source === null) {
  106950. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  106951. }
  106952. if (source === null) {
  106953. continue;
  106954. }
  106955. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  106956. }
  106957. }
  106958. else {
  106959. var value = materialValues[technique.uniforms[unif]];
  106960. if (!value) {
  106961. continue;
  106962. }
  106963. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106964. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  106965. if (texture === null || texture === undefined) {
  106966. continue;
  106967. }
  106968. shaderMaterial.getEffect().setTexture(unif, texture);
  106969. }
  106970. else {
  106971. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  106972. }
  106973. }
  106974. }
  106975. onSuccess(shaderMaterial);
  106976. };
  106977. /**
  106978. * Prepare uniforms to send the only one time
  106979. * Loads the appropriate textures
  106980. */
  106981. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  106982. var materialValues = material.values || technique.parameters;
  106983. var techniqueUniforms = technique.uniforms;
  106984. /**
  106985. * Prepare values here (not matrices)
  106986. */
  106987. for (var unif in unTreatedUniforms) {
  106988. var uniform = unTreatedUniforms[unif];
  106989. var type = uniform.type;
  106990. var value = materialValues[techniqueUniforms[unif]];
  106991. if (value === undefined) {
  106992. // In case the value is the same for all materials
  106993. value = uniform.value;
  106994. }
  106995. if (!value) {
  106996. continue;
  106997. }
  106998. var onLoadTexture = function (uniformName) {
  106999. return function (texture) {
  107000. if (uniform.value && uniformName) {
  107001. // Static uniform
  107002. shaderMaterial.setTexture(uniformName, texture);
  107003. delete unTreatedUniforms[uniformName];
  107004. }
  107005. };
  107006. };
  107007. // Texture (sampler2D)
  107008. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107009. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107010. }
  107011. // Others
  107012. else {
  107013. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107014. // Static uniform
  107015. delete unTreatedUniforms[unif];
  107016. }
  107017. }
  107018. }
  107019. };
  107020. /**
  107021. * Shader compilation failed
  107022. */
  107023. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107024. return function (effect, error) {
  107025. shaderMaterial.dispose(true);
  107026. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107027. };
  107028. };
  107029. /**
  107030. * Shader compilation success
  107031. */
  107032. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107033. return function (_) {
  107034. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107035. shaderMaterial.onBind = function (mesh) {
  107036. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107037. };
  107038. };
  107039. };
  107040. /**
  107041. * Returns the appropriate uniform if already handled by babylon
  107042. */
  107043. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107044. for (var unif in technique.uniforms) {
  107045. var uniform = technique.uniforms[unif];
  107046. var uniformParameter = technique.parameters[uniform];
  107047. if (tokenizer.currentIdentifier === unif) {
  107048. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107049. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107050. if (transformIndex !== -1) {
  107051. delete unTreatedUniforms[unif];
  107052. return babylonTransforms[transformIndex];
  107053. }
  107054. }
  107055. }
  107056. }
  107057. return tokenizer.currentIdentifier;
  107058. };
  107059. /**
  107060. * All shaders loaded. Create materials one by one
  107061. */
  107062. var importMaterials = function (gltfRuntime) {
  107063. // Create materials
  107064. for (var mat in gltfRuntime.materials) {
  107065. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107066. }
  107067. };
  107068. /**
  107069. * Implementation of the base glTF spec
  107070. */
  107071. var GLTFLoaderBase = /** @class */ (function () {
  107072. function GLTFLoaderBase() {
  107073. }
  107074. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107075. var gltfRuntime = {
  107076. extensions: {},
  107077. accessors: {},
  107078. buffers: {},
  107079. bufferViews: {},
  107080. meshes: {},
  107081. lights: {},
  107082. cameras: {},
  107083. nodes: {},
  107084. images: {},
  107085. textures: {},
  107086. shaders: {},
  107087. programs: {},
  107088. samplers: {},
  107089. techniques: {},
  107090. materials: {},
  107091. animations: {},
  107092. skins: {},
  107093. extensionsUsed: [],
  107094. scenes: {},
  107095. buffersCount: 0,
  107096. shaderscount: 0,
  107097. scene: scene,
  107098. rootUrl: rootUrl,
  107099. loadedBufferCount: 0,
  107100. loadedBufferViews: {},
  107101. loadedShaderCount: 0,
  107102. importOnlyMeshes: false,
  107103. dummyNodes: []
  107104. };
  107105. // Parse
  107106. if (parsedData.extensions) {
  107107. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107108. }
  107109. if (parsedData.extensionsUsed) {
  107110. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107111. }
  107112. if (parsedData.buffers) {
  107113. parseBuffers(parsedData.buffers, gltfRuntime);
  107114. }
  107115. if (parsedData.bufferViews) {
  107116. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107117. }
  107118. if (parsedData.accessors) {
  107119. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107120. }
  107121. if (parsedData.meshes) {
  107122. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107123. }
  107124. if (parsedData.lights) {
  107125. parseObject(parsedData.lights, "lights", gltfRuntime);
  107126. }
  107127. if (parsedData.cameras) {
  107128. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107129. }
  107130. if (parsedData.nodes) {
  107131. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107132. }
  107133. if (parsedData.images) {
  107134. parseObject(parsedData.images, "images", gltfRuntime);
  107135. }
  107136. if (parsedData.textures) {
  107137. parseObject(parsedData.textures, "textures", gltfRuntime);
  107138. }
  107139. if (parsedData.shaders) {
  107140. parseShaders(parsedData.shaders, gltfRuntime);
  107141. }
  107142. if (parsedData.programs) {
  107143. parseObject(parsedData.programs, "programs", gltfRuntime);
  107144. }
  107145. if (parsedData.samplers) {
  107146. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107147. }
  107148. if (parsedData.techniques) {
  107149. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107150. }
  107151. if (parsedData.materials) {
  107152. parseObject(parsedData.materials, "materials", gltfRuntime);
  107153. }
  107154. if (parsedData.animations) {
  107155. parseObject(parsedData.animations, "animations", gltfRuntime);
  107156. }
  107157. if (parsedData.skins) {
  107158. parseObject(parsedData.skins, "skins", gltfRuntime);
  107159. }
  107160. if (parsedData.scenes) {
  107161. gltfRuntime.scenes = parsedData.scenes;
  107162. }
  107163. if (parsedData.scene && parsedData.scenes) {
  107164. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107165. }
  107166. return gltfRuntime;
  107167. };
  107168. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107169. var buffer = gltfRuntime.buffers[id];
  107170. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107171. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107172. }
  107173. else {
  107174. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107175. if (request) {
  107176. onError(request.status + " " + request.statusText);
  107177. }
  107178. });
  107179. }
  107180. };
  107181. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107182. var texture = gltfRuntime.textures[id];
  107183. if (!texture || !texture.source) {
  107184. onError("");
  107185. return;
  107186. }
  107187. if (texture.babylonTexture) {
  107188. onSuccess(null);
  107189. return;
  107190. }
  107191. var source = gltfRuntime.images[texture.source];
  107192. if (BABYLON.Tools.IsBase64(source.uri)) {
  107193. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107194. }
  107195. else {
  107196. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107197. if (request) {
  107198. onError(request.status + " " + request.statusText);
  107199. }
  107200. });
  107201. }
  107202. };
  107203. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107204. var texture = gltfRuntime.textures[id];
  107205. if (texture.babylonTexture) {
  107206. onSuccess(texture.babylonTexture);
  107207. return;
  107208. }
  107209. var sampler = gltfRuntime.samplers[texture.sampler];
  107210. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107211. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107212. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107213. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107214. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107215. var blob = new Blob([buffer]);
  107216. var blobURL = URL.createObjectURL(blob);
  107217. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107218. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107219. if (sampler.wrapS !== undefined) {
  107220. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107221. }
  107222. if (sampler.wrapT !== undefined) {
  107223. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107224. }
  107225. newTexture.name = id;
  107226. texture.babylonTexture = newTexture;
  107227. onSuccess(newTexture);
  107228. };
  107229. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107230. var shader = gltfRuntime.shaders[id];
  107231. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107232. var shaderString = atob(shader.uri.split(",")[1]);
  107233. if (onSuccess) {
  107234. onSuccess(shaderString);
  107235. }
  107236. }
  107237. else {
  107238. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107239. if (request && onError) {
  107240. onError(request.status + " " + request.statusText);
  107241. }
  107242. });
  107243. }
  107244. };
  107245. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107246. var material = gltfRuntime.materials[id];
  107247. if (!material.technique) {
  107248. if (onError) {
  107249. onError("No technique found.");
  107250. }
  107251. return;
  107252. }
  107253. var technique = gltfRuntime.techniques[material.technique];
  107254. if (!technique) {
  107255. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107256. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107257. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107258. onSuccess(defaultMaterial);
  107259. return;
  107260. }
  107261. var program = gltfRuntime.programs[technique.program];
  107262. var states = technique.states;
  107263. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107264. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107265. var newVertexShader = "";
  107266. var newPixelShader = "";
  107267. var vertexTokenizer = new Tokenizer(vertexShader);
  107268. var pixelTokenizer = new Tokenizer(pixelShader);
  107269. var unTreatedUniforms = {};
  107270. var uniforms = [];
  107271. var attributes = [];
  107272. var samplers = [];
  107273. // Fill uniform, sampler2D and attributes
  107274. for (var unif in technique.uniforms) {
  107275. var uniform = technique.uniforms[unif];
  107276. var uniformParameter = technique.parameters[uniform];
  107277. unTreatedUniforms[unif] = uniformParameter;
  107278. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107279. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107280. if (transformIndex !== -1) {
  107281. uniforms.push(babylonTransforms[transformIndex]);
  107282. delete unTreatedUniforms[unif];
  107283. }
  107284. else {
  107285. uniforms.push(unif);
  107286. }
  107287. }
  107288. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107289. samplers.push(unif);
  107290. }
  107291. else {
  107292. uniforms.push(unif);
  107293. }
  107294. }
  107295. for (var attr in technique.attributes) {
  107296. var attribute = technique.attributes[attr];
  107297. var attributeParameter = technique.parameters[attribute];
  107298. if (attributeParameter.semantic) {
  107299. attributes.push(getAttribute(attributeParameter));
  107300. }
  107301. }
  107302. // Configure vertex shader
  107303. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107304. var tokenType = vertexTokenizer.currentToken;
  107305. if (tokenType !== ETokenType.IDENTIFIER) {
  107306. newVertexShader += vertexTokenizer.currentString;
  107307. continue;
  107308. }
  107309. var foundAttribute = false;
  107310. for (var attr in technique.attributes) {
  107311. var attribute = technique.attributes[attr];
  107312. var attributeParameter = technique.parameters[attribute];
  107313. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107314. newVertexShader += getAttribute(attributeParameter);
  107315. foundAttribute = true;
  107316. break;
  107317. }
  107318. }
  107319. if (foundAttribute) {
  107320. continue;
  107321. }
  107322. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107323. }
  107324. // Configure pixel shader
  107325. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107326. var tokenType = pixelTokenizer.currentToken;
  107327. if (tokenType !== ETokenType.IDENTIFIER) {
  107328. newPixelShader += pixelTokenizer.currentString;
  107329. continue;
  107330. }
  107331. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107332. }
  107333. // Create shader material
  107334. var shaderPath = {
  107335. vertex: program.vertexShader + id,
  107336. fragment: program.fragmentShader + id
  107337. };
  107338. var options = {
  107339. attributes: attributes,
  107340. uniforms: uniforms,
  107341. samplers: samplers,
  107342. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107343. };
  107344. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107345. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107346. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107347. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107348. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107349. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107350. if (states && states.functions) {
  107351. var functions = states.functions;
  107352. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107353. shaderMaterial.backFaceCulling = false;
  107354. }
  107355. var blendFunc = functions.blendFuncSeparate;
  107356. if (blendFunc) {
  107357. 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) {
  107358. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107359. }
  107360. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107361. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107362. }
  107363. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107364. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107365. }
  107366. 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) {
  107367. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107368. }
  107369. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107370. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107371. }
  107372. 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) {
  107373. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107374. }
  107375. }
  107376. }
  107377. };
  107378. return GLTFLoaderBase;
  107379. }());
  107380. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107381. /**
  107382. * glTF V1 Loader
  107383. */
  107384. var GLTFLoader = /** @class */ (function () {
  107385. function GLTFLoader() {
  107386. this.state = null;
  107387. }
  107388. GLTFLoader.RegisterExtension = function (extension) {
  107389. if (GLTFLoader.Extensions[extension.name]) {
  107390. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107391. return;
  107392. }
  107393. GLTFLoader.Extensions[extension.name] = extension;
  107394. };
  107395. GLTFLoader.prototype.dispose = function () {
  107396. // do nothing
  107397. };
  107398. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107399. var _this = this;
  107400. scene.useRightHandedSystem = true;
  107401. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107402. gltfRuntime.importOnlyMeshes = true;
  107403. if (meshesNames === "") {
  107404. gltfRuntime.importMeshesNames = [];
  107405. }
  107406. else if (typeof meshesNames === "string") {
  107407. gltfRuntime.importMeshesNames = [meshesNames];
  107408. }
  107409. else if (meshesNames && !(meshesNames instanceof Array)) {
  107410. gltfRuntime.importMeshesNames = [meshesNames];
  107411. }
  107412. else {
  107413. gltfRuntime.importMeshesNames = [];
  107414. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107415. }
  107416. // Create nodes
  107417. _this._createNodes(gltfRuntime);
  107418. var meshes = new Array();
  107419. var skeletons = new Array();
  107420. // Fill arrays of meshes and skeletons
  107421. for (var nde in gltfRuntime.nodes) {
  107422. var node = gltfRuntime.nodes[nde];
  107423. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107424. meshes.push(node.babylonNode);
  107425. }
  107426. }
  107427. for (var skl in gltfRuntime.skins) {
  107428. var skin = gltfRuntime.skins[skl];
  107429. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107430. skeletons.push(skin.babylonSkeleton);
  107431. }
  107432. }
  107433. // Load buffers, shaders, materials, etc.
  107434. _this._loadBuffersAsync(gltfRuntime, function () {
  107435. _this._loadShadersAsync(gltfRuntime, function () {
  107436. importMaterials(gltfRuntime);
  107437. postLoad(gltfRuntime);
  107438. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107439. onSuccess(meshes, skeletons);
  107440. }
  107441. });
  107442. }, onProgress);
  107443. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107444. onSuccess(meshes, skeletons);
  107445. }
  107446. }, onError);
  107447. return true;
  107448. };
  107449. /**
  107450. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  107451. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107452. * @param scene the scene the meshes should be added to
  107453. * @param data gltf data containing information of the meshes in a loaded file
  107454. * @param rootUrl root url to load from
  107455. * @param onProgress event that fires when loading progress has occured
  107456. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107457. */
  107458. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107459. var _this = this;
  107460. return new Promise(function (resolve, reject) {
  107461. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  107462. resolve({
  107463. meshes: meshes,
  107464. particleSystems: [],
  107465. skeletons: skeletons,
  107466. animationGroups: []
  107467. });
  107468. }, onProgress, function (message) {
  107469. reject(new Error(message));
  107470. });
  107471. });
  107472. };
  107473. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107474. var _this = this;
  107475. scene.useRightHandedSystem = true;
  107476. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107477. // Load runtime extensios
  107478. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107479. // Create nodes
  107480. _this._createNodes(gltfRuntime);
  107481. // Load buffers, shaders, materials, etc.
  107482. _this._loadBuffersAsync(gltfRuntime, function () {
  107483. _this._loadShadersAsync(gltfRuntime, function () {
  107484. importMaterials(gltfRuntime);
  107485. postLoad(gltfRuntime);
  107486. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107487. onSuccess();
  107488. }
  107489. });
  107490. });
  107491. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107492. onSuccess();
  107493. }
  107494. }, onError);
  107495. }, onError);
  107496. };
  107497. /**
  107498. * Imports all objects from a loaded gltf file and adds them to the scene
  107499. * @param scene the scene the objects should be added to
  107500. * @param data gltf data containing information of the meshes in a loaded file
  107501. * @param rootUrl root url to load from
  107502. * @param onProgress event that fires when loading progress has occured
  107503. * @returns a promise which completes when objects have been loaded to the scene
  107504. */
  107505. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107506. var _this = this;
  107507. return new Promise(function (resolve, reject) {
  107508. _this._loadAsync(scene, data, rootUrl, function () {
  107509. resolve();
  107510. }, onProgress, function (message) {
  107511. reject(new Error(message));
  107512. });
  107513. });
  107514. };
  107515. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107516. var hasShaders = false;
  107517. var processShader = function (sha, shader) {
  107518. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107519. if (shaderString instanceof ArrayBuffer) {
  107520. return;
  107521. }
  107522. gltfRuntime.loadedShaderCount++;
  107523. if (shaderString) {
  107524. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107525. }
  107526. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107527. onload();
  107528. }
  107529. }, function () {
  107530. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107531. });
  107532. };
  107533. for (var sha in gltfRuntime.shaders) {
  107534. hasShaders = true;
  107535. var shader = gltfRuntime.shaders[sha];
  107536. if (shader) {
  107537. processShader.bind(this, sha, shader)();
  107538. }
  107539. else {
  107540. BABYLON.Tools.Error("No shader named: " + sha);
  107541. }
  107542. }
  107543. if (!hasShaders) {
  107544. onload();
  107545. }
  107546. };
  107547. ;
  107548. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107549. var hasBuffers = false;
  107550. var processBuffer = function (buf, buffer) {
  107551. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107552. gltfRuntime.loadedBufferCount++;
  107553. if (bufferView) {
  107554. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107555. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107556. }
  107557. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107558. }
  107559. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107560. onLoad();
  107561. }
  107562. }, function () {
  107563. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107564. });
  107565. };
  107566. for (var buf in gltfRuntime.buffers) {
  107567. hasBuffers = true;
  107568. var buffer = gltfRuntime.buffers[buf];
  107569. if (buffer) {
  107570. processBuffer.bind(this, buf, buffer)();
  107571. }
  107572. else {
  107573. BABYLON.Tools.Error("No buffer named: " + buf);
  107574. }
  107575. }
  107576. if (!hasBuffers) {
  107577. onLoad();
  107578. }
  107579. };
  107580. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107581. var currentScene = gltfRuntime.currentScene;
  107582. if (currentScene) {
  107583. // Only one scene even if multiple scenes are defined
  107584. for (var i = 0; i < currentScene.nodes.length; i++) {
  107585. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107586. }
  107587. }
  107588. else {
  107589. // Load all scenes
  107590. for (var thing in gltfRuntime.scenes) {
  107591. currentScene = gltfRuntime.scenes[thing];
  107592. for (var i = 0; i < currentScene.nodes.length; i++) {
  107593. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107594. }
  107595. }
  107596. }
  107597. };
  107598. GLTFLoader.Extensions = {};
  107599. return GLTFLoader;
  107600. }());
  107601. GLTF1.GLTFLoader = GLTFLoader;
  107602. ;
  107603. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107604. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107605. })(BABYLON || (BABYLON = {}));
  107606. //# sourceMappingURL=babylon.glTFLoader.js.map
  107607. var BABYLON;
  107608. (function (BABYLON) {
  107609. var GLTF1;
  107610. (function (GLTF1) {
  107611. /**
  107612. * Utils functions for GLTF
  107613. */
  107614. var GLTFUtils = /** @class */ (function () {
  107615. function GLTFUtils() {
  107616. }
  107617. /**
  107618. * Sets the given "parameter" matrix
  107619. * @param scene: the {BABYLON.Scene} object
  107620. * @param source: the source node where to pick the matrix
  107621. * @param parameter: the GLTF technique parameter
  107622. * @param uniformName: the name of the shader's uniform
  107623. * @param shaderMaterial: the shader material
  107624. */
  107625. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107626. var mat = null;
  107627. if (parameter.semantic === "MODEL") {
  107628. mat = source.getWorldMatrix();
  107629. }
  107630. else if (parameter.semantic === "PROJECTION") {
  107631. mat = scene.getProjectionMatrix();
  107632. }
  107633. else if (parameter.semantic === "VIEW") {
  107634. mat = scene.getViewMatrix();
  107635. }
  107636. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107637. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107638. }
  107639. else if (parameter.semantic === "MODELVIEW") {
  107640. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107641. }
  107642. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107643. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107644. }
  107645. else if (parameter.semantic === "MODELINVERSE") {
  107646. mat = source.getWorldMatrix().invert();
  107647. }
  107648. else if (parameter.semantic === "VIEWINVERSE") {
  107649. mat = scene.getViewMatrix().invert();
  107650. }
  107651. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107652. mat = scene.getProjectionMatrix().invert();
  107653. }
  107654. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107655. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107656. }
  107657. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107658. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107659. }
  107660. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107661. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107662. }
  107663. else {
  107664. debugger;
  107665. }
  107666. if (mat) {
  107667. switch (parameter.type) {
  107668. case GLTF1.EParameterType.FLOAT_MAT2:
  107669. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107670. break;
  107671. case GLTF1.EParameterType.FLOAT_MAT3:
  107672. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107673. break;
  107674. case GLTF1.EParameterType.FLOAT_MAT4:
  107675. shaderMaterial.setMatrix(uniformName, mat);
  107676. break;
  107677. default: break;
  107678. }
  107679. }
  107680. };
  107681. /**
  107682. * Sets the given "parameter" matrix
  107683. * @param shaderMaterial: the shader material
  107684. * @param uniform: the name of the shader's uniform
  107685. * @param value: the value of the uniform
  107686. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107687. */
  107688. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107689. switch (type) {
  107690. case GLTF1.EParameterType.FLOAT:
  107691. shaderMaterial.setFloat(uniform, value);
  107692. return true;
  107693. case GLTF1.EParameterType.FLOAT_VEC2:
  107694. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107695. return true;
  107696. case GLTF1.EParameterType.FLOAT_VEC3:
  107697. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107698. return true;
  107699. case GLTF1.EParameterType.FLOAT_VEC4:
  107700. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107701. return true;
  107702. default: return false;
  107703. }
  107704. };
  107705. /**
  107706. * Returns the wrap mode of the texture
  107707. * @param mode: the mode value
  107708. */
  107709. GLTFUtils.GetWrapMode = function (mode) {
  107710. switch (mode) {
  107711. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107712. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107713. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107714. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107715. }
  107716. };
  107717. /**
  107718. * Returns the byte stride giving an accessor
  107719. * @param accessor: the GLTF accessor objet
  107720. */
  107721. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107722. // Needs this function since "byteStride" isn't requiered in glTF format
  107723. var type = accessor.type;
  107724. switch (type) {
  107725. case "VEC2": return 2;
  107726. case "VEC3": return 3;
  107727. case "VEC4": return 4;
  107728. case "MAT2": return 4;
  107729. case "MAT3": return 9;
  107730. case "MAT4": return 16;
  107731. default: return 1;
  107732. }
  107733. };
  107734. /**
  107735. * Returns the texture filter mode giving a mode value
  107736. * @param mode: the filter mode value
  107737. */
  107738. GLTFUtils.GetTextureFilterMode = function (mode) {
  107739. switch (mode) {
  107740. case GLTF1.ETextureFilterType.LINEAR:
  107741. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107742. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107743. case GLTF1.ETextureFilterType.NEAREST:
  107744. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107745. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107746. }
  107747. };
  107748. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107749. var byteOffset = bufferView.byteOffset + byteOffset;
  107750. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107751. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107752. throw new Error("Buffer access is out of range");
  107753. }
  107754. var buffer = loadedBufferView.buffer;
  107755. byteOffset += loadedBufferView.byteOffset;
  107756. switch (componentType) {
  107757. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107758. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107759. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107760. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107761. default: return new Float32Array(buffer, byteOffset, byteLength);
  107762. }
  107763. };
  107764. /**
  107765. * Returns a buffer from its accessor
  107766. * @param gltfRuntime: the GLTF runtime
  107767. * @param accessor: the GLTF accessor
  107768. */
  107769. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107770. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107771. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107772. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107773. };
  107774. /**
  107775. * Decodes a buffer view into a string
  107776. * @param view: the buffer view
  107777. */
  107778. GLTFUtils.DecodeBufferToText = function (view) {
  107779. var result = "";
  107780. var length = view.byteLength;
  107781. for (var i = 0; i < length; ++i) {
  107782. result += String.fromCharCode(view[i]);
  107783. }
  107784. return result;
  107785. };
  107786. /**
  107787. * Returns the default material of gltf. Related to
  107788. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107789. * @param scene: the Babylon.js scene
  107790. */
  107791. GLTFUtils.GetDefaultMaterial = function (scene) {
  107792. if (!GLTFUtils._DefaultMaterial) {
  107793. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107794. "precision highp float;",
  107795. "",
  107796. "uniform mat4 worldView;",
  107797. "uniform mat4 projection;",
  107798. "",
  107799. "attribute vec3 position;",
  107800. "",
  107801. "void main(void)",
  107802. "{",
  107803. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107804. "}"
  107805. ].join("\n");
  107806. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107807. "precision highp float;",
  107808. "",
  107809. "uniform vec4 u_emission;",
  107810. "",
  107811. "void main(void)",
  107812. "{",
  107813. " gl_FragColor = u_emission;",
  107814. "}"
  107815. ].join("\n");
  107816. var shaderPath = {
  107817. vertex: "GLTFDefaultMaterial",
  107818. fragment: "GLTFDefaultMaterial"
  107819. };
  107820. var options = {
  107821. attributes: ["position"],
  107822. uniforms: ["worldView", "projection", "u_emission"],
  107823. samplers: new Array(),
  107824. needAlphaBlending: false
  107825. };
  107826. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107827. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107828. }
  107829. return GLTFUtils._DefaultMaterial;
  107830. };
  107831. // The GLTF default material
  107832. GLTFUtils._DefaultMaterial = null;
  107833. return GLTFUtils;
  107834. }());
  107835. GLTF1.GLTFUtils = GLTFUtils;
  107836. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107837. })(BABYLON || (BABYLON = {}));
  107838. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107839. var BABYLON;
  107840. (function (BABYLON) {
  107841. var GLTF1;
  107842. (function (GLTF1) {
  107843. var GLTFLoaderExtension = /** @class */ (function () {
  107844. function GLTFLoaderExtension(name) {
  107845. this._name = name;
  107846. }
  107847. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107848. get: function () {
  107849. return this._name;
  107850. },
  107851. enumerable: true,
  107852. configurable: true
  107853. });
  107854. /**
  107855. * Defines an override for loading the runtime
  107856. * Return true to stop further extensions from loading the runtime
  107857. */
  107858. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107859. return false;
  107860. };
  107861. /**
  107862. * Defines an onverride for creating gltf runtime
  107863. * Return true to stop further extensions from creating the runtime
  107864. */
  107865. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107866. return false;
  107867. };
  107868. /**
  107869. * Defines an override for loading buffers
  107870. * Return true to stop further extensions from loading this buffer
  107871. */
  107872. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107873. return false;
  107874. };
  107875. /**
  107876. * Defines an override for loading texture buffers
  107877. * Return true to stop further extensions from loading this texture data
  107878. */
  107879. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107880. return false;
  107881. };
  107882. /**
  107883. * Defines an override for creating textures
  107884. * Return true to stop further extensions from loading this texture
  107885. */
  107886. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107887. return false;
  107888. };
  107889. /**
  107890. * Defines an override for loading shader strings
  107891. * Return true to stop further extensions from loading this shader data
  107892. */
  107893. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107894. return false;
  107895. };
  107896. /**
  107897. * Defines an override for loading materials
  107898. * Return true to stop further extensions from loading this material
  107899. */
  107900. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107901. return false;
  107902. };
  107903. // ---------
  107904. // Utilities
  107905. // ---------
  107906. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107907. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107908. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  107909. }, function () {
  107910. setTimeout(function () {
  107911. if (!onSuccess) {
  107912. return;
  107913. }
  107914. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107915. });
  107916. });
  107917. };
  107918. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107919. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107920. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  107921. }, function () {
  107922. setTimeout(function () {
  107923. onSuccess();
  107924. });
  107925. });
  107926. };
  107927. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107928. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107929. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107930. }, function () {
  107931. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107932. });
  107933. };
  107934. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  107935. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  107936. if (buffer) {
  107937. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107938. }
  107939. }, onError);
  107940. };
  107941. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107942. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107943. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107944. }, function () {
  107945. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107946. });
  107947. };
  107948. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107949. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107950. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107951. }, function () {
  107952. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107953. });
  107954. };
  107955. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107956. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107957. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107958. }, function () {
  107959. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107960. });
  107961. };
  107962. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107963. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107964. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107965. }, function () {
  107966. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107967. });
  107968. };
  107969. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107970. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107971. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107972. if (func(loaderExtension)) {
  107973. return;
  107974. }
  107975. }
  107976. defaultFunc();
  107977. };
  107978. return GLTFLoaderExtension;
  107979. }());
  107980. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107981. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107982. })(BABYLON || (BABYLON = {}));
  107983. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107984. var BABYLON;
  107985. (function (BABYLON) {
  107986. var GLTF1;
  107987. (function (GLTF1) {
  107988. var BinaryExtensionBufferName = "binary_glTF";
  107989. ;
  107990. ;
  107991. var GLTFBinaryExtension = /** @class */ (function (_super) {
  107992. __extends(GLTFBinaryExtension, _super);
  107993. function GLTFBinaryExtension() {
  107994. return _super.call(this, "KHR_binary_glTF") || this;
  107995. }
  107996. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107997. var extensionsUsed = data.json.extensionsUsed;
  107998. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  107999. return false;
  108000. }
  108001. this._bin = data.bin;
  108002. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108003. return true;
  108004. };
  108005. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108006. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108007. return false;
  108008. }
  108009. if (id !== BinaryExtensionBufferName) {
  108010. return false;
  108011. }
  108012. onSuccess(this._bin);
  108013. return true;
  108014. };
  108015. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108016. var texture = gltfRuntime.textures[id];
  108017. var source = gltfRuntime.images[texture.source];
  108018. if (!source.extensions || !(this.name in source.extensions)) {
  108019. return false;
  108020. }
  108021. var sourceExt = source.extensions[this.name];
  108022. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108023. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108024. onSuccess(buffer);
  108025. return true;
  108026. };
  108027. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108028. var shader = gltfRuntime.shaders[id];
  108029. if (!shader.extensions || !(this.name in shader.extensions)) {
  108030. return false;
  108031. }
  108032. var binaryExtensionShader = shader.extensions[this.name];
  108033. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108034. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108035. setTimeout(function () {
  108036. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108037. onSuccess(shaderString);
  108038. });
  108039. return true;
  108040. };
  108041. return GLTFBinaryExtension;
  108042. }(GLTF1.GLTFLoaderExtension));
  108043. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108044. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108045. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108046. })(BABYLON || (BABYLON = {}));
  108047. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108048. var BABYLON;
  108049. (function (BABYLON) {
  108050. var GLTF1;
  108051. (function (GLTF1) {
  108052. ;
  108053. ;
  108054. ;
  108055. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108056. __extends(GLTFMaterialsCommonExtension, _super);
  108057. function GLTFMaterialsCommonExtension() {
  108058. return _super.call(this, "KHR_materials_common") || this;
  108059. }
  108060. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108061. if (!gltfRuntime.extensions)
  108062. return false;
  108063. var extension = gltfRuntime.extensions[this.name];
  108064. if (!extension)
  108065. return false;
  108066. // Create lights
  108067. var lights = extension.lights;
  108068. if (lights) {
  108069. for (var thing in lights) {
  108070. var light = lights[thing];
  108071. switch (light.type) {
  108072. case "ambient":
  108073. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108074. var ambient = light.ambient;
  108075. if (ambient) {
  108076. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108077. }
  108078. break;
  108079. case "point":
  108080. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108081. var point = light.point;
  108082. if (point) {
  108083. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108084. }
  108085. break;
  108086. case "directional":
  108087. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108088. var directional = light.directional;
  108089. if (directional) {
  108090. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108091. }
  108092. break;
  108093. case "spot":
  108094. var spot = light.spot;
  108095. if (spot) {
  108096. 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);
  108097. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108098. }
  108099. break;
  108100. default:
  108101. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108102. break;
  108103. }
  108104. }
  108105. }
  108106. return false;
  108107. };
  108108. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108109. var material = gltfRuntime.materials[id];
  108110. if (!material || !material.extensions)
  108111. return false;
  108112. var extension = material.extensions[this.name];
  108113. if (!extension)
  108114. return false;
  108115. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108116. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108117. if (extension.technique === "CONSTANT") {
  108118. standardMaterial.disableLighting = true;
  108119. }
  108120. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108121. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108122. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108123. // Ambient
  108124. if (typeof extension.values.ambient === "string") {
  108125. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108126. }
  108127. else {
  108128. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108129. }
  108130. // Diffuse
  108131. if (typeof extension.values.diffuse === "string") {
  108132. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108133. }
  108134. else {
  108135. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108136. }
  108137. // Emission
  108138. if (typeof extension.values.emission === "string") {
  108139. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108140. }
  108141. else {
  108142. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108143. }
  108144. // Specular
  108145. if (typeof extension.values.specular === "string") {
  108146. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108147. }
  108148. else {
  108149. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108150. }
  108151. return true;
  108152. };
  108153. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108154. // Create buffer from texture url
  108155. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108156. // Create texture from buffer
  108157. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108158. }, onError);
  108159. };
  108160. return GLTFMaterialsCommonExtension;
  108161. }(GLTF1.GLTFLoaderExtension));
  108162. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108163. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108164. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108165. })(BABYLON || (BABYLON = {}));
  108166. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108167. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108168. /**
  108169. * Defines the module used to import/export glTF 2.0 assets
  108170. */
  108171. var BABYLON;
  108172. (function (BABYLON) {
  108173. var GLTF2;
  108174. (function (GLTF2) {
  108175. var _ArrayItem = /** @class */ (function () {
  108176. function _ArrayItem() {
  108177. }
  108178. _ArrayItem.Assign = function (values) {
  108179. if (values) {
  108180. for (var index = 0; index < values.length; index++) {
  108181. values[index]._index = index;
  108182. }
  108183. }
  108184. };
  108185. return _ArrayItem;
  108186. }());
  108187. /** @hidden */
  108188. var GLTFLoader = /** @class */ (function () {
  108189. function GLTFLoader(parent) {
  108190. this._completePromises = new Array();
  108191. this._disposed = false;
  108192. this._state = null;
  108193. this._extensions = {};
  108194. this._defaultSampler = {};
  108195. this._defaultBabylonMaterials = {};
  108196. this._requests = new Array();
  108197. this._parent = parent;
  108198. }
  108199. GLTFLoader._Register = function (name, factory) {
  108200. if (GLTFLoader._ExtensionFactories[name]) {
  108201. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108202. return;
  108203. }
  108204. GLTFLoader._ExtensionFactories[name] = factory;
  108205. // Keep the order of registration so that extensions registered first are called first.
  108206. GLTFLoader._ExtensionNames.push(name);
  108207. };
  108208. Object.defineProperty(GLTFLoader.prototype, "state", {
  108209. /**
  108210. * Loader state or null if the loader is not active.
  108211. */
  108212. get: function () {
  108213. return this._state;
  108214. },
  108215. enumerable: true,
  108216. configurable: true
  108217. });
  108218. GLTFLoader.prototype.dispose = function () {
  108219. if (this._disposed) {
  108220. return;
  108221. }
  108222. this._disposed = true;
  108223. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108224. var request = _a[_i];
  108225. request.abort();
  108226. }
  108227. this._requests.length = 0;
  108228. delete this._gltf;
  108229. delete this._babylonScene;
  108230. delete this._readyPromise;
  108231. this._completePromises.length = 0;
  108232. for (var name_1 in this._extensions) {
  108233. this._extensions[name_1].dispose();
  108234. }
  108235. this._extensions = {};
  108236. delete this._rootBabylonMesh;
  108237. delete this._progressCallback;
  108238. this._parent._clear();
  108239. };
  108240. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108241. var _this = this;
  108242. return Promise.resolve().then(function () {
  108243. _this._babylonScene = scene;
  108244. _this._rootUrl = rootUrl;
  108245. _this._progressCallback = onProgress;
  108246. _this._loadData(data);
  108247. var nodes = null;
  108248. if (meshesNames) {
  108249. var nodeMap_1 = {};
  108250. if (_this._gltf.nodes) {
  108251. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108252. var node = _a[_i];
  108253. if (node.name) {
  108254. nodeMap_1[node.name] = node._index;
  108255. }
  108256. }
  108257. }
  108258. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108259. nodes = names.map(function (name) {
  108260. var node = nodeMap_1[name];
  108261. if (node === undefined) {
  108262. throw new Error("Failed to find node '" + name + "'");
  108263. }
  108264. return node;
  108265. });
  108266. }
  108267. return _this._loadAsync(nodes).then(function () {
  108268. return {
  108269. meshes: _this._getMeshes(),
  108270. particleSystems: [],
  108271. skeletons: _this._getSkeletons(),
  108272. animationGroups: _this._getAnimationGroups()
  108273. };
  108274. });
  108275. });
  108276. };
  108277. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108278. var _this = this;
  108279. return Promise.resolve().then(function () {
  108280. _this._babylonScene = scene;
  108281. _this._rootUrl = rootUrl;
  108282. _this._progressCallback = onProgress;
  108283. _this._loadData(data);
  108284. return _this._loadAsync(null);
  108285. });
  108286. };
  108287. GLTFLoader.prototype._loadAsync = function (nodes) {
  108288. var _this = this;
  108289. return Promise.resolve().then(function () {
  108290. _this._parent._startPerformanceCounter("Loading => Ready");
  108291. _this._parent._startPerformanceCounter("Loading => Complete");
  108292. _this._state = BABYLON.GLTFLoaderState.LOADING;
  108293. _this._parent._log("Loading");
  108294. var readyDeferred = new BABYLON.Deferred();
  108295. _this._readyPromise = readyDeferred.promise;
  108296. _this._loadExtensions();
  108297. _this._checkExtensions();
  108298. var promises = new Array();
  108299. if (nodes) {
  108300. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  108301. }
  108302. else {
  108303. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108304. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  108305. }
  108306. if (_this._parent.compileMaterials) {
  108307. promises.push(_this._compileMaterialsAsync());
  108308. }
  108309. if (_this._parent.compileShadowGenerators) {
  108310. promises.push(_this._compileShadowGeneratorsAsync());
  108311. }
  108312. var resultPromise = Promise.all(promises).then(function () {
  108313. _this._state = BABYLON.GLTFLoaderState.READY;
  108314. _this._parent._log("Ready");
  108315. readyDeferred.resolve();
  108316. _this._startAnimations();
  108317. });
  108318. resultPromise.then(function () {
  108319. _this._parent._endPerformanceCounter("Loading => Ready");
  108320. BABYLON.Tools.SetImmediate(function () {
  108321. if (!_this._disposed) {
  108322. Promise.all(_this._completePromises).then(function () {
  108323. _this._parent._endPerformanceCounter("Loading => Complete");
  108324. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  108325. _this._parent._log("Complete");
  108326. _this._parent.onCompleteObservable.notifyObservers(undefined);
  108327. _this._parent.onCompleteObservable.clear();
  108328. _this.dispose();
  108329. }).catch(function (error) {
  108330. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108331. _this.dispose();
  108332. });
  108333. }
  108334. });
  108335. });
  108336. return resultPromise;
  108337. }).catch(function (error) {
  108338. if (!_this._disposed) {
  108339. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108340. _this.dispose();
  108341. throw error;
  108342. }
  108343. });
  108344. };
  108345. GLTFLoader.prototype._loadData = function (data) {
  108346. this._gltf = data.json;
  108347. this._setupData();
  108348. if (data.bin) {
  108349. var buffers = this._gltf.buffers;
  108350. if (buffers && buffers[0] && !buffers[0].uri) {
  108351. var binaryBuffer = buffers[0];
  108352. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108353. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108354. }
  108355. binaryBuffer._data = Promise.resolve(data.bin);
  108356. }
  108357. else {
  108358. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108359. }
  108360. }
  108361. };
  108362. GLTFLoader.prototype._setupData = function () {
  108363. _ArrayItem.Assign(this._gltf.accessors);
  108364. _ArrayItem.Assign(this._gltf.animations);
  108365. _ArrayItem.Assign(this._gltf.buffers);
  108366. _ArrayItem.Assign(this._gltf.bufferViews);
  108367. _ArrayItem.Assign(this._gltf.cameras);
  108368. _ArrayItem.Assign(this._gltf.images);
  108369. _ArrayItem.Assign(this._gltf.materials);
  108370. _ArrayItem.Assign(this._gltf.meshes);
  108371. _ArrayItem.Assign(this._gltf.nodes);
  108372. _ArrayItem.Assign(this._gltf.samplers);
  108373. _ArrayItem.Assign(this._gltf.scenes);
  108374. _ArrayItem.Assign(this._gltf.skins);
  108375. _ArrayItem.Assign(this._gltf.textures);
  108376. if (this._gltf.nodes) {
  108377. var nodeParents = {};
  108378. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108379. var node = _a[_i];
  108380. if (node.children) {
  108381. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108382. var index = _c[_b];
  108383. nodeParents[index] = node._index;
  108384. }
  108385. }
  108386. }
  108387. var rootNode = this._createRootNode();
  108388. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108389. var node = _e[_d];
  108390. var parentIndex = nodeParents[node._index];
  108391. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108392. }
  108393. }
  108394. };
  108395. GLTFLoader.prototype._loadExtensions = function () {
  108396. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  108397. var name_2 = _a[_i];
  108398. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  108399. this._extensions[name_2] = extension;
  108400. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  108401. }
  108402. this._parent.onExtensionLoadedObservable.clear();
  108403. };
  108404. GLTFLoader.prototype._checkExtensions = function () {
  108405. if (this._gltf.extensionsRequired) {
  108406. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108407. var name_3 = _a[_i];
  108408. var extension = this._extensions[name_3];
  108409. if (!extension || !extension.enabled) {
  108410. throw new Error("Require extension " + name_3 + " is not available");
  108411. }
  108412. }
  108413. }
  108414. };
  108415. GLTFLoader.prototype._createRootNode = function () {
  108416. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108417. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108418. switch (this._parent.coordinateSystemMode) {
  108419. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108420. if (!this._babylonScene.useRightHandedSystem) {
  108421. rootNode.rotation = [0, 1, 0, 0];
  108422. rootNode.scale = [1, 1, -1];
  108423. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108424. }
  108425. break;
  108426. }
  108427. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108428. this._babylonScene.useRightHandedSystem = true;
  108429. break;
  108430. }
  108431. default: {
  108432. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  108433. }
  108434. }
  108435. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108436. return rootNode;
  108437. };
  108438. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108439. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108440. if (promise) {
  108441. return promise;
  108442. }
  108443. var promises = new Array();
  108444. this._parent._logOpen(context + " " + (scene.name || ""));
  108445. if (scene.nodes) {
  108446. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108447. var index = _a[_i];
  108448. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108449. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108450. }
  108451. }
  108452. promises.push(this._loadAnimationsAsync());
  108453. this._parent._logClose();
  108454. return Promise.all(promises).then(function () { });
  108455. };
  108456. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  108457. if (node._primitiveBabylonMeshes) {
  108458. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108459. var babylonMesh = _a[_i];
  108460. callback(babylonMesh);
  108461. }
  108462. }
  108463. else {
  108464. callback(node._babylonMesh);
  108465. }
  108466. };
  108467. GLTFLoader.prototype._getMeshes = function () {
  108468. var meshes = new Array();
  108469. // Root mesh is always first.
  108470. meshes.push(this._rootBabylonMesh);
  108471. var nodes = this._gltf.nodes;
  108472. if (nodes) {
  108473. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108474. var node = nodes_1[_i];
  108475. if (node._babylonMesh) {
  108476. meshes.push(node._babylonMesh);
  108477. }
  108478. if (node._primitiveBabylonMeshes) {
  108479. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  108480. var babylonMesh = _b[_a];
  108481. meshes.push(babylonMesh);
  108482. }
  108483. }
  108484. }
  108485. }
  108486. return meshes;
  108487. };
  108488. GLTFLoader.prototype._getSkeletons = function () {
  108489. var skeletons = new Array();
  108490. var skins = this._gltf.skins;
  108491. if (skins) {
  108492. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108493. var skin = skins_1[_i];
  108494. if (skin._babylonSkeleton) {
  108495. skeletons.push(skin._babylonSkeleton);
  108496. }
  108497. }
  108498. }
  108499. return skeletons;
  108500. };
  108501. GLTFLoader.prototype._getAnimationGroups = function () {
  108502. var animationGroups = new Array();
  108503. var animations = this._gltf.animations;
  108504. if (animations) {
  108505. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108506. var animation = animations_1[_i];
  108507. if (animation._babylonAnimationGroup) {
  108508. animationGroups.push(animation._babylonAnimationGroup);
  108509. }
  108510. }
  108511. }
  108512. return animationGroups;
  108513. };
  108514. GLTFLoader.prototype._startAnimations = function () {
  108515. switch (this._parent.animationStartMode) {
  108516. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108517. // do nothing
  108518. break;
  108519. }
  108520. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108521. var babylonAnimationGroups = this._getAnimationGroups();
  108522. if (babylonAnimationGroups.length !== 0) {
  108523. babylonAnimationGroups[0].start(true);
  108524. }
  108525. break;
  108526. }
  108527. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108528. var babylonAnimationGroups = this._getAnimationGroups();
  108529. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  108530. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  108531. babylonAnimationGroup.start(true);
  108532. }
  108533. break;
  108534. }
  108535. default: {
  108536. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  108537. return;
  108538. }
  108539. }
  108540. };
  108541. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108542. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108543. if (promise) {
  108544. return promise;
  108545. }
  108546. if (node._babylonMesh) {
  108547. throw new Error(context + ": Invalid recursive node hierarchy");
  108548. }
  108549. var promises = new Array();
  108550. this._parent._logOpen(context + " " + (node.name || ""));
  108551. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  108552. node._babylonMesh = babylonMesh;
  108553. babylonMesh.setEnabled(false);
  108554. GLTFLoader._LoadTransform(node, babylonMesh);
  108555. if (node.mesh != undefined) {
  108556. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108557. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108558. }
  108559. if (node.camera != undefined) {
  108560. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  108561. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  108562. }
  108563. if (node.children) {
  108564. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108565. var index = _a[_i];
  108566. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108567. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108568. }
  108569. }
  108570. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108571. this._parent._logClose();
  108572. return Promise.all(promises).then(function () {
  108573. babylonMesh.setEnabled(true);
  108574. });
  108575. };
  108576. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108577. var _this = this;
  108578. var promises = new Array();
  108579. this._parent._logOpen(context + " " + (mesh.name || ""));
  108580. var primitives = mesh.primitives;
  108581. if (!primitives || primitives.length === 0) {
  108582. throw new Error(context + ": Primitives are missing");
  108583. }
  108584. _ArrayItem.Assign(primitives);
  108585. if (primitives.length === 1) {
  108586. var primitive = primitives[0];
  108587. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108588. }
  108589. else {
  108590. node._primitiveBabylonMeshes = [];
  108591. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108592. var primitive = primitives_1[_i];
  108593. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108594. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  108595. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108596. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108597. }
  108598. }
  108599. if (node.skin != undefined) {
  108600. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108601. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108602. }
  108603. this._parent._logClose();
  108604. return Promise.all(promises).then(function () {
  108605. _this._forEachPrimitive(node, function (babylonMesh) {
  108606. babylonMesh._refreshBoundingInfo(true);
  108607. });
  108608. });
  108609. };
  108610. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108611. var _this = this;
  108612. var promises = new Array();
  108613. this._parent._logOpen("" + context);
  108614. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108615. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  108616. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  108617. babylonGeometry.applyToMesh(babylonMesh);
  108618. });
  108619. }));
  108620. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  108621. if (primitive.material == undefined) {
  108622. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  108623. }
  108624. else {
  108625. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108626. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  108627. babylonMesh.material = babylonMaterial;
  108628. }));
  108629. }
  108630. this._parent._logClose();
  108631. return Promise.all(promises).then(function () { });
  108632. };
  108633. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108634. var _this = this;
  108635. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108636. if (promise) {
  108637. return promise;
  108638. }
  108639. var attributes = primitive.attributes;
  108640. if (!attributes) {
  108641. throw new Error(context + ": Attributes are missing");
  108642. }
  108643. var promises = new Array();
  108644. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  108645. if (primitive.indices == undefined) {
  108646. babylonMesh.isUnIndexed = true;
  108647. }
  108648. else {
  108649. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108650. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108651. babylonGeometry.setIndices(data);
  108652. }));
  108653. }
  108654. var loadAttribute = function (attribute, kind, callback) {
  108655. if (attributes[attribute] == undefined) {
  108656. return;
  108657. }
  108658. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108659. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108660. babylonMesh._delayInfo.push(kind);
  108661. }
  108662. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108663. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  108664. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  108665. }));
  108666. if (callback) {
  108667. callback(accessor);
  108668. }
  108669. };
  108670. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108671. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108672. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108673. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108674. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108675. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108676. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108677. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  108678. if (accessor.type === "VEC4" /* VEC4 */) {
  108679. babylonMesh.hasVertexAlpha = true;
  108680. }
  108681. });
  108682. return Promise.all(promises).then(function () {
  108683. return babylonGeometry;
  108684. });
  108685. };
  108686. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108687. if (!primitive.targets) {
  108688. return;
  108689. }
  108690. if (node._numMorphTargets == undefined) {
  108691. node._numMorphTargets = primitive.targets.length;
  108692. }
  108693. else if (primitive.targets.length !== node._numMorphTargets) {
  108694. throw new Error(context + ": Primitives do not have the same number of targets");
  108695. }
  108696. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108697. for (var index = 0; index < primitive.targets.length; index++) {
  108698. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108699. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108700. // TODO: tell the target whether it has positions, normals, tangents
  108701. }
  108702. };
  108703. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  108704. if (!primitive.targets) {
  108705. return Promise.resolve();
  108706. }
  108707. var promises = new Array();
  108708. var morphTargetManager = babylonMesh.morphTargetManager;
  108709. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108710. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108711. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  108712. }
  108713. return Promise.all(promises).then(function () { });
  108714. };
  108715. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  108716. var _this = this;
  108717. var promises = new Array();
  108718. var loadAttribute = function (attribute, kind, setData) {
  108719. if (attributes[attribute] == undefined) {
  108720. return;
  108721. }
  108722. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  108723. if (!babylonVertexBuffer) {
  108724. return;
  108725. }
  108726. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108727. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108728. setData(babylonVertexBuffer, data);
  108729. }));
  108730. };
  108731. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  108732. babylonVertexBuffer.forEach(data.length, function (value, index) {
  108733. data[index] += value;
  108734. });
  108735. babylonMorphTarget.setPositions(data);
  108736. });
  108737. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  108738. babylonVertexBuffer.forEach(data.length, function (value, index) {
  108739. data[index] += value;
  108740. });
  108741. babylonMorphTarget.setNormals(data);
  108742. });
  108743. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  108744. var dataIndex = 0;
  108745. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  108746. // Tangent data for morph targets is stored as xyz delta.
  108747. // The vertexData.tangent is stored as xyzw.
  108748. // So we need to skip every fourth vertexData.tangent.
  108749. if (((index + 1) % 4) !== 0) {
  108750. data[dataIndex++] += value;
  108751. }
  108752. });
  108753. babylonMorphTarget.setTangents(data);
  108754. });
  108755. return Promise.all(promises).then(function () { });
  108756. };
  108757. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108758. var position = BABYLON.Vector3.Zero();
  108759. var rotation = BABYLON.Quaternion.Identity();
  108760. var scaling = BABYLON.Vector3.One();
  108761. if (node.matrix) {
  108762. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108763. matrix.decompose(scaling, rotation, position);
  108764. }
  108765. else {
  108766. if (node.translation)
  108767. position = BABYLON.Vector3.FromArray(node.translation);
  108768. if (node.rotation)
  108769. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108770. if (node.scale)
  108771. scaling = BABYLON.Vector3.FromArray(node.scale);
  108772. }
  108773. babylonNode.position = position;
  108774. babylonNode.rotationQuaternion = rotation;
  108775. babylonNode.scaling = scaling;
  108776. };
  108777. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108778. var _this = this;
  108779. var assignSkeleton = function (skeleton) {
  108780. _this._forEachPrimitive(node, function (babylonMesh) {
  108781. babylonMesh.skeleton = skeleton;
  108782. });
  108783. // Ignore the TRS of skinned nodes.
  108784. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  108785. node._babylonMesh.parent = _this._rootBabylonMesh;
  108786. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108787. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108788. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108789. };
  108790. if (skin._loaded) {
  108791. return skin._loaded.then(function () {
  108792. assignSkeleton(skin._babylonSkeleton);
  108793. });
  108794. }
  108795. var skeletonId = "skeleton" + skin._index;
  108796. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  108797. skin._babylonSkeleton = babylonSkeleton;
  108798. this._loadBones(context, skin);
  108799. assignSkeleton(babylonSkeleton);
  108800. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108801. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  108802. }));
  108803. };
  108804. GLTFLoader.prototype._loadBones = function (context, skin) {
  108805. var babylonBones = {};
  108806. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108807. var index = _a[_i];
  108808. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108809. this._loadBone(node, skin, babylonBones);
  108810. }
  108811. };
  108812. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  108813. var babylonBone = babylonBones[node._index];
  108814. if (babylonBone) {
  108815. return babylonBone;
  108816. }
  108817. var babylonParentBone = null;
  108818. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  108819. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  108820. }
  108821. var boneIndex = skin.joints.indexOf(node._index);
  108822. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  108823. babylonBones[node._index] = babylonBone;
  108824. node._babylonBones = node._babylonBones || [];
  108825. node._babylonBones.push(babylonBone);
  108826. return babylonBone;
  108827. };
  108828. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108829. if (skin.inverseBindMatrices == undefined) {
  108830. return Promise.resolve(null);
  108831. }
  108832. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108833. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  108834. };
  108835. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  108836. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  108837. var babylonBone = _a[_i];
  108838. var baseMatrix = BABYLON.Matrix.Identity();
  108839. var boneIndex = babylonBone._index;
  108840. if (inverseBindMatricesData && boneIndex !== -1) {
  108841. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  108842. baseMatrix.invertToRef(baseMatrix);
  108843. }
  108844. var babylonParentBone = babylonBone.getParent();
  108845. if (babylonParentBone) {
  108846. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108847. }
  108848. babylonBone.updateMatrix(baseMatrix, false, false);
  108849. babylonBone._updateDifferenceMatrix(undefined, false);
  108850. }
  108851. };
  108852. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108853. return node.matrix ?
  108854. BABYLON.Matrix.FromArray(node.matrix) :
  108855. 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());
  108856. };
  108857. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  108858. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  108859. babylonCamera.parent = babylonMesh;
  108860. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  108861. switch (camera.type) {
  108862. case "perspective" /* PERSPECTIVE */: {
  108863. var perspective = camera.perspective;
  108864. if (!perspective) {
  108865. throw new Error(context + ": Camera perspective properties are missing");
  108866. }
  108867. babylonCamera.fov = perspective.yfov;
  108868. babylonCamera.minZ = perspective.znear;
  108869. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  108870. break;
  108871. }
  108872. case "orthographic" /* ORTHOGRAPHIC */: {
  108873. if (!camera.orthographic) {
  108874. throw new Error(context + ": Camera orthographic properties are missing");
  108875. }
  108876. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  108877. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  108878. babylonCamera.orthoRight = camera.orthographic.xmag;
  108879. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  108880. babylonCamera.orthoTop = camera.orthographic.ymag;
  108881. babylonCamera.minZ = camera.orthographic.znear;
  108882. babylonCamera.maxZ = camera.orthographic.zfar;
  108883. break;
  108884. }
  108885. default: {
  108886. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  108887. }
  108888. }
  108889. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  108890. };
  108891. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108892. var animations = this._gltf.animations;
  108893. if (!animations) {
  108894. return Promise.resolve();
  108895. }
  108896. var promises = new Array();
  108897. for (var index = 0; index < animations.length; index++) {
  108898. var animation = animations[index];
  108899. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108900. }
  108901. return Promise.all(promises).then(function () { });
  108902. };
  108903. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108904. var _this = this;
  108905. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108906. animation._babylonAnimationGroup = babylonAnimationGroup;
  108907. var promises = new Array();
  108908. _ArrayItem.Assign(animation.channels);
  108909. _ArrayItem.Assign(animation.samplers);
  108910. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108911. var channel = _a[_i];
  108912. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108913. }
  108914. return Promise.all(promises).then(function () {
  108915. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  108916. });
  108917. };
  108918. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108919. var _this = this;
  108920. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108921. // Ignore animations that have no animation targets.
  108922. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  108923. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  108924. return Promise.resolve();
  108925. }
  108926. // Ignore animations targeting TRS of skinned nodes.
  108927. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  108928. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  108929. return Promise.resolve();
  108930. }
  108931. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108932. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108933. var targetPath;
  108934. var animationType;
  108935. switch (channel.target.path) {
  108936. case "translation" /* TRANSLATION */: {
  108937. targetPath = "position";
  108938. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108939. break;
  108940. }
  108941. case "rotation" /* ROTATION */: {
  108942. targetPath = "rotationQuaternion";
  108943. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108944. break;
  108945. }
  108946. case "scale" /* SCALE */: {
  108947. targetPath = "scaling";
  108948. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108949. break;
  108950. }
  108951. case "weights" /* WEIGHTS */: {
  108952. targetPath = "influence";
  108953. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108954. break;
  108955. }
  108956. default: {
  108957. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  108958. }
  108959. }
  108960. var outputBufferOffset = 0;
  108961. var getNextOutputValue;
  108962. switch (targetPath) {
  108963. case "position": {
  108964. getNextOutputValue = function () {
  108965. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108966. outputBufferOffset += 3;
  108967. return value;
  108968. };
  108969. break;
  108970. }
  108971. case "rotationQuaternion": {
  108972. getNextOutputValue = function () {
  108973. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108974. outputBufferOffset += 4;
  108975. return value;
  108976. };
  108977. break;
  108978. }
  108979. case "scaling": {
  108980. getNextOutputValue = function () {
  108981. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108982. outputBufferOffset += 3;
  108983. return value;
  108984. };
  108985. break;
  108986. }
  108987. case "influence": {
  108988. getNextOutputValue = function () {
  108989. var value = new Array(targetNode._numMorphTargets);
  108990. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108991. value[i] = data.output[outputBufferOffset++];
  108992. }
  108993. return value;
  108994. };
  108995. break;
  108996. }
  108997. }
  108998. var getNextKey;
  108999. switch (data.interpolation) {
  109000. case "STEP" /* STEP */: {
  109001. getNextKey = function (frameIndex) { return ({
  109002. frame: data.input[frameIndex],
  109003. value: getNextOutputValue(),
  109004. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109005. }); };
  109006. break;
  109007. }
  109008. case "LINEAR" /* LINEAR */: {
  109009. getNextKey = function (frameIndex) { return ({
  109010. frame: data.input[frameIndex],
  109011. value: getNextOutputValue()
  109012. }); };
  109013. break;
  109014. }
  109015. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109016. getNextKey = function (frameIndex) { return ({
  109017. frame: data.input[frameIndex],
  109018. inTangent: getNextOutputValue(),
  109019. value: getNextOutputValue(),
  109020. outTangent: getNextOutputValue()
  109021. }); };
  109022. break;
  109023. }
  109024. }
  109025. var keys = new Array(data.input.length);
  109026. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109027. keys[frameIndex] = getNextKey(frameIndex);
  109028. }
  109029. if (targetPath === "influence") {
  109030. var _loop_1 = function (targetIndex) {
  109031. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109032. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109033. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109034. frame: key.frame,
  109035. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109036. value: key.value[targetIndex],
  109037. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109038. }); }));
  109039. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  109040. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109041. var babylonAnimationClone = babylonAnimation.clone();
  109042. morphTarget.animations.push(babylonAnimationClone);
  109043. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  109044. });
  109045. };
  109046. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109047. _loop_1(targetIndex);
  109048. }
  109049. }
  109050. else {
  109051. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109052. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109053. babylonAnimation.setKeys(keys);
  109054. if (targetNode._babylonBones) {
  109055. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  109056. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  109057. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  109058. babylonAnimationTarget.animations.push(babylonAnimation);
  109059. }
  109060. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  109061. }
  109062. else {
  109063. targetNode._babylonMesh.animations.push(babylonAnimation);
  109064. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  109065. }
  109066. }
  109067. });
  109068. };
  109069. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109070. if (sampler._data) {
  109071. return sampler._data;
  109072. }
  109073. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109074. switch (interpolation) {
  109075. case "STEP" /* STEP */:
  109076. case "LINEAR" /* LINEAR */:
  109077. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109078. break;
  109079. }
  109080. default: {
  109081. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109082. }
  109083. }
  109084. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109085. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109086. sampler._data = Promise.all([
  109087. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  109088. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  109089. ]).then(function (_a) {
  109090. var inputData = _a[0], outputData = _a[1];
  109091. return {
  109092. input: inputData,
  109093. interpolation: interpolation,
  109094. output: outputData,
  109095. };
  109096. });
  109097. return sampler._data;
  109098. };
  109099. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109100. if (buffer._data) {
  109101. return buffer._data;
  109102. }
  109103. if (!buffer.uri) {
  109104. throw new Error(context + ": Uri is missing");
  109105. }
  109106. buffer._data = this._loadUriAsync(context, buffer.uri);
  109107. return buffer._data;
  109108. };
  109109. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109110. if (bufferView._data) {
  109111. return bufferView._data;
  109112. }
  109113. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109114. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  109115. try {
  109116. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109117. }
  109118. catch (e) {
  109119. throw new Error(context + ": " + e.message);
  109120. }
  109121. });
  109122. return bufferView._data;
  109123. };
  109124. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  109125. if (accessor.type !== "SCALAR" /* SCALAR */) {
  109126. throw new Error(context + ": Invalid type " + accessor.type);
  109127. }
  109128. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  109129. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  109130. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  109131. throw new Error(context + ": Invalid component type " + accessor.componentType);
  109132. }
  109133. if (accessor._data) {
  109134. return accessor._data;
  109135. }
  109136. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109137. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109138. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  109139. });
  109140. return accessor._data;
  109141. };
  109142. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  109143. // TODO: support normalized and stride
  109144. var _this = this;
  109145. if (accessor.componentType !== 5126 /* FLOAT */) {
  109146. throw new Error("Invalid component type " + accessor.componentType);
  109147. }
  109148. if (accessor._data) {
  109149. return accessor._data;
  109150. }
  109151. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109152. var length = numComponents * accessor.count;
  109153. if (accessor.bufferView == undefined) {
  109154. accessor._data = Promise.resolve(new Float32Array(length));
  109155. }
  109156. else {
  109157. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109158. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109159. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  109160. });
  109161. }
  109162. if (accessor.sparse) {
  109163. var sparse_1 = accessor.sparse;
  109164. accessor._data = accessor._data.then(function (data) {
  109165. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  109166. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  109167. return Promise.all([
  109168. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  109169. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  109170. ]).then(function (_a) {
  109171. var indicesData = _a[0], valuesData = _a[1];
  109172. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  109173. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  109174. var valuesIndex = 0;
  109175. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  109176. var dataIndex = indices[indicesIndex] * numComponents;
  109177. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109178. data[dataIndex++] = values[valuesIndex++];
  109179. }
  109180. }
  109181. return data;
  109182. });
  109183. });
  109184. }
  109185. return accessor._data;
  109186. };
  109187. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  109188. var _this = this;
  109189. if (bufferView._babylonBuffer) {
  109190. return bufferView._babylonBuffer;
  109191. }
  109192. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  109193. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  109194. });
  109195. return bufferView._babylonBuffer;
  109196. };
  109197. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  109198. var _this = this;
  109199. if (accessor._babylonVertexBuffer) {
  109200. return accessor._babylonVertexBuffer;
  109201. }
  109202. if (accessor.sparse) {
  109203. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  109204. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  109205. });
  109206. }
  109207. else {
  109208. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109209. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  109210. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  109211. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  109212. });
  109213. }
  109214. return accessor._babylonVertexBuffer;
  109215. };
  109216. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  109217. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  109218. if (!babylonMaterial) {
  109219. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  109220. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109221. babylonMaterial.metallic = 1;
  109222. babylonMaterial.roughness = 1;
  109223. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109224. }
  109225. return babylonMaterial;
  109226. };
  109227. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  109228. var promises = new Array();
  109229. // Ensure metallic workflow
  109230. babylonMaterial.metallic = 1;
  109231. babylonMaterial.roughness = 1;
  109232. var properties = material.pbrMetallicRoughness;
  109233. if (properties) {
  109234. if (properties.baseColorFactor) {
  109235. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109236. babylonMaterial.alpha = properties.baseColorFactor[3];
  109237. }
  109238. else {
  109239. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109240. }
  109241. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109242. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109243. if (properties.baseColorTexture) {
  109244. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109245. babylonMaterial.albedoTexture = texture;
  109246. }));
  109247. }
  109248. if (properties.metallicRoughnessTexture) {
  109249. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109250. babylonMaterial.metallicTexture = texture;
  109251. }));
  109252. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109253. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109254. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109255. }
  109256. }
  109257. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109258. return Promise.all(promises).then(function () { });
  109259. };
  109260. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109261. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  109262. if (promise) {
  109263. return promise;
  109264. }
  109265. material._babylonData = material._babylonData || {};
  109266. var babylonData = material._babylonData[babylonDrawMode];
  109267. if (!babylonData) {
  109268. this._parent._logOpen(context + " " + (material.name || ""));
  109269. var name_4 = material.name || "material" + material._index;
  109270. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  109271. babylonData = {
  109272. material: babylonMaterial,
  109273. meshes: [],
  109274. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  109275. };
  109276. material._babylonData[babylonDrawMode] = babylonData;
  109277. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109278. this._parent._logClose();
  109279. }
  109280. babylonData.meshes.push(babylonMesh);
  109281. babylonMesh.onDisposeObservable.addOnce(function () {
  109282. var index = babylonData.meshes.indexOf(babylonMesh);
  109283. if (index !== -1) {
  109284. babylonData.meshes.splice(index, 1);
  109285. }
  109286. });
  109287. assign(babylonData.material);
  109288. return babylonData.loaded;
  109289. };
  109290. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  109291. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  109292. if (promise) {
  109293. return promise;
  109294. }
  109295. var promises = new Array();
  109296. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  109297. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  109298. return Promise.all(promises).then(function () { });
  109299. };
  109300. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  109301. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  109302. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109303. babylonMaterial.fillMode = drawMode;
  109304. babylonMaterial.enableSpecularAntiAliasing = true;
  109305. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  109306. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  109307. return babylonMaterial;
  109308. };
  109309. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  109310. var promises = new Array();
  109311. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109312. if (material.doubleSided) {
  109313. babylonMaterial.backFaceCulling = false;
  109314. babylonMaterial.twoSidedLighting = true;
  109315. }
  109316. if (material.normalTexture) {
  109317. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109318. babylonMaterial.bumpTexture = texture;
  109319. }));
  109320. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109321. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109322. if (material.normalTexture.scale != undefined) {
  109323. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109324. }
  109325. }
  109326. if (material.occlusionTexture) {
  109327. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109328. babylonMaterial.ambientTexture = texture;
  109329. }));
  109330. babylonMaterial.useAmbientInGrayScale = true;
  109331. if (material.occlusionTexture.strength != undefined) {
  109332. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109333. }
  109334. }
  109335. if (material.emissiveTexture) {
  109336. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109337. babylonMaterial.emissiveTexture = texture;
  109338. }));
  109339. }
  109340. return Promise.all(promises).then(function () { });
  109341. };
  109342. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  109343. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109344. switch (alphaMode) {
  109345. case "OPAQUE" /* OPAQUE */: {
  109346. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109347. break;
  109348. }
  109349. case "MASK" /* MASK */: {
  109350. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109351. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109352. if (babylonMaterial.albedoTexture) {
  109353. babylonMaterial.albedoTexture.hasAlpha = true;
  109354. }
  109355. break;
  109356. }
  109357. case "BLEND" /* BLEND */: {
  109358. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109359. if (babylonMaterial.albedoTexture) {
  109360. babylonMaterial.albedoTexture.hasAlpha = true;
  109361. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109362. }
  109363. break;
  109364. }
  109365. default: {
  109366. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109367. }
  109368. }
  109369. };
  109370. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109371. var _this = this;
  109372. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  109373. if (promise) {
  109374. return promise;
  109375. }
  109376. this._parent._logOpen("" + context);
  109377. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109378. context = "#/textures/" + textureInfo.index;
  109379. var promises = new Array();
  109380. this._parent._logOpen(context + " " + (texture.name || ""));
  109381. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109382. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109383. var deferred = new BABYLON.Deferred();
  109384. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109385. if (!_this._disposed) {
  109386. deferred.resolve();
  109387. }
  109388. }, function (message, exception) {
  109389. if (!_this._disposed) {
  109390. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109391. }
  109392. });
  109393. promises.push(deferred.promise);
  109394. babylonTexture.name = texture.name || "texture" + texture._index;
  109395. babylonTexture.wrapU = samplerData.wrapU;
  109396. babylonTexture.wrapV = samplerData.wrapV;
  109397. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109398. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109399. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  109400. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  109401. babylonTexture.updateURL(dataUrl, blob);
  109402. }));
  109403. assign(babylonTexture);
  109404. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109405. this._parent._logClose();
  109406. this._parent._logClose();
  109407. return Promise.all(promises).then(function () { });
  109408. };
  109409. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109410. if (!sampler._data) {
  109411. sampler._data = {
  109412. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109413. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109414. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109415. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109416. };
  109417. }
  109418. ;
  109419. return sampler._data;
  109420. };
  109421. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109422. if (!image._blob) {
  109423. this._parent._logOpen(context + " " + (image.name || ""));
  109424. var promise = void 0;
  109425. if (image.uri) {
  109426. promise = this._loadUriAsync(context, image.uri);
  109427. }
  109428. else {
  109429. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109430. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109431. }
  109432. image._blob = promise.then(function (data) {
  109433. return new Blob([data], { type: image.mimeType });
  109434. });
  109435. this._parent._logClose();
  109436. }
  109437. return image._blob;
  109438. };
  109439. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109440. var _this = this;
  109441. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109442. if (promise) {
  109443. return promise;
  109444. }
  109445. if (!GLTFLoader._ValidateUri(uri)) {
  109446. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109447. }
  109448. if (BABYLON.Tools.IsBase64(uri)) {
  109449. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  109450. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  109451. return Promise.resolve(data);
  109452. }
  109453. this._parent._log("Loading " + uri);
  109454. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  109455. return new Promise(function (resolve, reject) {
  109456. if (!_this._disposed) {
  109457. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  109458. if (!_this._disposed) {
  109459. var data = new Uint8Array(fileData);
  109460. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  109461. resolve(data);
  109462. }
  109463. }, function (event) {
  109464. if (!_this._disposed) {
  109465. if (request_1) {
  109466. request_1._lengthComputable = event.lengthComputable;
  109467. request_1._loaded = event.loaded;
  109468. request_1._total = event.total;
  109469. }
  109470. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  109471. try {
  109472. _this._onProgress();
  109473. }
  109474. catch (e) {
  109475. reject(e);
  109476. }
  109477. }
  109478. }
  109479. }, _this._babylonScene.database, true, function (request, exception) {
  109480. if (!_this._disposed) {
  109481. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109482. }
  109483. });
  109484. _this._requests.push(request_1);
  109485. }
  109486. });
  109487. });
  109488. };
  109489. GLTFLoader.prototype._onProgress = function () {
  109490. if (!this._progressCallback) {
  109491. return;
  109492. }
  109493. var lengthComputable = true;
  109494. var loaded = 0;
  109495. var total = 0;
  109496. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109497. var request = _a[_i];
  109498. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109499. return;
  109500. }
  109501. lengthComputable = lengthComputable && request._lengthComputable;
  109502. loaded += request._loaded;
  109503. total += request._total;
  109504. }
  109505. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109506. };
  109507. GLTFLoader._GetProperty = function (context, array, index) {
  109508. if (!array || index == undefined || !array[index]) {
  109509. throw new Error(context + ": Failed to find index (" + index + ")");
  109510. }
  109511. return array[index];
  109512. };
  109513. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109514. // Set defaults if undefined
  109515. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109516. switch (mode) {
  109517. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109518. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109519. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109520. default:
  109521. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109522. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109523. }
  109524. };
  109525. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109526. // Set defaults if undefined
  109527. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109528. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109529. if (magFilter === 9729 /* LINEAR */) {
  109530. switch (minFilter) {
  109531. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109532. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109533. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109534. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109535. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109536. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109537. default:
  109538. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109539. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109540. }
  109541. }
  109542. else {
  109543. if (magFilter !== 9728 /* NEAREST */) {
  109544. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109545. }
  109546. switch (minFilter) {
  109547. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109548. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109549. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109550. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109551. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109552. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109553. default:
  109554. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109555. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109556. }
  109557. }
  109558. };
  109559. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  109560. var buffer = bufferView.buffer;
  109561. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  109562. try {
  109563. switch (componentType) {
  109564. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  109565. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  109566. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  109567. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  109568. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  109569. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  109570. default: throw new Error("Invalid component type " + componentType);
  109571. }
  109572. }
  109573. catch (e) {
  109574. throw new Error(context + ": " + e);
  109575. }
  109576. };
  109577. GLTFLoader._GetNumComponents = function (context, type) {
  109578. switch (type) {
  109579. case "SCALAR": return 1;
  109580. case "VEC2": return 2;
  109581. case "VEC3": return 3;
  109582. case "VEC4": return 4;
  109583. case "MAT2": return 4;
  109584. case "MAT3": return 9;
  109585. case "MAT4": return 16;
  109586. }
  109587. throw new Error(context + ": Invalid type (" + type + ")");
  109588. };
  109589. GLTFLoader._ValidateUri = function (uri) {
  109590. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109591. };
  109592. GLTFLoader._GetDrawMode = function (context, mode) {
  109593. if (mode == undefined) {
  109594. mode = 4 /* TRIANGLES */;
  109595. }
  109596. switch (mode) {
  109597. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  109598. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  109599. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  109600. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  109601. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  109602. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  109603. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  109604. }
  109605. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  109606. };
  109607. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109608. var _this = this;
  109609. this._parent._startPerformanceCounter("Compile materials");
  109610. var promises = new Array();
  109611. if (this._gltf.materials) {
  109612. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109613. var material = _a[_i];
  109614. if (material._babylonData) {
  109615. for (var babylonDrawMode in material._babylonData) {
  109616. var babylonData = material._babylonData[babylonDrawMode];
  109617. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  109618. var babylonMesh = _c[_b];
  109619. // Ensure nonUniformScaling is set if necessary.
  109620. babylonMesh.computeWorldMatrix(true);
  109621. var babylonMaterial = babylonData.material;
  109622. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109623. if (this._parent.useClipPlane) {
  109624. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109625. }
  109626. }
  109627. }
  109628. }
  109629. }
  109630. }
  109631. return Promise.all(promises).then(function () {
  109632. _this._parent._endPerformanceCounter("Compile materials");
  109633. });
  109634. };
  109635. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109636. var _this = this;
  109637. this._parent._startPerformanceCounter("Compile shadow generators");
  109638. var promises = new Array();
  109639. var lights = this._babylonScene.lights;
  109640. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109641. var light = lights_1[_i];
  109642. var generator = light.getShadowGenerator();
  109643. if (generator) {
  109644. promises.push(generator.forceCompilationAsync());
  109645. }
  109646. }
  109647. return Promise.all(promises).then(function () {
  109648. _this._parent._endPerformanceCounter("Compile shadow generators");
  109649. });
  109650. };
  109651. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109652. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  109653. var name_5 = _a[_i];
  109654. var extension = this._extensions[name_5];
  109655. if (extension.enabled) {
  109656. var promise = actionAsync(extension);
  109657. if (promise) {
  109658. return promise;
  109659. }
  109660. }
  109661. }
  109662. return null;
  109663. };
  109664. GLTFLoader._ExtensionNames = new Array();
  109665. GLTFLoader._ExtensionFactories = {};
  109666. return GLTFLoader;
  109667. }());
  109668. GLTF2.GLTFLoader = GLTFLoader;
  109669. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  109670. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109671. })(BABYLON || (BABYLON = {}));
  109672. //# sourceMappingURL=babylon.glTFLoader.js.map
  109673. var BABYLON;
  109674. (function (BABYLON) {
  109675. var GLTF2;
  109676. (function (GLTF2) {
  109677. /**
  109678. * Abstract class that can be implemented to extend existing glTF loader behavior.
  109679. */
  109680. var GLTFLoaderExtension = /** @class */ (function () {
  109681. /**
  109682. * Creates new GLTFLoaderExtension
  109683. * @param loader defines the GLTFLoader to use
  109684. */
  109685. function GLTFLoaderExtension(loader) {
  109686. /**
  109687. * Gets or sets a boolean indicating if the extension is enabled
  109688. */
  109689. this.enabled = true;
  109690. this._loader = loader;
  109691. }
  109692. /**
  109693. * Release all resources
  109694. */
  109695. GLTFLoaderExtension.prototype.dispose = function () {
  109696. delete this._loader;
  109697. };
  109698. // #region Overridable Methods
  109699. /**
  109700. * Override this method to modify the default behavior for loading scenes.
  109701. * @hidden
  109702. */
  109703. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109704. /**
  109705. * Override this method to modify the default behavior for loading nodes.
  109706. * @hidden
  109707. */
  109708. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109709. /**
  109710. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  109711. * @hidden
  109712. */
  109713. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109714. /**
  109715. * Override this method to modify the default behavior for loading materials.
  109716. * @hidden
  109717. */
  109718. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  109719. /**
  109720. * Override this method to modify the default behavior for loading material properties.
  109721. * @hidden
  109722. */
  109723. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  109724. /**
  109725. * Override this method to modify the default behavior for loading textures.
  109726. * @hidden
  109727. */
  109728. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  109729. /**
  109730. * Override this method to modify the default behavior for loading uris.
  109731. * @hidden
  109732. */
  109733. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109734. // #endregion
  109735. /**
  109736. * Helper method called by a loader extension to load an glTF extension.
  109737. * @hidden
  109738. */
  109739. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109740. if (!property.extensions) {
  109741. return null;
  109742. }
  109743. var extensions = property.extensions;
  109744. var extension = extensions[this.name];
  109745. if (!extension) {
  109746. return null;
  109747. }
  109748. // Clear out the extension before executing the action to avoid infinite recursion.
  109749. delete extensions[this.name];
  109750. try {
  109751. return actionAsync(context + "/extensions/" + this.name, extension);
  109752. }
  109753. finally {
  109754. // Restore the extension after executing the action.
  109755. extensions[this.name] = extension;
  109756. }
  109757. };
  109758. /**
  109759. * Helper method called by the loader to allow extensions to override loading scenes.
  109760. * @hidden
  109761. */
  109762. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  109763. if (!property.extras) {
  109764. return null;
  109765. }
  109766. var extras = property.extras;
  109767. var value = extras[this.name];
  109768. if (value === undefined) {
  109769. return null;
  109770. }
  109771. // Clear out the extras value before executing the action to avoid infinite recursion.
  109772. delete extras[this.name];
  109773. try {
  109774. return actionAsync(context + "/extras/" + this.name, value);
  109775. }
  109776. finally {
  109777. // Restore the extras value after executing the action.
  109778. extras[this.name] = value;
  109779. }
  109780. };
  109781. /**
  109782. * Helper method called by the loader to allow extensions to override loading scenes.
  109783. * @hidden
  109784. */
  109785. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109786. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109787. };
  109788. /**
  109789. * Helper method called by the loader to allow extensions to override loading nodes.
  109790. * @hidden
  109791. */
  109792. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109793. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109794. };
  109795. /**
  109796. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  109797. * @hidden
  109798. */
  109799. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109800. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109801. };
  109802. /**
  109803. * Helper method called by the loader to allow extensions to override loading materials.
  109804. * @hidden
  109805. */
  109806. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109807. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  109808. };
  109809. /**
  109810. * Helper method called by the loader to allow extensions to override loading material properties.
  109811. * @hidden
  109812. */
  109813. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  109814. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  109815. };
  109816. /**
  109817. * Helper method called by the loader to allow extensions to override loading textures.
  109818. * @hidden
  109819. */
  109820. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  109821. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  109822. };
  109823. /**
  109824. * Helper method called by the loader to allow extensions to override loading uris.
  109825. * @hidden
  109826. */
  109827. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109828. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109829. };
  109830. return GLTFLoaderExtension;
  109831. }());
  109832. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109833. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109834. })(BABYLON || (BABYLON = {}));
  109835. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109836. var BABYLON;
  109837. (function (BABYLON) {
  109838. var GLTF2;
  109839. (function (GLTF2) {
  109840. var Extensions;
  109841. (function (Extensions) {
  109842. var NAME = "MSFT_lod";
  109843. /**
  109844. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  109845. */
  109846. var MSFT_lod = /** @class */ (function (_super) {
  109847. __extends(MSFT_lod, _super);
  109848. function MSFT_lod(loader) {
  109849. var _this = _super.call(this, loader) || this;
  109850. _this.name = NAME;
  109851. /**
  109852. * Maximum number of LODs to load, starting from the lowest LOD.
  109853. */
  109854. _this.maxLODsToLoad = Number.MAX_VALUE;
  109855. /**
  109856. * Observable raised when all node LODs of one level are loaded.
  109857. * The event data is the index of the loaded LOD starting from zero.
  109858. * Dispose the loader to cancel the loading of the next level of LODs.
  109859. */
  109860. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  109861. /**
  109862. * Observable raised when all material LODs of one level are loaded.
  109863. * The event data is the index of the loaded LOD starting from zero.
  109864. * Dispose the loader to cancel the loading of the next level of LODs.
  109865. */
  109866. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  109867. _this._nodeIndexLOD = null;
  109868. _this._nodeSignalLODs = new Array();
  109869. _this._nodePromiseLODs = new Array();
  109870. _this._materialIndexLOD = null;
  109871. _this._materialSignalLODs = new Array();
  109872. _this._materialPromiseLODs = new Array();
  109873. _this._loader._readyPromise.then(function () {
  109874. var _loop_1 = function (indexLOD) {
  109875. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  109876. if (indexLOD !== 0) {
  109877. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  109878. }
  109879. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  109880. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  109881. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  109882. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  109883. _this._nodeSignalLODs[indexLOD].resolve();
  109884. }
  109885. });
  109886. _this._loader._completePromises.push(promise);
  109887. };
  109888. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  109889. _loop_1(indexLOD);
  109890. }
  109891. var _loop_2 = function (indexLOD) {
  109892. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  109893. if (indexLOD !== 0) {
  109894. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  109895. }
  109896. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  109897. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  109898. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  109899. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  109900. _this._materialSignalLODs[indexLOD].resolve();
  109901. }
  109902. });
  109903. _this._loader._completePromises.push(promise);
  109904. };
  109905. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  109906. _loop_2(indexLOD);
  109907. }
  109908. });
  109909. return _this;
  109910. }
  109911. MSFT_lod.prototype.dispose = function () {
  109912. _super.prototype.dispose.call(this);
  109913. this._nodeIndexLOD = null;
  109914. this._nodeSignalLODs.length = 0;
  109915. this._nodePromiseLODs.length = 0;
  109916. this._materialIndexLOD = null;
  109917. this._materialSignalLODs.length = 0;
  109918. this._materialPromiseLODs.length = 0;
  109919. this.onMaterialLODsLoadedObservable.clear();
  109920. this.onNodeLODsLoadedObservable.clear();
  109921. };
  109922. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109923. var _this = this;
  109924. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  109925. var firstPromise;
  109926. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  109927. _this._loader._parent._logOpen("" + extensionContext);
  109928. var _loop_3 = function (indexLOD) {
  109929. var nodeLOD = nodeLODs[indexLOD];
  109930. if (indexLOD !== 0) {
  109931. _this._nodeIndexLOD = indexLOD;
  109932. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  109933. }
  109934. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109935. if (indexLOD !== 0) {
  109936. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109937. if (previousNodeLOD._babylonMesh) {
  109938. previousNodeLOD._babylonMesh.dispose();
  109939. delete previousNodeLOD._babylonMesh;
  109940. _this._disposeUnusedMaterials();
  109941. }
  109942. }
  109943. });
  109944. if (indexLOD === 0) {
  109945. firstPromise = promise;
  109946. }
  109947. else {
  109948. _this._nodeIndexLOD = null;
  109949. }
  109950. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  109951. _this._nodePromiseLODs[indexLOD].push(promise);
  109952. };
  109953. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109954. _loop_3(indexLOD);
  109955. }
  109956. _this._loader._parent._logClose();
  109957. return firstPromise;
  109958. });
  109959. };
  109960. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109961. var _this = this;
  109962. // Don't load material LODs if already loading a node LOD.
  109963. if (this._nodeIndexLOD) {
  109964. return null;
  109965. }
  109966. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109967. var firstPromise;
  109968. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  109969. _this._loader._parent._logOpen("" + extensionContext);
  109970. var _loop_4 = function (indexLOD) {
  109971. var materialLOD = materialLODs[indexLOD];
  109972. if (indexLOD !== 0) {
  109973. _this._materialIndexLOD = indexLOD;
  109974. }
  109975. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  109976. if (indexLOD !== 0) {
  109977. var babylonDataLOD = materialLOD._babylonData;
  109978. assign(babylonDataLOD[babylonDrawMode].material);
  109979. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  109980. if (previousBabylonDataLOD[babylonDrawMode]) {
  109981. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  109982. delete previousBabylonDataLOD[babylonDrawMode];
  109983. }
  109984. }
  109985. });
  109986. if (indexLOD === 0) {
  109987. firstPromise = promise;
  109988. }
  109989. else {
  109990. _this._materialIndexLOD = null;
  109991. }
  109992. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  109993. _this._materialPromiseLODs[indexLOD].push(promise);
  109994. };
  109995. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109996. _loop_4(indexLOD);
  109997. }
  109998. _this._loader._parent._logClose();
  109999. return firstPromise;
  110000. });
  110001. };
  110002. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110003. var _this = this;
  110004. // Defer the loading of uris if loading a material or node LOD.
  110005. if (this._materialIndexLOD !== null) {
  110006. this._loader._parent._log("deferred");
  110007. var previousIndexLOD = this._materialIndexLOD - 1;
  110008. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110009. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  110010. return _this._loader._loadUriAsync(context, uri);
  110011. });
  110012. }
  110013. else if (this._nodeIndexLOD !== null) {
  110014. this._loader._parent._log("deferred");
  110015. var previousIndexLOD = this._nodeIndexLOD - 1;
  110016. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  110017. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  110018. return _this._loader._loadUriAsync(context, uri);
  110019. });
  110020. }
  110021. return null;
  110022. };
  110023. /**
  110024. * Gets an array of LOD properties from lowest to highest.
  110025. */
  110026. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110027. if (this.maxLODsToLoad <= 0) {
  110028. throw new Error("maxLODsToLoad must be greater than zero");
  110029. }
  110030. var properties = new Array();
  110031. for (var i = ids.length - 1; i >= 0; i--) {
  110032. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110033. if (properties.length === this.maxLODsToLoad) {
  110034. return properties;
  110035. }
  110036. }
  110037. properties.push(property);
  110038. return properties;
  110039. };
  110040. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  110041. var materials = this._loader._gltf.materials;
  110042. if (materials) {
  110043. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  110044. var material = materials_1[_i];
  110045. if (material._babylonData) {
  110046. for (var drawMode in material._babylonData) {
  110047. var babylonData = material._babylonData[drawMode];
  110048. if (babylonData.meshes.length === 0) {
  110049. babylonData.material.dispose(false, true);
  110050. delete material._babylonData[drawMode];
  110051. }
  110052. }
  110053. }
  110054. }
  110055. }
  110056. };
  110057. return MSFT_lod;
  110058. }(GLTF2.GLTFLoaderExtension));
  110059. Extensions.MSFT_lod = MSFT_lod;
  110060. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110061. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110062. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110063. })(BABYLON || (BABYLON = {}));
  110064. //# sourceMappingURL=MSFT_lod.js.map
  110065. var BABYLON;
  110066. (function (BABYLON) {
  110067. var GLTF2;
  110068. (function (GLTF2) {
  110069. var Extensions;
  110070. (function (Extensions) {
  110071. var NAME = "MSFT_minecraftMesh";
  110072. /** @hidden */
  110073. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  110074. __extends(MSFT_minecraftMesh, _super);
  110075. function MSFT_minecraftMesh() {
  110076. var _this = _super !== null && _super.apply(this, arguments) || this;
  110077. _this.name = NAME;
  110078. return _this;
  110079. }
  110080. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110081. var _this = this;
  110082. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  110083. if (value) {
  110084. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110085. if (babylonMaterial.needAlphaBlending()) {
  110086. babylonMaterial.forceDepthWrite = true;
  110087. babylonMaterial.separateCullingPass = true;
  110088. }
  110089. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  110090. babylonMaterial.twoSidedLighting = true;
  110091. assign(babylonMaterial);
  110092. });
  110093. }
  110094. return null;
  110095. });
  110096. };
  110097. return MSFT_minecraftMesh;
  110098. }(GLTF2.GLTFLoaderExtension));
  110099. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  110100. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  110101. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110102. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110103. })(BABYLON || (BABYLON = {}));
  110104. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  110105. var BABYLON;
  110106. (function (BABYLON) {
  110107. var GLTF2;
  110108. (function (GLTF2) {
  110109. var Extensions;
  110110. (function (Extensions) {
  110111. var NAME = "MSFT_sRGBFactors";
  110112. /** @hidden */
  110113. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  110114. __extends(MSFT_sRGBFactors, _super);
  110115. function MSFT_sRGBFactors() {
  110116. var _this = _super !== null && _super.apply(this, arguments) || this;
  110117. _this.name = NAME;
  110118. return _this;
  110119. }
  110120. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110121. var _this = this;
  110122. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  110123. if (value) {
  110124. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110125. if (!babylonMaterial.albedoTexture) {
  110126. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  110127. }
  110128. if (!babylonMaterial.reflectivityTexture) {
  110129. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  110130. }
  110131. assign(babylonMaterial);
  110132. });
  110133. }
  110134. return null;
  110135. });
  110136. };
  110137. return MSFT_sRGBFactors;
  110138. }(GLTF2.GLTFLoaderExtension));
  110139. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  110140. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  110141. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110142. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110143. })(BABYLON || (BABYLON = {}));
  110144. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  110145. var BABYLON;
  110146. (function (BABYLON) {
  110147. var GLTF2;
  110148. (function (GLTF2) {
  110149. var Extensions;
  110150. (function (Extensions) {
  110151. var NAME = "KHR_draco_mesh_compression";
  110152. /**
  110153. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  110154. */
  110155. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110156. __extends(KHR_draco_mesh_compression, _super);
  110157. function KHR_draco_mesh_compression(loader) {
  110158. var _this = _super.call(this, loader) || this;
  110159. _this.name = NAME;
  110160. _this._dracoCompression = null;
  110161. // Disable extension if decoder is not available.
  110162. if (!BABYLON.DracoCompression.DecoderAvailable) {
  110163. _this.enabled = false;
  110164. }
  110165. return _this;
  110166. }
  110167. KHR_draco_mesh_compression.prototype.dispose = function () {
  110168. if (this._dracoCompression) {
  110169. this._dracoCompression.dispose();
  110170. }
  110171. _super.prototype.dispose.call(this);
  110172. };
  110173. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110174. var _this = this;
  110175. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110176. if (primitive.mode != undefined) {
  110177. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110178. primitive.mode !== 4 /* TRIANGLES */) {
  110179. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110180. }
  110181. // TODO: handle triangle strips
  110182. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110183. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110184. }
  110185. }
  110186. var attributes = {};
  110187. var loadAttribute = function (name, kind) {
  110188. var uniqueId = extension.attributes[name];
  110189. if (uniqueId == undefined) {
  110190. return;
  110191. }
  110192. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110193. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110194. babylonMesh._delayInfo.push(kind);
  110195. }
  110196. attributes[kind] = uniqueId;
  110197. };
  110198. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110199. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110200. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110201. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110202. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110203. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110204. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110205. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110206. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110207. if (!bufferView._dracoBabylonGeometry) {
  110208. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110209. if (!_this._dracoCompression) {
  110210. _this._dracoCompression = new BABYLON.DracoCompression();
  110211. }
  110212. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  110213. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  110214. babylonVertexData.applyToGeometry(babylonGeometry);
  110215. return babylonGeometry;
  110216. }).catch(function (error) {
  110217. throw new Error(context + ": " + error.message);
  110218. });
  110219. });
  110220. }
  110221. return bufferView._dracoBabylonGeometry;
  110222. });
  110223. };
  110224. return KHR_draco_mesh_compression;
  110225. }(GLTF2.GLTFLoaderExtension));
  110226. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110227. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110228. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110229. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110230. })(BABYLON || (BABYLON = {}));
  110231. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110232. var BABYLON;
  110233. (function (BABYLON) {
  110234. var GLTF2;
  110235. (function (GLTF2) {
  110236. var Extensions;
  110237. (function (Extensions) {
  110238. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110239. /**
  110240. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  110241. */
  110242. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110243. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110244. function KHR_materials_pbrSpecularGlossiness() {
  110245. var _this = _super !== null && _super.apply(this, arguments) || this;
  110246. _this.name = NAME;
  110247. return _this;
  110248. }
  110249. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110250. var _this = this;
  110251. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  110252. var promises = new Array();
  110253. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110254. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  110255. return Promise.all(promises).then(function () { });
  110256. });
  110257. };
  110258. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  110259. var promises = new Array();
  110260. if (properties.diffuseFactor) {
  110261. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110262. babylonMaterial.alpha = properties.diffuseFactor[3];
  110263. }
  110264. else {
  110265. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110266. }
  110267. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110268. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110269. if (properties.diffuseTexture) {
  110270. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110271. babylonMaterial.albedoTexture = texture;
  110272. }));
  110273. }
  110274. if (properties.specularGlossinessTexture) {
  110275. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110276. babylonMaterial.reflectivityTexture = texture;
  110277. }));
  110278. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110279. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110280. }
  110281. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110282. return Promise.all(promises).then(function () { });
  110283. };
  110284. return KHR_materials_pbrSpecularGlossiness;
  110285. }(GLTF2.GLTFLoaderExtension));
  110286. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110287. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110288. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110289. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110290. })(BABYLON || (BABYLON = {}));
  110291. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110292. var BABYLON;
  110293. (function (BABYLON) {
  110294. var GLTF2;
  110295. (function (GLTF2) {
  110296. var Extensions;
  110297. (function (Extensions) {
  110298. var NAME = "KHR_materials_unlit";
  110299. /**
  110300. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  110301. */
  110302. var KHR_materials_unlit = /** @class */ (function (_super) {
  110303. __extends(KHR_materials_unlit, _super);
  110304. function KHR_materials_unlit() {
  110305. var _this = _super !== null && _super.apply(this, arguments) || this;
  110306. _this.name = NAME;
  110307. return _this;
  110308. }
  110309. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110310. var _this = this;
  110311. return this._loadExtensionAsync(context, material, function () {
  110312. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  110313. });
  110314. };
  110315. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  110316. var promises = new Array();
  110317. babylonMaterial.unlit = true;
  110318. // Ensure metallic workflow
  110319. babylonMaterial.metallic = 1;
  110320. babylonMaterial.roughness = 1;
  110321. var properties = material.pbrMetallicRoughness;
  110322. if (properties) {
  110323. if (properties.baseColorFactor) {
  110324. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110325. babylonMaterial.alpha = properties.baseColorFactor[3];
  110326. }
  110327. else {
  110328. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110329. }
  110330. if (properties.baseColorTexture) {
  110331. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110332. babylonMaterial.albedoTexture = texture;
  110333. }));
  110334. }
  110335. }
  110336. if (material.doubleSided) {
  110337. babylonMaterial.backFaceCulling = false;
  110338. babylonMaterial.twoSidedLighting = true;
  110339. }
  110340. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110341. return Promise.all(promises).then(function () { });
  110342. };
  110343. return KHR_materials_unlit;
  110344. }(GLTF2.GLTFLoaderExtension));
  110345. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  110346. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  110347. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110348. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110349. })(BABYLON || (BABYLON = {}));
  110350. //# sourceMappingURL=KHR_materials_unlit.js.map
  110351. var BABYLON;
  110352. (function (BABYLON) {
  110353. var GLTF2;
  110354. (function (GLTF2) {
  110355. var Extensions;
  110356. (function (Extensions) {
  110357. var NAME = "KHR_lights";
  110358. var LightType;
  110359. (function (LightType) {
  110360. LightType["AMBIENT"] = "ambient";
  110361. LightType["DIRECTIONAL"] = "directional";
  110362. LightType["POINT"] = "point";
  110363. LightType["SPOT"] = "spot";
  110364. })(LightType || (LightType = {}));
  110365. /**
  110366. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  110367. */
  110368. var KHR_lights = /** @class */ (function (_super) {
  110369. __extends(KHR_lights, _super);
  110370. function KHR_lights() {
  110371. var _this = _super !== null && _super.apply(this, arguments) || this;
  110372. _this.name = NAME;
  110373. return _this;
  110374. }
  110375. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110376. var _this = this;
  110377. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  110378. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  110379. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  110380. if (light.type !== LightType.AMBIENT) {
  110381. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  110382. }
  110383. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110384. return promise;
  110385. });
  110386. };
  110387. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110388. var _this = this;
  110389. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  110390. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  110391. var babylonLight;
  110392. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  110393. var name = node._babylonMesh.name;
  110394. switch (light.type) {
  110395. case LightType.AMBIENT: {
  110396. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  110397. }
  110398. case LightType.DIRECTIONAL: {
  110399. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110400. break;
  110401. }
  110402. case LightType.POINT: {
  110403. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110404. break;
  110405. }
  110406. case LightType.SPOT: {
  110407. var spotLight = light;
  110408. // TODO: support inner and outer cone angles
  110409. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110410. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110411. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110412. break;
  110413. }
  110414. default: {
  110415. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  110416. }
  110417. }
  110418. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110419. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110420. babylonLight.parent = node._babylonMesh;
  110421. return promise;
  110422. });
  110423. };
  110424. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110425. get: function () {
  110426. var extensions = this._loader._gltf.extensions;
  110427. if (!extensions || !extensions[this.name]) {
  110428. throw new Error("#/extensions: '" + this.name + "' not found");
  110429. }
  110430. var extension = extensions[this.name];
  110431. return extension.lights;
  110432. },
  110433. enumerable: true,
  110434. configurable: true
  110435. });
  110436. return KHR_lights;
  110437. }(GLTF2.GLTFLoaderExtension));
  110438. Extensions.KHR_lights = KHR_lights;
  110439. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110440. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110441. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110442. })(BABYLON || (BABYLON = {}));
  110443. var BABYLON;
  110444. (function (BABYLON) {
  110445. var GLTF2;
  110446. (function (GLTF2) {
  110447. var Extensions;
  110448. (function (Extensions) {
  110449. var NAME = "KHR_texture_transform";
  110450. /**
  110451. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  110452. */
  110453. var KHR_texture_transform = /** @class */ (function (_super) {
  110454. __extends(KHR_texture_transform, _super);
  110455. function KHR_texture_transform() {
  110456. var _this = _super !== null && _super.apply(this, arguments) || this;
  110457. _this.name = NAME;
  110458. return _this;
  110459. }
  110460. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110461. var _this = this;
  110462. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  110463. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  110464. if (extension.offset) {
  110465. babylonTexture.uOffset = extension.offset[0];
  110466. babylonTexture.vOffset = extension.offset[1];
  110467. }
  110468. // Always rotate around the origin.
  110469. babylonTexture.uRotationCenter = 0;
  110470. babylonTexture.vRotationCenter = 0;
  110471. if (extension.rotation) {
  110472. babylonTexture.wAng = -extension.rotation;
  110473. }
  110474. if (extension.scale) {
  110475. babylonTexture.uScale = extension.scale[0];
  110476. babylonTexture.vScale = extension.scale[1];
  110477. }
  110478. if (extension.texCoord != undefined) {
  110479. babylonTexture.coordinatesIndex = extension.texCoord;
  110480. }
  110481. assign(babylonTexture);
  110482. });
  110483. });
  110484. };
  110485. return KHR_texture_transform;
  110486. }(GLTF2.GLTFLoaderExtension));
  110487. Extensions.KHR_texture_transform = KHR_texture_transform;
  110488. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  110489. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110490. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110491. })(BABYLON || (BABYLON = {}));
  110492. return BABYLON;
  110493. });
  110494. /***/ }),
  110495. /* 15 */
  110496. /***/ (function(module, exports, __webpack_require__) {
  110497. module.exports = __webpack_require__(16);
  110498. /***/ }),
  110499. /* 16 */
  110500. /***/ (function(module, exports, __webpack_require__) {
  110501. "use strict";
  110502. function __export(m) {
  110503. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  110504. }
  110505. Object.defineProperty(exports, "__esModule", { value: true });
  110506. var mappers_1 = __webpack_require__(3);
  110507. exports.mapperManager = mappers_1.mapperManager;
  110508. var globals_1 = __webpack_require__(4);
  110509. exports.viewerGlobals = globals_1.viewerGlobals;
  110510. var viewerManager_1 = __webpack_require__(7);
  110511. exports.viewerManager = viewerManager_1.viewerManager;
  110512. var defaultViewer_1 = __webpack_require__(8);
  110513. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  110514. var viewer_1 = __webpack_require__(9);
  110515. exports.AbstractViewer = viewer_1.AbstractViewer;
  110516. var telemetryManager_1 = __webpack_require__(6);
  110517. exports.telemetryManager = telemetryManager_1.telemetryManager;
  110518. var modelLoader_1 = __webpack_require__(13);
  110519. exports.ModelLoader = modelLoader_1.ModelLoader;
  110520. var viewerModel_1 = __webpack_require__(5);
  110521. exports.ViewerModel = viewerModel_1.ViewerModel;
  110522. exports.ModelState = viewerModel_1.ModelState;
  110523. /**
  110524. * BabylonJS Viewer
  110525. *
  110526. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  110527. */
  110528. var BABYLON = __webpack_require__(0);
  110529. exports.BABYLON = BABYLON;
  110530. // load needed modules.
  110531. __webpack_require__(14);
  110532. __webpack_require__(64);
  110533. var initializer_1 = __webpack_require__(65);
  110534. exports.InitTags = initializer_1.InitTags;
  110535. // promise polyfill, if needed!
  110536. BABYLON.PromisePolyfill.Apply();
  110537. initializer_1.initListeners();
  110538. //deprectaed, here for backwards compatibility
  110539. var disableInit = globals_1.viewerGlobals.disableInit;
  110540. exports.disableInit = disableInit;
  110541. /**
  110542. * Dispose all viewers currently registered
  110543. */
  110544. function disposeAll() {
  110545. viewerManager_1.viewerManager.dispose();
  110546. mappers_1.mapperManager.dispose();
  110547. telemetryManager_1.telemetryManager.dispose();
  110548. }
  110549. exports.disposeAll = disposeAll;
  110550. var Version = globals_1.viewerGlobals.version;
  110551. exports.Version = Version;
  110552. console.log("Babylon.js viewer (v" + Version + ")");
  110553. // export publicliy all configuration interfaces
  110554. __export(__webpack_require__(10));
  110555. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q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0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  110556. /***/ }),
  110557. /* 17 */
  110558. /***/ (function(module, exports) {
  110559. var g;
  110560. // This works in non-strict mode
  110561. g = (function() {
  110562. return this;
  110563. })();
  110564. try {
  110565. // This works if eval is allowed (see CSP)
  110566. g = g || Function("return this")() || (1,eval)("this");
  110567. } catch(e) {
  110568. // This works if the window reference is available
  110569. if(typeof window === "object")
  110570. g = window;
  110571. }
  110572. // g can still be undefined, but nothing to do about it...
  110573. // We return undefined, instead of nothing here, so it's
  110574. // easier to handle this case. if(!global) { ...}
  110575. module.exports = g;
  110576. /***/ }),
  110577. /* 18 */
  110578. /***/ (function(module, exports) {
  110579. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110580. module.exports = CANNON;
  110581. /***/ }),
  110582. /* 19 */
  110583. /***/ (function(module, exports) {
  110584. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110585. module.exports = OIMO;
  110586. /***/ }),
  110587. /* 20 */
  110588. /***/ (function(module, exports) {
  110589. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  110590. module.exports = earcut;
  110591. /***/ }),
  110592. /* 21 */
  110593. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  110594. "use strict";
  110595. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  110596. var isMergeableObject = function isMergeableObject(value) {
  110597. return isNonNullObject(value)
  110598. && !isSpecial(value)
  110599. };
  110600. function isNonNullObject(value) {
  110601. return !!value && typeof value === 'object'
  110602. }
  110603. function isSpecial(value) {
  110604. var stringValue = Object.prototype.toString.call(value);
  110605. return stringValue === '[object RegExp]'
  110606. || stringValue === '[object Date]'
  110607. || isReactElement(value)
  110608. }
  110609. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  110610. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  110611. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  110612. function isReactElement(value) {
  110613. return value.$$typeof === REACT_ELEMENT_TYPE
  110614. }
  110615. function emptyTarget(val) {
  110616. return Array.isArray(val) ? [] : {}
  110617. }
  110618. function cloneUnlessOtherwiseSpecified(value, options) {
  110619. return (options.clone !== false && options.isMergeableObject(value))
  110620. ? deepmerge(emptyTarget(value), value, options)
  110621. : value
  110622. }
  110623. function defaultArrayMerge(target, source, options) {
  110624. return target.concat(source).map(function(element) {
  110625. return cloneUnlessOtherwiseSpecified(element, options)
  110626. })
  110627. }
  110628. function mergeObject(target, source, options) {
  110629. var destination = {};
  110630. if (options.isMergeableObject(target)) {
  110631. Object.keys(target).forEach(function(key) {
  110632. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  110633. });
  110634. }
  110635. Object.keys(source).forEach(function(key) {
  110636. if (!options.isMergeableObject(source[key]) || !target[key]) {
  110637. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  110638. } else {
  110639. destination[key] = deepmerge(target[key], source[key], options);
  110640. }
  110641. });
  110642. return destination
  110643. }
  110644. function deepmerge(target, source, options) {
  110645. options = options || {};
  110646. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  110647. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  110648. var sourceIsArray = Array.isArray(source);
  110649. var targetIsArray = Array.isArray(target);
  110650. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  110651. if (!sourceAndTargetTypesMatch) {
  110652. return cloneUnlessOtherwiseSpecified(source, options)
  110653. } else if (sourceIsArray) {
  110654. return options.arrayMerge(target, source, options)
  110655. } else {
  110656. return mergeObject(target, source, options)
  110657. }
  110658. }
  110659. deepmerge.all = function deepmergeAll(array, options) {
  110660. if (!Array.isArray(array)) {
  110661. throw new Error('first argument should be an array')
  110662. }
  110663. return array.reduce(function(prev, next) {
  110664. return deepmerge(prev, next, options)
  110665. }, {})
  110666. };
  110667. var deepmerge_1 = deepmerge;
  110668. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  110669. /***/ }),
  110670. /* 22 */
  110671. /***/ (function(module, exports, __webpack_require__) {
  110672. "use strict";
  110673. Object.defineProperty(exports, "__esModule", { value: true });
  110674. var babylonjs_1 = __webpack_require__(0);
  110675. var configuration_1 = __webpack_require__(10);
  110676. var viewerModel_1 = __webpack_require__(5);
  110677. var helper_1 = __webpack_require__(1);
  110678. var viewerLabs_1 = __webpack_require__(24);
  110679. var _1 = __webpack_require__(26);
  110680. var SceneManager = /** @class */ (function () {
  110681. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  110682. var _this = this;
  110683. this._engine = _engine;
  110684. this._configurationContainer = _configurationContainer;
  110685. this._observablesManager = _observablesManager;
  110686. this._animationBlendingEnabled = true;
  110687. this._white = babylonjs_1.Color3.White();
  110688. this._forceShadowUpdate = false;
  110689. this._processShadows = true;
  110690. this._groundEnabled = true;
  110691. this._groundMirrorEnabled = true;
  110692. this._defaultRenderingPipelineEnabled = false;
  110693. this._globalConfiguration = {};
  110694. this._defaultRenderingPipelineShouldBuild = true;
  110695. // default from rendering pipeline
  110696. this._bloomEnabled = false;
  110697. // default from rendering pipeline
  110698. this._fxaaEnabled = false;
  110699. this._focusOnModel = function (model) {
  110700. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  110701. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  110702. var halfSizeVec = sizeVec.scale(0.5);
  110703. var center = boundingInfo.min.add(halfSizeVec);
  110704. _this.camera.setTarget(center);
  110705. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  110706. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  110707. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  110708. var sceneDiagonalLenght = sizeVec.length();
  110709. if (isFinite(sceneDiagonalLenght))
  110710. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  110711. if (_this._configurationContainer.configuration)
  110712. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  110713. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  110714. // casting ais safe, due to the constraints tested before
  110715. (<ShadowLight>light).setDirectionToTarget(center);
  110716. });*/
  110717. };
  110718. this._cameraBehaviorMapping = {};
  110719. this.models = [];
  110720. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  110721. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  110722. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  110723. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  110724. this.onSceneInitObservable = new babylonjs_1.Observable();
  110725. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  110726. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  110727. //this._viewer.onEngineInitObservable.add(() => {
  110728. this._handleHardwareLimitations();
  110729. //});
  110730. this.onSceneInitObservable.add(function (scene) {
  110731. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  110732. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  110733. var updateShadows = function () {
  110734. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  110735. var light = _a[_i];
  110736. var generator = light.getShadowGenerator();
  110737. if (generator) {
  110738. // Processing shadows if animates
  110739. var shadowMap = generator.getShadowMap();
  110740. if (shadowMap) {
  110741. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  110742. }
  110743. }
  110744. }
  110745. };
  110746. scene.registerBeforeRender(function () {
  110747. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  110748. // make sure all models are loaded
  110749. updateShadows();
  110750. _this._forceShadowUpdate = false;
  110751. }
  110752. else if (!(_this.models.every(function (model) {
  110753. if (!model.shadowsRenderedAfterLoad) {
  110754. model.shadowsRenderedAfterLoad = true;
  110755. return false;
  110756. }
  110757. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  110758. }))) {
  110759. updateShadows();
  110760. }
  110761. });
  110762. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  110763. });
  110764. if (this._observablesManager) {
  110765. this._observablesManager.onModelLoadedObservable.add(function (model) {
  110766. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  110767. var light = _a[_i];
  110768. var generator = light.getShadowGenerator();
  110769. if (generator) {
  110770. // Processing shadows if animates
  110771. var shadowMap = generator.getShadowMap();
  110772. if (shadowMap) {
  110773. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  110774. }
  110775. }
  110776. }
  110777. _this._focusOnModel(model);
  110778. });
  110779. this._observablesManager.onModelAddedObservable.add(function (model) {
  110780. _this.models.push(model);
  110781. });
  110782. this._observablesManager.onModelRemovedObservable.add(function (model) {
  110783. _this.models.splice(_this.models.indexOf(model), 1);
  110784. });
  110785. }
  110786. }
  110787. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  110788. get: function () {
  110789. return this._defaultRenderingPipeline;
  110790. },
  110791. enumerable: true,
  110792. configurable: true
  110793. });
  110794. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  110795. /**
  110796. * Returns a boolean representing HDR support
  110797. */
  110798. get: function () {
  110799. return this._hdrSupport;
  110800. },
  110801. enumerable: true,
  110802. configurable: true
  110803. });
  110804. Object.defineProperty(SceneManager.prototype, "mainColor", {
  110805. /**
  110806. * Return the main color defined in the configuration.
  110807. */
  110808. get: function () {
  110809. return this._configurationContainer.mainColor;
  110810. },
  110811. enumerable: true,
  110812. configurable: true
  110813. });
  110814. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  110815. get: function () {
  110816. return this._configurationContainer.reflectionColor;
  110817. },
  110818. enumerable: true,
  110819. configurable: true
  110820. });
  110821. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  110822. get: function () {
  110823. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  110824. },
  110825. set: function (value) {
  110826. this.scene.animationPropertiesOverride.enableBlending = value;
  110827. },
  110828. enumerable: true,
  110829. configurable: true
  110830. });
  110831. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  110832. get: function () {
  110833. return this._observablesManager;
  110834. },
  110835. enumerable: true,
  110836. configurable: true
  110837. });
  110838. Object.defineProperty(SceneManager.prototype, "processShadows", {
  110839. /**
  110840. * The flag defining whether shadows are rendered constantly or once.
  110841. */
  110842. get: function () {
  110843. return this._processShadows;
  110844. },
  110845. /**
  110846. * Should shadows be rendered every frame, or only once and stop.
  110847. * This can be used to optimize a scene.
  110848. *
  110849. * Not that the shadows will NOT disapear but will remain in place.
  110850. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  110851. */
  110852. set: function (process) {
  110853. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  110854. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  110855. var light = _a[_i];
  110856. var generator = light.getShadowGenerator();
  110857. if (generator) {
  110858. var shadowMap = generator.getShadowMap();
  110859. if (shadowMap) {
  110860. shadowMap.refreshRate = refreshType;
  110861. }
  110862. }
  110863. }
  110864. this._processShadows = process;
  110865. },
  110866. enumerable: true,
  110867. configurable: true
  110868. });
  110869. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  110870. get: function () {
  110871. return this._groundEnabled;
  110872. },
  110873. set: function (newValue) {
  110874. if (newValue === this._groundEnabled)
  110875. return;
  110876. this._groundEnabled = newValue;
  110877. if (this.environmentHelper && this.environmentHelper.ground) {
  110878. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  110879. }
  110880. },
  110881. enumerable: true,
  110882. configurable: true
  110883. });
  110884. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  110885. /**
  110886. * gets wether the reflection is disabled.
  110887. */
  110888. get: function () {
  110889. return this._groundMirrorEnabled;
  110890. },
  110891. /**
  110892. * sets wether the reflection is disabled.
  110893. */
  110894. set: function (value) {
  110895. if (this._groundMirrorEnabled === value) {
  110896. return;
  110897. }
  110898. this._groundMirrorEnabled = value;
  110899. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  110900. if (!value) {
  110901. this.environmentHelper.groundMaterial.reflectionTexture = null;
  110902. }
  110903. else {
  110904. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  110905. }
  110906. }
  110907. },
  110908. enumerable: true,
  110909. configurable: true
  110910. });
  110911. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  110912. get: function () {
  110913. return this._defaultRenderingPipelineEnabled;
  110914. },
  110915. set: function (value) {
  110916. if (value === this._defaultRenderingPipelineEnabled) {
  110917. return;
  110918. }
  110919. this._defaultRenderingPipelineEnabled = value;
  110920. this._rebuildPostprocesses();
  110921. if (this._defaultRenderingPipeline) {
  110922. this._defaultRenderingPipelineShouldBuild = false;
  110923. this._defaultRenderingPipeline.prepare();
  110924. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110925. }
  110926. },
  110927. enumerable: true,
  110928. configurable: true
  110929. });
  110930. /**
  110931. * Sets the engine flags to unlock all babylon features.
  110932. * Can also be configured using the scene.flags configuration object
  110933. */
  110934. SceneManager.prototype.unlockBabylonFeatures = function () {
  110935. this.scene.shadowsEnabled = true;
  110936. this.scene.particlesEnabled = true;
  110937. this.scene.postProcessesEnabled = true;
  110938. this.scene.collisionsEnabled = true;
  110939. this.scene.lightsEnabled = true;
  110940. this.scene.texturesEnabled = true;
  110941. this.scene.lensFlaresEnabled = true;
  110942. this.scene.proceduralTexturesEnabled = true;
  110943. this.scene.renderTargetsEnabled = true;
  110944. this.scene.spritesEnabled = true;
  110945. this.scene.skeletonsEnabled = true;
  110946. this.scene.audioEnabled = true;
  110947. };
  110948. /**
  110949. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  110950. */
  110951. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  110952. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  110953. // if the scen exists, dispose it.
  110954. if (this.scene) {
  110955. this.scene.dispose();
  110956. }
  110957. // create a new scene
  110958. this.scene = new babylonjs_1.Scene(this._engine);
  110959. this._configurationContainer.scene = this.scene;
  110960. // set a default PBR material
  110961. if (!sceneConfiguration.defaultMaterial) {
  110962. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  110963. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  110964. defaultMaterial.microSurface = 0.6;
  110965. if (this.scene.defaultMaterial) {
  110966. this.scene.defaultMaterial.dispose();
  110967. }
  110968. this.scene.defaultMaterial = defaultMaterial;
  110969. }
  110970. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  110971. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  110972. /*if (sceneConfiguration.glow) {
  110973. let options: Partial<IGlowLayerOptions> = {
  110974. mainTextureFixedSize: 512
  110975. };
  110976. if (typeof sceneConfiguration.glow === 'object') {
  110977. options = sceneConfiguration.glow
  110978. }
  110979. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  110980. }*/
  110981. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  110982. };
  110983. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  110984. if (clearModels === void 0) { clearModels = true; }
  110985. if (clearLights === void 0) { clearLights = false; }
  110986. if (clearModels) {
  110987. this.models.forEach(function (m) { return m.dispose(); });
  110988. this.models.length = 0;
  110989. }
  110990. if (clearLights) {
  110991. this.scene.lights.forEach(function (l) { return l.dispose(); });
  110992. }
  110993. };
  110994. /**
  110995. * This will update the scene's configuration, including camera, lights, environment.
  110996. * @param newConfiguration the delta that should be configured. This includes only the changes
  110997. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  110998. */
  110999. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  111000. var _this = this;
  111001. if (this._configurationContainer) {
  111002. this._globalConfiguration = this._configurationContainer.configuration;
  111003. }
  111004. else {
  111005. this._globalConfiguration = newConfiguration;
  111006. }
  111007. if (newConfiguration.lab) {
  111008. if (newConfiguration.lab.assetsRootURL) {
  111009. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  111010. }
  111011. }
  111012. // update scene configuration
  111013. if (newConfiguration.scene) {
  111014. this._configureScene(newConfiguration.scene);
  111015. }
  111016. // optimizer
  111017. if (newConfiguration.optimizer !== undefined) {
  111018. this._configureOptimizer(newConfiguration.optimizer);
  111019. }
  111020. // configure model
  111021. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  111022. this._configureModel(newConfiguration.model);
  111023. }*/
  111024. // lights
  111025. this._configureLights(newConfiguration.lights);
  111026. // environment
  111027. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  111028. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  111029. }
  111030. // camera
  111031. this._configureCamera(newConfiguration.camera);
  111032. if (newConfiguration.lab) {
  111033. if (newConfiguration.lab.environmentMap) {
  111034. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  111035. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  111036. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  111037. });
  111038. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  111039. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  111040. }
  111041. }
  111042. // rendering piplines
  111043. if (newConfiguration.lab.defaultRenderingPipelines) {
  111044. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  111045. if (typeof pipelineConfig === 'boolean') {
  111046. this.defaultRenderingPipelineEnabled = pipelineConfig;
  111047. }
  111048. else {
  111049. this.defaultRenderingPipelineEnabled = true;
  111050. }
  111051. }
  111052. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  111053. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  111054. this.environmentHelper.setMainColor(mainColor);
  111055. }
  111056. if (newConfiguration.lab.globalLightRotation !== undefined) {
  111057. // rotate all lights that are shadow lights
  111058. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  111059. // casting and '!' are safe, due to the constraints tested before
  111060. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  111061. });
  111062. this._forceShadowUpdate = true;
  111063. }
  111064. }
  111065. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  111066. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  111067. }
  111068. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  111069. this._defaultRenderingPipelineShouldBuild = false;
  111070. this._defaultRenderingPipeline.prepare();
  111071. }
  111072. };
  111073. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  111074. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  111075. if (this._defaultRenderingPipeline) {
  111076. this._defaultRenderingPipeline.dispose();
  111077. this._defaultRenderingPipeline = null;
  111078. this.scene.autoClearDepthAndStencil = true;
  111079. this.scene.autoClear = true;
  111080. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  111081. }
  111082. return;
  111083. }
  111084. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  111085. if (pipelineConfig) {
  111086. if (!this._defaultRenderingPipeline) {
  111087. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  111088. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  111089. }
  111090. this.scene.autoClear = false;
  111091. this.scene.autoClearDepthAndStencil = false;
  111092. this._defaultRenderingPipelineShouldBuild = true;
  111093. var bloomEnabled = this._bloomEnabled;
  111094. if (typeof pipelineConfig !== 'boolean') {
  111095. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  111096. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  111097. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  111098. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  111099. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  111100. }
  111101. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  111102. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  111103. }
  111104. };
  111105. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  111106. get: function () {
  111107. return this._bloomEnabled;
  111108. },
  111109. set: function (value) {
  111110. if (this._bloomEnabled === value) {
  111111. return;
  111112. }
  111113. this._bloomEnabled = value;
  111114. this._rebuildPostprocesses();
  111115. if (this._defaultRenderingPipeline) {
  111116. this._defaultRenderingPipelineShouldBuild = false;
  111117. this._defaultRenderingPipeline.prepare();
  111118. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111119. }
  111120. },
  111121. enumerable: true,
  111122. configurable: true
  111123. });
  111124. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  111125. get: function () {
  111126. return this._fxaaEnabled;
  111127. },
  111128. set: function (value) {
  111129. if (this._fxaaEnabled === value) {
  111130. return;
  111131. }
  111132. this._fxaaEnabled = value;
  111133. this._rebuildPostprocesses();
  111134. if (this._defaultRenderingPipeline) {
  111135. this._defaultRenderingPipelineShouldBuild = false;
  111136. this._defaultRenderingPipeline.prepare();
  111137. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  111138. }
  111139. },
  111140. enumerable: true,
  111141. configurable: true
  111142. });
  111143. /**
  111144. * internally configure the scene using the provided configuration.
  111145. * The scene will not be recreated, but just updated.
  111146. * @param sceneConfig the (new) scene configuration
  111147. */
  111148. SceneManager.prototype._configureScene = function (sceneConfig) {
  111149. // sanity check!
  111150. if (!this.scene) {
  111151. return;
  111152. }
  111153. var cc = sceneConfig.clearColor;
  111154. var oldcc = this.scene.clearColor;
  111155. if (cc) {
  111156. if (cc.r !== undefined) {
  111157. oldcc.r = cc.r;
  111158. }
  111159. if (cc.g !== undefined) {
  111160. oldcc.g = cc.g;
  111161. }
  111162. if (cc.b !== undefined) {
  111163. oldcc.b = cc.b;
  111164. }
  111165. if (cc.a !== undefined) {
  111166. oldcc.a = cc.a;
  111167. }
  111168. }
  111169. // image processing configuration - optional.
  111170. if (sceneConfig.imageProcessingConfiguration) {
  111171. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  111172. }
  111173. //animation properties override
  111174. if (sceneConfig.animationPropertiesOverride) {
  111175. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  111176. }
  111177. if (sceneConfig.environmentTexture) {
  111178. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  111179. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  111180. this.scene.environmentTexture.dispose();
  111181. }
  111182. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  111183. this.scene.environmentTexture = environmentTexture;
  111184. }
  111185. }
  111186. if (sceneConfig.debug === true) {
  111187. this.scene.debugLayer.show();
  111188. }
  111189. else if (sceneConfig.debug === false) {
  111190. if (this.scene.debugLayer.isVisible()) {
  111191. this.scene.debugLayer.hide();
  111192. }
  111193. }
  111194. if (sceneConfig.disableHdr) {
  111195. this._handleHardwareLimitations(false);
  111196. }
  111197. else {
  111198. this._handleHardwareLimitations(true);
  111199. }
  111200. if (sceneConfig.renderInBackground !== undefined) {
  111201. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  111202. }
  111203. var canvas = this._engine.getRenderingCanvas();
  111204. if (canvas) {
  111205. if (this.camera && sceneConfig.disableCameraControl) {
  111206. this.camera.detachControl(canvas);
  111207. }
  111208. else if (this.camera && sceneConfig.disableCameraControl === false) {
  111209. this.camera.attachControl(canvas);
  111210. }
  111211. }
  111212. // process mainColor changes:
  111213. if (sceneConfig.mainColor) {
  111214. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  111215. var mc = sceneConfig.mainColor;
  111216. if (mc.r !== undefined) {
  111217. this.mainColor.r = mc.r;
  111218. }
  111219. if (mc.g !== undefined) {
  111220. this.mainColor.g = mc.g;
  111221. }
  111222. if (mc.b !== undefined) {
  111223. this.mainColor.b = mc.b;
  111224. }
  111225. this.reflectionColor.copyFrom(this.mainColor);
  111226. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  111227. // reflection color
  111228. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  111229. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  111230. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  111231. this.reflectionColor.copyFrom(tmpColor3);
  111232. //update the environment, if exists
  111233. if (this.environmentHelper) {
  111234. if (this.environmentHelper.groundMaterial) {
  111235. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  111236. }
  111237. if (this.environmentHelper.skyboxMaterial) {
  111238. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  111239. }
  111240. }
  111241. }
  111242. if (sceneConfig.defaultMaterial) {
  111243. var conf = sceneConfig.defaultMaterial;
  111244. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  111245. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  111246. this.scene.defaultMaterial.dispose();
  111247. if (conf.materialType === 'standard') {
  111248. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  111249. }
  111250. else {
  111251. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  111252. }
  111253. }
  111254. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  111255. }
  111256. if (sceneConfig.flags) {
  111257. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  111258. }
  111259. this.onSceneConfiguredObservable.notifyObservers({
  111260. sceneManager: this,
  111261. object: this.scene,
  111262. newConfiguration: sceneConfig
  111263. });
  111264. };
  111265. /**
  111266. * Configure the scene optimizer.
  111267. * The existing scene optimizer will be disposed and a new one will be created.
  111268. * @param optimizerConfig the (new) optimizer configuration
  111269. */
  111270. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  111271. var _this = this;
  111272. if (typeof optimizerConfig === 'boolean') {
  111273. if (this.sceneOptimizer) {
  111274. this.sceneOptimizer.stop();
  111275. this.sceneOptimizer.dispose();
  111276. delete this.sceneOptimizer;
  111277. }
  111278. if (optimizerConfig) {
  111279. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  111280. this.sceneOptimizer.start();
  111281. }
  111282. }
  111283. else {
  111284. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  111285. // check for degradation
  111286. if (optimizerConfig.degradation) {
  111287. switch (optimizerConfig.degradation) {
  111288. case "low":
  111289. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  111290. break;
  111291. case "moderate":
  111292. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  111293. break;
  111294. case "hight":
  111295. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  111296. break;
  111297. }
  111298. }
  111299. if (this.sceneOptimizer) {
  111300. this.sceneOptimizer.stop();
  111301. this.sceneOptimizer.dispose();
  111302. }
  111303. if (optimizerConfig.custom) {
  111304. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  111305. if (customOptimizer_1) {
  111306. optimizerOptions.addCustomOptimization(function () {
  111307. return customOptimizer_1(_this);
  111308. }, function () {
  111309. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  111310. });
  111311. }
  111312. }
  111313. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  111314. this.sceneOptimizer.start();
  111315. }
  111316. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  111317. sceneManager: this,
  111318. object: this.sceneOptimizer,
  111319. newConfiguration: optimizerConfig
  111320. });
  111321. };
  111322. /**
  111323. * configure all models using the configuration.
  111324. * @param modelConfiguration the configuration to use to reconfigure the models
  111325. */
  111326. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  111327. this.models.forEach(model => {
  111328. model.updateConfiguration(modelConfiguration);
  111329. });
  111330. this.onModelsConfiguredObservable.notifyObservers({
  111331. sceneManager: this,
  111332. object: this.models,
  111333. newConfiguration: modelConfiguration
  111334. });
  111335. }*/
  111336. /**
  111337. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  111338. * @param cameraConfig the new camera configuration
  111339. * @param model optionally use the model to configure the camera.
  111340. */
  111341. SceneManager.prototype._configureCamera = function (cameraConfig) {
  111342. var _this = this;
  111343. if (cameraConfig === void 0) { cameraConfig = {}; }
  111344. if (!this.scene.activeCamera) {
  111345. var attachControl = true;
  111346. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  111347. attachControl = false;
  111348. }
  111349. this.scene.createDefaultCamera(true, true, attachControl);
  111350. this.camera = this.scene.activeCamera;
  111351. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  111352. }
  111353. if (cameraConfig.position) {
  111354. var newPosition = this.camera.position.clone();
  111355. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  111356. this.camera.setPosition(newPosition);
  111357. }
  111358. if (cameraConfig.target) {
  111359. var newTarget = this.camera.target.clone();
  111360. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  111361. this.camera.setTarget(newTarget);
  111362. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  111363. this._focusOnModel(this.models[0]);
  111364. }*/
  111365. if (cameraConfig.rotation) {
  111366. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  111367. }
  111368. if (cameraConfig.behaviors) {
  111369. for (var name_1 in cameraConfig.behaviors) {
  111370. if (cameraConfig.behaviors[name_1] !== undefined) {
  111371. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  111372. }
  111373. }
  111374. }
  111375. ;
  111376. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  111377. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  111378. });
  111379. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111380. var sceneDiagonalLenght = sceneDiagonal.length();
  111381. if (isFinite(sceneDiagonalLenght))
  111382. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  111383. // sanity check!
  111384. if (this.scene.imageProcessingConfiguration) {
  111385. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  111386. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  111387. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  111388. }
  111389. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  111390. this.onCameraConfiguredObservable.notifyObservers({
  111391. sceneManager: this,
  111392. object: this.camera,
  111393. newConfiguration: cameraConfig
  111394. });
  111395. };
  111396. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  111397. var _this = this;
  111398. if (!skyboxConifguration && !groundConfiguration) {
  111399. if (this.environmentHelper) {
  111400. this.environmentHelper.dispose();
  111401. this.environmentHelper = undefined;
  111402. }
  111403. ;
  111404. }
  111405. else {
  111406. var options = {
  111407. createGround: !!groundConfiguration && this._groundEnabled,
  111408. createSkybox: !!skyboxConifguration,
  111409. setupImageProcessing: false,
  111410. };
  111411. // will that cause problems with model ground configuration?
  111412. /*if (model) {
  111413. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  111414. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  111415. const halfSizeVec = sizeVec.scale(0.5);
  111416. const center = boundingInfo.min.add(halfSizeVec);
  111417. options.groundYBias = -center.y;
  111418. }*/
  111419. if (groundConfiguration) {
  111420. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  111421. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  111422. if (groundSize) {
  111423. options.groundSize = groundSize;
  111424. }
  111425. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  111426. if (groundConfig_1.shadowLevel !== undefined) {
  111427. options.groundShadowLevel = groundConfig_1.shadowLevel;
  111428. }
  111429. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  111430. if (groundConfig_1.texture) {
  111431. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  111432. }
  111433. if (groundConfig_1.color) {
  111434. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  111435. }
  111436. if (groundConfig_1.opacity !== undefined) {
  111437. options.groundOpacity = groundConfig_1.opacity;
  111438. }
  111439. if (groundConfig_1.mirror) {
  111440. options.enableGroundMirror = true;
  111441. // to prevent undefines
  111442. if (typeof groundConfig_1.mirror === "object") {
  111443. if (groundConfig_1.mirror.amount !== undefined)
  111444. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  111445. if (groundConfig_1.mirror.sizeRatio !== undefined)
  111446. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  111447. if (groundConfig_1.mirror.blurKernel !== undefined)
  111448. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  111449. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  111450. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  111451. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  111452. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  111453. if (this._defaultPipelineTextureType !== undefined)
  111454. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  111455. }
  111456. }
  111457. }
  111458. var postInitSkyboxMaterial = false;
  111459. if (skyboxConifguration) {
  111460. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  111461. if (conf.material && conf.material.imageProcessingConfiguration) {
  111462. options.setupImageProcessing = false; // will be configured later manually.
  111463. }
  111464. var skyboxSize = conf.scale;
  111465. if (skyboxSize) {
  111466. options.skyboxSize = skyboxSize;
  111467. }
  111468. options.sizeAuto = !options.skyboxSize;
  111469. if (conf.color) {
  111470. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  111471. }
  111472. if (conf.cubeTexture && conf.cubeTexture.url) {
  111473. if (typeof conf.cubeTexture.url === "string") {
  111474. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  111475. }
  111476. else {
  111477. // init later!
  111478. postInitSkyboxMaterial = true;
  111479. }
  111480. }
  111481. if (conf.material) {
  111482. postInitSkyboxMaterial = true;
  111483. }
  111484. }
  111485. options.setupImageProcessing = false; // TMP
  111486. if (!this.environmentHelper) {
  111487. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  111488. }
  111489. else {
  111490. // unlikely, but there might be a new scene! we need to dispose.
  111491. // get the scene used by the envHelper
  111492. var scene = this.environmentHelper.rootMesh.getScene();
  111493. // is it a different scene? Oh no!
  111494. if (scene !== this.scene) {
  111495. this.environmentHelper.dispose();
  111496. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  111497. }
  111498. else {
  111499. // recreate the ground
  111500. if (this.environmentHelper.ground) {
  111501. this.environmentHelper.ground.dispose();
  111502. }
  111503. // recreate the skybox
  111504. if (this.environmentHelper.skybox) {
  111505. this.environmentHelper.skybox.dispose();
  111506. }
  111507. this.environmentHelper.updateOptions(options);
  111508. // update doesn't change the size of the skybox and ground, so we have to recreate!
  111509. //this.environmentHelper.dispose();
  111510. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  111511. }
  111512. }
  111513. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  111514. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  111515. }
  111516. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  111517. if (this.environmentHelper.groundMaterial && groundConfig) {
  111518. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  111519. if (groundConfig.material) {
  111520. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  111521. }
  111522. if (this.environmentHelper.groundMirror) {
  111523. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  111524. // TODO user camera exposure value to set the mirror clear color
  111525. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  111526. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  111527. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  111528. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  111529. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  111530. this.environmentHelper.groundMirror.clearColor.a = 1;
  111531. if (!this.groundMirrorEnabled) {
  111532. this.environmentHelper.groundMaterial.reflectionTexture = null;
  111533. }
  111534. }
  111535. }
  111536. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  111537. if (skyboxMaterial) {
  111538. skyboxMaterial._perceptualColor = this.mainColor;
  111539. if (postInitSkyboxMaterial) {
  111540. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  111541. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  111542. }
  111543. }
  111544. }
  111545. }
  111546. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  111547. _this._updateGroundMirrorRenderList(model);
  111548. });
  111549. this.onEnvironmentConfiguredObservable.notifyObservers({
  111550. sceneManager: this,
  111551. object: this.environmentHelper,
  111552. newConfiguration: {
  111553. skybox: skyboxConifguration,
  111554. ground: groundConfiguration
  111555. }
  111556. });
  111557. };
  111558. /**
  111559. * configure the lights.
  111560. *
  111561. * @param lightsConfiguration the (new) light(s) configuration
  111562. * @param model optionally use the model to configure the camera.
  111563. */
  111564. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  111565. var _this = this;
  111566. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  111567. // sanity check!
  111568. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  111569. if (!lightKeys.length) {
  111570. if (!this.scene.lights.length)
  111571. this.scene.createDefaultLight(true);
  111572. }
  111573. else {
  111574. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  111575. // compare to the global (!) configuration object and dispose unneeded:
  111576. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  111577. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  111578. lightsAvailable_1.forEach(function (lName) {
  111579. if (lightsToConfigure_1.indexOf(lName) === -1) {
  111580. _this.scene.getLightByName(lName).dispose();
  111581. }
  111582. });
  111583. }
  111584. lightKeys.forEach(function (name, idx) {
  111585. var lightConfig = { type: 0 };
  111586. if (typeof lightsConfiguration[name] === 'object') {
  111587. lightConfig = lightsConfiguration[name];
  111588. }
  111589. if (typeof lightsConfiguration[name] === 'number') {
  111590. lightConfig.type = lightsConfiguration[name];
  111591. }
  111592. lightConfig.name = name;
  111593. var light;
  111594. // light is not already available
  111595. if (lightsAvailable_1.indexOf(name) === -1) {
  111596. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  111597. if (!constructor)
  111598. return;
  111599. light = constructor();
  111600. }
  111601. else {
  111602. // available? get it from the scene
  111603. light = _this.scene.getLightByName(name);
  111604. if (typeof lightsConfiguration[name] === 'boolean') {
  111605. lightConfig.type = light.getTypeID();
  111606. }
  111607. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  111608. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  111609. light.dispose();
  111610. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  111611. if (!constructor)
  111612. return;
  111613. light = constructor();
  111614. }
  111615. }
  111616. // if config set the light to false, dispose it.
  111617. if (lightsConfiguration[name] === false) {
  111618. light.dispose();
  111619. return;
  111620. }
  111621. //enabled
  111622. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  111623. light.setEnabled(enabled);
  111624. helper_1.extendClassWithConfig(light, lightConfig);
  111625. //position. Some lights don't support shadows
  111626. if (light instanceof babylonjs_1.ShadowLight) {
  111627. // set default values
  111628. light.shadowMinZ = light.shadowMinZ || 0.2;
  111629. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  111630. if (lightConfig.target) {
  111631. if (light.setDirectionToTarget) {
  111632. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  111633. light.setDirectionToTarget(target);
  111634. }
  111635. }
  111636. else if (lightConfig.direction) {
  111637. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  111638. light.direction = direction;
  111639. }
  111640. var isShadowEnabled = false;
  111641. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  111642. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  111643. isShadowEnabled = true;
  111644. }
  111645. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  111646. var spotLight = light;
  111647. if (lightConfig.spotAngle !== undefined) {
  111648. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  111649. }
  111650. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  111651. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  111652. }
  111653. isShadowEnabled = true;
  111654. }
  111655. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  111656. if (lightConfig.shadowFieldOfView) {
  111657. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  111658. }
  111659. isShadowEnabled = true;
  111660. }
  111661. var shadowGenerator_1 = light.getShadowGenerator();
  111662. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  111663. var bufferSize = lightConfig.shadowBufferSize || 256;
  111664. if (!shadowGenerator_1) {
  111665. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  111666. }
  111667. var blurKernel = _this.getBlurKernel(light, bufferSize);
  111668. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  111669. shadowGenerator_1.blurKernel = blurKernel;
  111670. //override defaults
  111671. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  111672. // add the focues meshes to the shadow list
  111673. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  111674. _this._updateShadowRenderList(shadowGenerator_1, model);
  111675. });
  111676. //if (model) {
  111677. _this._updateShadowRenderList(shadowGenerator_1);
  111678. //}
  111679. }
  111680. else if (shadowGenerator_1) {
  111681. shadowGenerator_1.dispose();
  111682. }
  111683. }
  111684. });
  111685. // render priority
  111686. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  111687. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  111688. var configuration = globalLightsConfiguration_1[name];
  111689. var light = _this.scene.getLightByName(name);
  111690. // sanity check
  111691. if (!light)
  111692. return;
  111693. light.renderPriority = -idx;
  111694. });
  111695. }
  111696. this.onLightsConfiguredObservable.notifyObservers({
  111697. sceneManager: this,
  111698. object: this.scene.lights,
  111699. newConfiguration: lightsConfiguration
  111700. });
  111701. };
  111702. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  111703. var focusMeshes = model ? model.meshes : this.scene.meshes;
  111704. // add the focues meshes to the shadow list
  111705. var shadownMap = shadowGenerator.getShadowMap();
  111706. if (!shadownMap)
  111707. return;
  111708. if (resetList && shadownMap.renderList) {
  111709. shadownMap.renderList.length = 0;
  111710. }
  111711. else {
  111712. shadownMap.renderList = shadownMap.renderList || [];
  111713. }
  111714. for (var index = 0; index < focusMeshes.length; index++) {
  111715. var mesh = focusMeshes[index];
  111716. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  111717. shadownMap.renderList.push(mesh);
  111718. }
  111719. }
  111720. if (!this._shadowGroundPlane) {
  111721. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  111722. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  111723. shadowGroundPlane.useVertexColors = false;
  111724. //material isn't ever used in rendering, just used to set back face culling
  111725. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  111726. shadowGroundPlane.material.backFaceCulling = false;
  111727. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  111728. shadowGroundPlane.freezeWorldMatrix();
  111729. this._shadowGroundPlane = shadowGroundPlane;
  111730. this.scene.removeMesh(shadowGroundPlane);
  111731. }
  111732. }
  111733. else {
  111734. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  111735. this._shadowGroundPlane.dispose();
  111736. this._shadowGroundPlane = null;
  111737. }
  111738. }
  111739. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  111740. shadownMap.renderList.push(this._shadowGroundPlane);
  111741. }
  111742. };
  111743. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  111744. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  111745. var focusMeshes = model ? model.meshes : this.scene.meshes;
  111746. var renderList = this.environmentHelper.groundMirror.renderList;
  111747. if (resetList) {
  111748. renderList.length = 0;
  111749. }
  111750. for (var index = 0; index < focusMeshes.length; index++) {
  111751. var mesh = focusMeshes[index];
  111752. if (renderList.indexOf(mesh) === -1) {
  111753. renderList.push(mesh);
  111754. }
  111755. }
  111756. }
  111757. };
  111758. /**
  111759. * Gets the shadow map blur kernel according to the light configuration.
  111760. * @param light The light used to generate the shadows
  111761. * @param bufferSize The size of the shadow map
  111762. * @return the kernel blur size
  111763. */
  111764. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  111765. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  111766. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  111767. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  111768. }
  111769. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  111770. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  111771. }
  111772. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  111773. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  111774. }
  111775. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  111776. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  111777. return blurKernel;
  111778. };
  111779. /**
  111780. * Alters render settings to reduce features based on hardware feature limitations
  111781. * @param enableHDR Allows the viewer to run in HDR mode.
  111782. */
  111783. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  111784. if (enableHDR === void 0) { enableHDR = true; }
  111785. //flip rendering settings switches based on hardware support
  111786. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  111787. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  111788. //shadows are disabled if there's not enough varyings for a single shadow
  111789. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  111790. this._maxShadows = 0;
  111791. }
  111792. else {
  111793. this._maxShadows = 3;
  111794. }
  111795. //can we render to any >= 16-bit targets (required for HDR)
  111796. var caps = this._engine.getCaps();
  111797. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  111798. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  111799. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  111800. if (linearHalfFloatTargets) {
  111801. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  111802. this._shadowGeneratorBias = 0.002;
  111803. }
  111804. else if (linearFloatTargets) {
  111805. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  111806. this._shadowGeneratorBias = 0.001;
  111807. }
  111808. else {
  111809. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  111810. this._shadowGeneratorBias = 0.001;
  111811. }
  111812. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  111813. };
  111814. /**
  111815. * Dispoe the entire viewer including the scene and the engine
  111816. */
  111817. SceneManager.prototype.dispose = function () {
  111818. // this.onCameraConfiguredObservable.clear();
  111819. this.onEnvironmentConfiguredObservable.clear();
  111820. this.onLightsConfiguredObservable.clear();
  111821. this.onModelsConfiguredObservable.clear();
  111822. this.onSceneConfiguredObservable.clear();
  111823. this.onSceneInitObservable.clear();
  111824. this.onSceneOptimizerConfiguredObservable.clear();
  111825. if (this.sceneOptimizer) {
  111826. this.sceneOptimizer.stop();
  111827. this.sceneOptimizer.dispose();
  111828. }
  111829. if (this.environmentHelper) {
  111830. this.environmentHelper.dispose();
  111831. }
  111832. this.models.forEach(function (model) {
  111833. model.dispose();
  111834. });
  111835. if (this._defaultRenderingPipeline) {
  111836. this._defaultRenderingPipeline.dispose();
  111837. }
  111838. this.models.length = 0;
  111839. if (this.scene) {
  111840. this.scene.dispose();
  111841. }
  111842. };
  111843. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  111844. var behavior;
  111845. var type;
  111846. if (typeof behaviorConfig === 'object') {
  111847. type = behaviorConfig.type;
  111848. }
  111849. else if (typeof behaviorConfig === 'number') {
  111850. type = behaviorConfig;
  111851. }
  111852. else {
  111853. type = this._cameraBehaviorMapping[name];
  111854. }
  111855. if (type === undefined)
  111856. return;
  111857. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  111858. var enabled = true;
  111859. if (typeof behaviorConfig === 'boolean') {
  111860. enabled = behaviorConfig;
  111861. }
  111862. // constructing behavior
  111863. switch (type) {
  111864. case 0 /* AUTOROTATION */:
  111865. this.camera.useAutoRotationBehavior = enabled;
  111866. behavior = this.camera.autoRotationBehavior;
  111867. break;
  111868. case 1 /* BOUNCING */:
  111869. this.camera.useBouncingBehavior = enabled;
  111870. behavior = this.camera.bouncingBehavior;
  111871. break;
  111872. case 2 /* FRAMING */:
  111873. this.camera.useFramingBehavior = enabled;
  111874. behavior = this.camera.framingBehavior;
  111875. break;
  111876. default:
  111877. behavior = null;
  111878. break;
  111879. }
  111880. if (behavior) {
  111881. this._cameraBehaviorMapping[name] = type;
  111882. if (typeof behaviorConfig === "object") {
  111883. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  111884. }
  111885. }
  111886. // post attach configuration. Some functionalities require the attached camera.
  111887. switch (type) {
  111888. case 0 /* AUTOROTATION */:
  111889. break;
  111890. case 1 /* BOUNCING */:
  111891. break;
  111892. case 2 /* FRAMING */:
  111893. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  111894. if (config.zoomOnBoundingInfo) {
  111895. behavior.zoomOnMeshHierarchy(model.rootMesh);
  111896. }
  111897. });
  111898. break;
  111899. }
  111900. };
  111901. return SceneManager;
  111902. }());
  111903. exports.SceneManager = SceneManager;
  111904. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUErakI7QUFDL2pCLGtEQUFtUjtBQUNuUixvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBc0ZJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQXlFQztRQXpFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBakN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU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LENBQUMsVUFBQyxLQUFLO29CQUNuRixJQUFJLE1BQU0sQ0FBQyxrQkFBa0IsRUFBRTt3QkFDVCxRQUFTLENBQUMsbUJBQW1CLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxDQUFDO3FCQUNuRTtnQkFDTCxDQUFDLENBQUMsQ0FBQztnQkFDSCxNQUFNO1NBQ2I7SUFDTCxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBejNDRCxJQXkzQ0M7QUF6M0NZLG9DQUFZIn0=
  111905. /***/ }),
  111906. /* 23 */
  111907. /***/ (function(module, exports, __webpack_require__) {
  111908. "use strict";
  111909. Object.defineProperty(exports, "__esModule", { value: true });
  111910. /**
  111911. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  111912. * native GroupAnimation class.
  111913. */
  111914. var GroupModelAnimation = /** @class */ (function () {
  111915. /**
  111916. * Create a new GroupModelAnimation object using an AnimationGroup object
  111917. * @param _animationGroup The aniamtion group to base the class on
  111918. */
  111919. function GroupModelAnimation(_animationGroup) {
  111920. var _this = this;
  111921. this._animationGroup = _animationGroup;
  111922. this._state = 0 /* INIT */;
  111923. this._playMode = 1 /* LOOP */;
  111924. this._animationGroup.onAnimationEndObservable.add(function () {
  111925. _this.stop();
  111926. _this._state = 4 /* ENDED */;
  111927. });
  111928. }
  111929. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  111930. /**
  111931. * Get the animation's name
  111932. */
  111933. get: function () {
  111934. return this._animationGroup.name;
  111935. },
  111936. enumerable: true,
  111937. configurable: true
  111938. });
  111939. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  111940. /**
  111941. * Get the current animation's state
  111942. */
  111943. get: function () {
  111944. return this._state;
  111945. },
  111946. enumerable: true,
  111947. configurable: true
  111948. });
  111949. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  111950. /**
  111951. * Gets the speed ratio to use for all animations
  111952. */
  111953. get: function () {
  111954. return this._animationGroup.speedRatio;
  111955. },
  111956. /**
  111957. * Sets the speed ratio to use for all animations
  111958. */
  111959. set: function (value) {
  111960. this._animationGroup.speedRatio = value;
  111961. },
  111962. enumerable: true,
  111963. configurable: true
  111964. });
  111965. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  111966. /**
  111967. * Get the max numbers of frame available in the animation group
  111968. *
  111969. * In correlation to an arry, this would be ".length"
  111970. */
  111971. get: function () {
  111972. return this._animationGroup.to - this._animationGroup.from;
  111973. },
  111974. enumerable: true,
  111975. configurable: true
  111976. });
  111977. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  111978. /**
  111979. * Get the current frame playing right now.
  111980. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  111981. *
  111982. * In correlation to an array, this would be the current index
  111983. */
  111984. get: function () {
  111985. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  111986. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  111987. }
  111988. else {
  111989. return 0;
  111990. }
  111991. },
  111992. enumerable: true,
  111993. configurable: true
  111994. });
  111995. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  111996. /**
  111997. * Get the FPS value of this animation
  111998. */
  111999. get: function () {
  112000. // get the first currentFrame found
  112001. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  112002. var animatable = this._animationGroup.animatables[i];
  112003. var animations = animatable.getAnimations();
  112004. if (!animations || !animations.length) {
  112005. continue;
  112006. }
  112007. for (var idx = 0; idx < animations.length; ++idx) {
  112008. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  112009. return animations[idx].animation.framePerSecond;
  112010. }
  112011. }
  112012. }
  112013. return 0;
  112014. },
  112015. enumerable: true,
  112016. configurable: true
  112017. });
  112018. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  112019. /**
  112020. * What is the animation'S play mode (looping or played once)
  112021. */
  112022. get: function () {
  112023. return this._playMode;
  112024. },
  112025. /**
  112026. * Set the play mode.
  112027. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  112028. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  112029. */
  112030. set: function (value) {
  112031. if (value === this._playMode) {
  112032. return;
  112033. }
  112034. this._playMode = value;
  112035. if (this.state === 1 /* PLAYING */) {
  112036. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  112037. }
  112038. else {
  112039. this._animationGroup.reset();
  112040. this._state = 0 /* INIT */;
  112041. }
  112042. },
  112043. enumerable: true,
  112044. configurable: true
  112045. });
  112046. /**
  112047. * Reset the animation group
  112048. */
  112049. GroupModelAnimation.prototype.reset = function () {
  112050. this._animationGroup.reset();
  112051. };
  112052. /**
  112053. * Restart the animation group
  112054. */
  112055. GroupModelAnimation.prototype.restart = function () {
  112056. if (this.state === 2 /* PAUSED */)
  112057. this._animationGroup.restart();
  112058. else
  112059. this.start();
  112060. };
  112061. /**
  112062. *
  112063. * @param frameNumber Go to a specific frame in the animation
  112064. */
  112065. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  112066. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  112067. };
  112068. /**
  112069. * Start playing the animation.
  112070. */
  112071. GroupModelAnimation.prototype.start = function () {
  112072. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  112073. if (this._animationGroup.isStarted) {
  112074. this._state = 1 /* PLAYING */;
  112075. }
  112076. };
  112077. /**
  112078. * Pause the animation
  112079. */
  112080. GroupModelAnimation.prototype.pause = function () {
  112081. this._animationGroup.pause();
  112082. this._state = 2 /* PAUSED */;
  112083. };
  112084. /**
  112085. * Stop the animation.
  112086. * This will fail silently if the animation group is already stopped.
  112087. */
  112088. GroupModelAnimation.prototype.stop = function () {
  112089. this._animationGroup.stop();
  112090. if (!this._animationGroup.isStarted) {
  112091. this._state = 3 /* STOPPED */;
  112092. }
  112093. };
  112094. /**
  112095. * Dispose this animation object.
  112096. */
  112097. GroupModelAnimation.prototype.dispose = function () {
  112098. this._animationGroup.dispose();
  112099. };
  112100. return GroupModelAnimation;
  112101. }());
  112102. exports.GroupModelAnimation = GroupModelAnimation;
  112103. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O1dBRUc7YUFDSDtZQUNJLE9BQU8sSUFBSSxDQUFDLE1BQU0sQ0FBQztRQUN2QixDQUFDOzs7T0FBQTtJQUtELHNCQUFXLDJDQUFVO1FBSHJCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsVUFBVSxDQUFDO1FBQzNDLENBQUM7UUFFRDs7V0FFRzthQUNILFVBQXNCLEt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UMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  112104. /***/ }),
  112105. /* 24 */
  112106. /***/ (function(module, exports, __webpack_require__) {
  112107. "use strict";
  112108. Object.defineProperty(exports, "__esModule", { value: true });
  112109. var environmentSerializer_1 = __webpack_require__(25);
  112110. var babylonjs_1 = __webpack_require__(0);
  112111. var texture_1 = __webpack_require__(12);
  112112. /**
  112113. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  112114. * The APIs in all labs-related classes and configuration might change.
  112115. * Once stable, lab features will be moved to the publis API and configuration object.
  112116. */
  112117. var ViewerLabs = /** @class */ (function () {
  112118. function ViewerLabs(_scene) {
  112119. this._scene = _scene;
  112120. this.environment = {
  112121. //irradiance
  112122. irradiancePolynomialCoefficients: {
  112123. x: new babylonjs_1.Vector3(0, 0, 0),
  112124. y: new babylonjs_1.Vector3(0, 0, 0),
  112125. z: new babylonjs_1.Vector3(0, 0, 0),
  112126. xx: new babylonjs_1.Vector3(0, 0, 0),
  112127. yy: new babylonjs_1.Vector3(0, 0, 0),
  112128. zz: new babylonjs_1.Vector3(0, 0, 0),
  112129. yz: new babylonjs_1.Vector3(0, 0, 0),
  112130. zx: new babylonjs_1.Vector3(0, 0, 0),
  112131. xy: new babylonjs_1.Vector3(0, 0, 0)
  112132. },
  112133. textureIntensityScale: 1.0
  112134. };
  112135. }
  112136. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  112137. var _this = this;
  112138. //@! todo: should loadEnvironment cancel any currently loading environments?
  112139. if (data instanceof ArrayBuffer) {
  112140. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  112141. if (onSuccess)
  112142. onSuccess(this.environment);
  112143. }
  112144. else if (typeof data === 'string') {
  112145. var url = this.getAssetUrl(data);
  112146. this._scene._loadFile(url, function (arrayBuffer) {
  112147. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  112148. if (onSuccess)
  112149. onSuccess(_this.environment);
  112150. }, function (progressEvent) { if (onProgress)
  112151. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  112152. if (onError) {
  112153. onError(e);
  112154. }
  112155. });
  112156. }
  112157. else {
  112158. //data assumed to be PBREnvironment object
  112159. this.environment = data;
  112160. if (onSuccess)
  112161. onSuccess(data);
  112162. }
  112163. };
  112164. /**
  112165. * Applies an `EnvironmentMapConfiguration` to the scene
  112166. * @param environmentMapConfiguration Environment map configuration to apply
  112167. */
  112168. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  112169. if (!this.environment)
  112170. return;
  112171. //set orientation
  112172. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  112173. // Add env texture to the scene.
  112174. if (this.environment.specularTexture) {
  112175. // IE crashes when disposing the old texture and setting a new one
  112176. if (!this._scene.environmentTexture) {
  112177. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  112178. }
  112179. if (this._scene.environmentTexture) {
  112180. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  112181. this._scene.environmentTexture.invertZ = true;
  112182. this._scene.environmentTexture.lodLevelInAlpha = true;
  112183. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  112184. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  112185. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  112186. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  112187. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  112188. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  112189. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  112190. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  112191. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  112192. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  112193. this._scene.environmentTexture.sphericalPolynomial = poly;
  112194. //set orientation
  112195. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  112196. }
  112197. }
  112198. };
  112199. /**
  112200. * Get an environment asset url by using the configuration if the path is not absolute.
  112201. * @param url Asset url
  112202. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  112203. */
  112204. ViewerLabs.prototype.getAssetUrl = function (url) {
  112205. var returnUrl = url;
  112206. if (url && url.toLowerCase().indexOf("//") === -1) {
  112207. if (!this.assetsRootURL) {
  112208. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  112209. return url;
  112210. }
  112211. returnUrl = this.assetsRootURL + returnUrl;
  112212. }
  112213. return returnUrl;
  112214. };
  112215. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  112216. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  112217. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  112218. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  112219. axis.normalize();
  112220. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  112221. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  112222. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  112223. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  112224. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  112225. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  112226. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  112227. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  112228. shadowLight.setDirectionToTarget(target);
  112229. };
  112230. return ViewerLabs;
  112231. }());
  112232. exports.ViewerLabs = ViewerLabs;
  112233. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixFQUFFLEVBQUUsSUFBSS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xhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  112234. /***/ }),
  112235. /* 25 */
  112236. /***/ (function(module, exports, __webpack_require__) {
  112237. "use strict";
  112238. Object.defineProperty(exports, "__esModule", { value: true });
  112239. var babylonjs_1 = __webpack_require__(0);
  112240. var texture_1 = __webpack_require__(12);
  112241. /**
  112242. * A static class proving methods to aid parsing Spectre environment files
  112243. */
  112244. var EnvironmentDeserializer = /** @class */ (function () {
  112245. function EnvironmentDeserializer() {
  112246. }
  112247. /**
  112248. * Parses an arraybuffer into a new PBREnvironment object
  112249. * @param arrayBuffer The arraybuffer of the Spectre environment file
  112250. * @return a PBREnvironment object
  112251. */
  112252. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  112253. var environment = {
  112254. //irradiance
  112255. irradiancePolynomialCoefficients: {
  112256. x: new babylonjs_1.Vector3(0, 0, 0),
  112257. y: new babylonjs_1.Vector3(0, 0, 0),
  112258. z: new babylonjs_1.Vector3(0, 0, 0),
  112259. xx: new babylonjs_1.Vector3(0, 0, 0),
  112260. yy: new babylonjs_1.Vector3(0, 0, 0),
  112261. zz: new babylonjs_1.Vector3(0, 0, 0),
  112262. yz: new babylonjs_1.Vector3(0, 0, 0),
  112263. zx: new babylonjs_1.Vector3(0, 0, 0),
  112264. xy: new babylonjs_1.Vector3(0, 0, 0)
  112265. },
  112266. //specular
  112267. textureIntensityScale: 1.0,
  112268. };
  112269. //read .env
  112270. var littleEndian = false;
  112271. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  112272. var dataView = new DataView(arrayBuffer);
  112273. var pos = 0;
  112274. for (var i = 0; i < magicBytes.length; i++) {
  112275. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  112276. babylonjs_1.Tools.Error('Not a Spectre environment map');
  112277. }
  112278. }
  112279. var version = dataView.getUint16(pos, littleEndian);
  112280. pos += 2;
  112281. if (version !== 1) {
  112282. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  112283. }
  112284. //read json descriptor - collect characters up to null terminator
  112285. var descriptorString = '';
  112286. var charCode = 0x00;
  112287. while ((charCode = dataView.getUint8(pos++))) {
  112288. descriptorString += String.fromCharCode(charCode);
  112289. }
  112290. var descriptor = JSON.parse(descriptorString);
  112291. var payloadPos = pos;
  112292. //irradiance
  112293. switch (descriptor.irradiance.type) {
  112294. case 'irradiance_sh_coefficients_9':
  112295. //irradiance
  112296. var harmonics = descriptor.irradiance;
  112297. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  112298. //harmonics now represent radiance
  112299. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  112300. break;
  112301. default:
  112302. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  112303. }
  112304. //specular
  112305. switch (descriptor.specular.type) {
  112306. case 'cubemap_faces':
  112307. var specularDescriptor = descriptor.specular;
  112308. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  112309. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  112310. var mipmaps = specularDescriptor.mipmaps;
  112311. var imageType = specularDescriptor.imageType;
  112312. for (var l = 0; l < mipmaps.length; l++) {
  112313. var faceRanges = mipmaps[l];
  112314. specularTexture.source[l] = [];
  112315. for (var i = 0; i < 6; i++) {
  112316. var range = faceRanges[i];
  112317. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  112318. switch (imageType) {
  112319. case 'png':
  112320. //construct image element from bytes
  112321. var image = new Image();
  112322. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  112323. image.src = src;
  112324. specularTexture.source[l][i] = image;
  112325. break;
  112326. default:
  112327. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  112328. }
  112329. }
  112330. }
  112331. break;
  112332. default:
  112333. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  112334. }
  112335. return environment;
  112336. };
  112337. /**
  112338. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  112339. * L = (1/pi) * E * rho
  112340. *
  112341. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  112342. * @param harmonics Spherical harmonic coefficients (9)
  112343. */
  112344. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  112345. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  112346. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  112347. // (The pixel shader must apply albedo after texture fetches, etc).
  112348. };
  112349. /**
  112350. * Convert spherical harmonics to spherical polynomial coefficients
  112351. * @param harmonics Spherical harmonic coefficients (9)
  112352. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  112353. */
  112354. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  112355. var rPi = 1 / Math.PI;
  112356. //x
  112357. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  112358. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  112359. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  112360. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  112361. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  112362. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  112363. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  112364. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  112365. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  112366. //xx
  112367. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  112368. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  112369. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  112370. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  112371. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  112372. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  112373. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  112374. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  112375. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  112376. //yz
  112377. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  112378. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  112379. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  112380. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  112381. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  112382. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  112383. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  112384. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  112385. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  112386. };
  112387. /**
  112388. * Multiplies harmonic coefficients in place
  112389. * @param harmonics Spherical harmonic coefficients (9)
  112390. * @param scaleFactor Value to multiply by
  112391. */
  112392. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  112393. harmonics.l00[0] *= scaleFactor;
  112394. harmonics.l00[1] *= scaleFactor;
  112395. harmonics.l00[2] *= scaleFactor;
  112396. harmonics.l1_1[0] *= scaleFactor;
  112397. harmonics.l1_1[1] *= scaleFactor;
  112398. harmonics.l1_1[2] *= scaleFactor;
  112399. harmonics.l10[0] *= scaleFactor;
  112400. harmonics.l10[1] *= scaleFactor;
  112401. harmonics.l10[2] *= scaleFactor;
  112402. harmonics.l11[0] *= scaleFactor;
  112403. harmonics.l11[1] *= scaleFactor;
  112404. harmonics.l11[2] *= scaleFactor;
  112405. harmonics.l2_2[0] *= scaleFactor;
  112406. harmonics.l2_2[1] *= scaleFactor;
  112407. harmonics.l2_2[2] *= scaleFactor;
  112408. harmonics.l2_1[0] *= scaleFactor;
  112409. harmonics.l2_1[1] *= scaleFactor;
  112410. harmonics.l2_1[2] *= scaleFactor;
  112411. harmonics.l20[0] *= scaleFactor;
  112412. harmonics.l20[1] *= scaleFactor;
  112413. harmonics.l20[2] *= scaleFactor;
  112414. harmonics.l21[0] *= scaleFactor;
  112415. harmonics.l21[1] *= scaleFactor;
  112416. harmonics.l21[2] *= scaleFactor;
  112417. harmonics.l22[0] *= scaleFactor;
  112418. harmonics.l22[1] *= scaleFactor;
  112419. harmonics.l22[2] *= scaleFactor;
  112420. };
  112421. return EnvironmentDeserializer;
  112422. }());
  112423. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  112424. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDL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0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  112425. /***/ }),
  112426. /* 26 */
  112427. /***/ (function(module, exports, __webpack_require__) {
  112428. "use strict";
  112429. Object.defineProperty(exports, "__esModule", { value: true });
  112430. var extended_1 = __webpack_require__(27);
  112431. var cache = {};
  112432. /**
  112433. *
  112434. * @param name the name of the custom optimizer configuration
  112435. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  112436. */
  112437. function getCustomOptimizerByName(name, upgrade) {
  112438. if (!cache[name]) {
  112439. switch (name) {
  112440. case 'extended':
  112441. if (upgrade) {
  112442. return extended_1.extendedUpgrade;
  112443. }
  112444. else {
  112445. return extended_1.extendedDegrade;
  112446. }
  112447. }
  112448. }
  112449. return cache[name];
  112450. }
  112451. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  112452. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  112453. /***/ }),
  112454. /* 27 */
  112455. /***/ (function(module, exports, __webpack_require__) {
  112456. "use strict";
  112457. Object.defineProperty(exports, "__esModule", { value: true });
  112458. var babylonjs_1 = __webpack_require__(0);
  112459. /**
  112460. * A custom upgrade-oriented function configuration for the scene optimizer.
  112461. *
  112462. * @param viewer the viewer to optimize
  112463. */
  112464. function extendedUpgrade(sceneManager) {
  112465. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  112466. // if (!this.Scene.BackgroundHelper) {
  112467. // this.Scene.EngineScene.autoClear = false;
  112468. // this.Scene.BackgroundHelper = true;
  112469. // Would require a dedicated clear color;
  112470. // return false;
  112471. // }
  112472. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  112473. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  112474. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112475. return false;
  112476. }
  112477. if (!sceneManager.scene.postProcessesEnabled) {
  112478. sceneManager.scene.postProcessesEnabled = true;
  112479. return false;
  112480. }
  112481. if (!sceneManager.groundEnabled) {
  112482. sceneManager.groundEnabled = true;
  112483. return false;
  112484. }
  112485. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  112486. sceneManager.fxaaEnabled = true;
  112487. return false;
  112488. }
  112489. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  112490. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  112491. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  112492. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112493. return false;
  112494. }
  112495. if (!sceneManager.processShadows) {
  112496. sceneManager.processShadows = true;
  112497. return false;
  112498. }
  112499. if (defaultPipeline && !sceneManager.bloomEnabled) {
  112500. sceneManager.bloomEnabled = true;
  112501. return false;
  112502. }
  112503. if (!sceneManager.groundMirrorEnabled) {
  112504. sceneManager.groundMirrorEnabled = true;
  112505. return false;
  112506. }
  112507. return true;
  112508. }
  112509. exports.extendedUpgrade = extendedUpgrade;
  112510. /**
  112511. * A custom degrade-oriented function configuration for the scene optimizer.
  112512. *
  112513. * @param viewer the viewer to optimize
  112514. */
  112515. function extendedDegrade(sceneManager) {
  112516. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  112517. if (sceneManager.groundMirrorEnabled) {
  112518. sceneManager.groundMirrorEnabled = false;
  112519. return false;
  112520. }
  112521. if (defaultPipeline && sceneManager.bloomEnabled) {
  112522. sceneManager.bloomEnabled = false;
  112523. return false;
  112524. }
  112525. if (sceneManager.processShadows) {
  112526. sceneManager.processShadows = false;
  112527. return false;
  112528. }
  112529. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  112530. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  112531. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112532. return false;
  112533. }
  112534. if (defaultPipeline && sceneManager.fxaaEnabled) {
  112535. sceneManager.fxaaEnabled = false;
  112536. return false;
  112537. }
  112538. if (sceneManager.groundEnabled) {
  112539. sceneManager.groundEnabled = false;
  112540. return false;
  112541. }
  112542. if (sceneManager.scene.postProcessesEnabled) {
  112543. sceneManager.scene.postProcessesEnabled = false;
  112544. return false;
  112545. }
  112546. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  112547. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  112548. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  112549. return false;
  112550. }
  112551. // if (this.Scene.BackgroundHelper) {
  112552. // this.Scene.EngineScene.autoClear = true;
  112553. // this.Scene.BackgroundHelper = false;
  112554. // Would require a dedicated clear color;
  112555. // return false;
  112556. // }
  112557. return true;
  112558. }
  112559. exports.extendedDegrade = extendedDegrade;
  112560. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFDdEMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQU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oRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  112561. /***/ }),
  112562. /* 28 */
  112563. /***/ (function(module, exports, __webpack_require__) {
  112564. "use strict";
  112565. Object.defineProperty(exports, "__esModule", { value: true });
  112566. var mappers_1 = __webpack_require__(3);
  112567. var types_1 = __webpack_require__(29);
  112568. var configurationCompatibility_1 = __webpack_require__(53);
  112569. var _1 = __webpack_require__(1);
  112570. var babylonjs_1 = __webpack_require__(0);
  112571. /**
  112572. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  112573. * parse the object and return a conform ViewerConfiguration.
  112574. * It is a private member of the scene.
  112575. */
  112576. var ConfigurationLoader = /** @class */ (function () {
  112577. function ConfigurationLoader(_enableCache) {
  112578. if (_enableCache === void 0) { _enableCache = false; }
  112579. this._enableCache = _enableCache;
  112580. this._configurationCache = {};
  112581. this._loadRequests = [];
  112582. }
  112583. /**
  112584. * load a configuration object that is defined in the initial configuration provided.
  112585. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  112586. *
  112587. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  112588. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  112589. * @returns A promise that delivers the extended viewer configuration, when done.
  112590. */
  112591. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  112592. var _this = this;
  112593. if (initConfig === void 0) { initConfig = {}; }
  112594. var loadedConfig = _1.deepmerge({}, initConfig);
  112595. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  112596. if (loadedConfig.configuration) {
  112597. var mapperType_1 = "json";
  112598. return Promise.resolve().then(function () {
  112599. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  112600. // a file to load
  112601. var url = '';
  112602. if (typeof loadedConfig.configuration === "string") {
  112603. url = loadedConfig.configuration;
  112604. }
  112605. // if configuration is an object
  112606. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  112607. url = loadedConfig.configuration.url;
  112608. var type = loadedConfig.configuration.mapper;
  112609. // empty string?
  112610. if (!type) {
  112611. // load mapper type from filename / url
  112612. type = loadedConfig.configuration.url.split('.').pop();
  112613. }
  112614. mapperType_1 = type || mapperType_1;
  112615. }
  112616. return _this._loadFile(url);
  112617. }
  112618. else {
  112619. if (typeof loadedConfig.configuration === "object") {
  112620. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  112621. return loadedConfig.configuration.payload || {};
  112622. }
  112623. return {};
  112624. }
  112625. }).then(function (data) {
  112626. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  112627. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  112628. var merged = _1.deepmerge(extendedConfiguration, parsed);
  112629. configurationCompatibility_1.processConfigurationCompatibility(merged);
  112630. if (callback)
  112631. callback(merged);
  112632. return merged;
  112633. });
  112634. }
  112635. else {
  112636. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  112637. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  112638. if (callback)
  112639. callback(loadedConfig);
  112640. return Promise.resolve(loadedConfig);
  112641. }
  112642. };
  112643. /**
  112644. * Dispose the configuration loader. This will cancel file requests, if active.
  112645. */
  112646. ConfigurationLoader.prototype.dispose = function () {
  112647. this._loadRequests.forEach(function (request) {
  112648. request.abort();
  112649. });
  112650. this._loadRequests.length = 0;
  112651. };
  112652. ConfigurationLoader.prototype._loadFile = function (url) {
  112653. var _this = this;
  112654. var cacheReference = this._configurationCache;
  112655. if (this._enableCache && cacheReference[url]) {
  112656. return Promise.resolve(cacheReference[url]);
  112657. }
  112658. return new Promise(function (resolve, reject) {
  112659. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  112660. var idx = _this._loadRequests.indexOf(fileRequest);
  112661. if (idx !== -1)
  112662. _this._loadRequests.splice(idx, 1);
  112663. if (_this._enableCache)
  112664. cacheReference[url] = result;
  112665. resolve(result);
  112666. }, undefined, undefined, false, function (request, error) {
  112667. var idx = _this._loadRequests.indexOf(fileRequest);
  112668. if (idx !== -1)
  112669. _this._loadRequests.splice(idx, 1);
  112670. reject(error);
  112671. });
  112672. _this._loadRequests.push(fileRequest);
  112673. });
  112674. };
  112675. return ConfigurationLoader;
  112676. }());
  112677. exports.ConfigurationLoader = ConfigurationLoader;
  112678. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNk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683. Object.defineProperty(exports, "__esModule", { value: true });
  112684. var minimal_1 = __webpack_require__(30);
  112685. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  112686. var default_1 = __webpack_require__(49);
  112687. exports.defaultConfiguration = default_1.defaultConfiguration;
  112688. var extended_1 = __webpack_require__(50);
  112689. var shadowLight_1 = __webpack_require__(51);
  112690. var environmentMap_1 = __webpack_require__(52);
  112691. var _1 = __webpack_require__(1);
  112692. /**
  112693. * Get the configuration type you need to use as the base for your viewer.
  112694. * The types can either be a single string, or comma separated types that will extend each other. for example:
  112695. *
  112696. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  112697. *
  112698. * @param types a comma-separated string of the type(s) or configuration to load.
  112699. */
  112700. var getConfigurationType = function (types) {
  112701. var config = {};
  112702. var typesSeparated = types.split(",");
  112703. typesSeparated.forEach(function (type) {
  112704. switch (type.trim()) {
  112705. case 'environmentMap':
  112706. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  112707. break;
  112708. case 'shadowDirectionalLight':
  112709. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  112710. break;
  112711. case 'shadowSpotLight':
  112712. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  112713. break;
  112714. case 'extended':
  112715. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  112716. break;
  112717. case 'minimal':
  112718. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  112719. break;
  112720. case 'none':
  112721. break;
  112722. case 'default':
  112723. default:
  112724. config = _1.deepmerge(config, default_1.defaultConfiguration);
  112725. break;
  112726. }
  112727. if (config.extends) {
  112728. config = _1.deepmerge(config, getConfigurationType(config.extends));
  112729. }
  112730. });
  112731. return config;
  112732. };
  112733. exports.getConfigurationType = getConfigurationType;
  112734. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8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FDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  112735. /***/ }),
  112736. /* 30 */
  112737. /***/ (function(module, exports, __webpack_require__) {
  112738. "use strict";
  112739. Object.defineProperty(exports, "__esModule", { value: true });
  112740. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  112741. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  112742. /**
  112743. * The minimal configuration needed to make the viewer work.
  112744. * Some functionalities might not work correctly (like fill-screen)
  112745. */
  112746. exports.minimalConfiguration = {
  112747. version: "0.1",
  112748. templates: {
  112749. main: {
  112750. html: babylonjs_viewer_assets_1.defaultTemplate
  112751. },
  112752. fillContainer: {
  112753. html: babylonjs_viewer_assets_1.fillContainer,
  112754. params: {
  112755. disable: false
  112756. }
  112757. },
  112758. loadingScreen: {
  112759. html: babylonjs_viewer_assets_1.loadingScreen,
  112760. params: {
  112761. backgroundColor: "#000000",
  112762. loadingImage: babylonjs_viewer_assets_2.loading
  112763. }
  112764. },
  112765. viewer: {
  112766. html: babylonjs_viewer_assets_1.defaultViewer,
  112767. },
  112768. overlay: {
  112769. html: babylonjs_viewer_assets_1.overlay,
  112770. params: {
  112771. closeImage: babylonjs_viewer_assets_2.close,
  112772. closeText: 'Close'
  112773. }
  112774. },
  112775. error: {
  112776. html: babylonjs_viewer_assets_1.error
  112777. }
  112778. },
  112779. engine: {
  112780. antialiasing: true
  112781. }
  112782. };
  112783. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  112784. /***/ }),
  112785. /* 31 */
  112786. /***/ (function(module, exports, __webpack_require__) {
  112787. "use strict";
  112788. Object.defineProperty(exports, "__esModule", { value: true });
  112789. exports.babylonFont = __webpack_require__(32);
  112790. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  112791. /***/ }),
  112792. /* 32 */
  112793. /***/ (function(module, exports) {
  112794. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABMwAA8AAAAAIYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp+FVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAAB7AAAAvq1MrYZjdnQgAAAEJAAAACAAAAAqCdkJr2ZwZ20AAAREAAAA8AAAAVn8nuaOZ2FzcAAABTQAAAAMAAAADAAIABtnbHlmAAAFQAAAB1kAAAoyCcJmr2hlYWQAAAycAAAAMgAAADb+XTcFaGhlYQAADNAAAAAVAAAAJBABCAZobXR4AAAM6AAAACcAAAAuErQDvGxvY2EAAA0QAAAAJgAAACYPBAyHbWF4cAAADTgAAAAcAAAAIACLANFuYW1lAAANVAAABTwAAAvzLvOWdHBvc3QAABKQAAAAEwAAACD/UQB3cHJlcAAAEqQAAACJAAAA03i98g542mNgZi9lnMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vaRxgPoRkAKtjgfAUGBgAs1UHMgB42hXJUxQYBgAEwclf2q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xqYh2QDOKekV1KvGpK0M8ZBZuCutU08i/RnQdwldRZzdnSHViOKo+tEThmhVRdXa2GpC+YpyXiWw+BfdbWkcwo2CZwHVK92Xlu/g5mfJzNQNIs11SmBdXHNap8paieQTUVzly6sPdrkhM6B/nnYcUJHvi6L2NsY/m9t5+wpMU1AZmiOHXUumc3qogw670/Hda03A5hJm4sjf91bgPxtrilIaspc01v5rNkTh6ZKUl+0X9usWlzRm1WRJUbbdbPjQc2c3uR/ntH2q1b4zszZuzdE+Srj/GC8I6p029v5F1nQBHfnP+HU/1rLQ99k+iofugfv0avRZvR+9G70NqxXDjEVYH8H9B5R3Yo2yuD74JuQUTd3QNNAvJiN+BtTGIWpeNpjYGYAg/9+DOUMWAAAKSoByAB42tvAoM2wiZGTSZtxExeI3M7Vmhtqq8rAob2dOzXYQU8GxOKJ8LDQkASxeJ3NteWFQSw+HRUZER4Qi19OQpiPA8QS4OPhZGcBsQTBAMQS2jChIMAAyGLYzgg3mgluNDPcaBa40axwo9nkJKFGs8ON5oAbzQk3epMwI7v2BgYF19pMCRcAxAEoGgAAAA=="
  112795. /***/ }),
  112796. /* 33 */
  112797. /***/ (function(module, exports, __webpack_require__) {
  112798. "use strict";
  112799. Object.defineProperty(exports, "__esModule", { value: true });
  112800. exports.babylonLogo = __webpack_require__(34);
  112801. exports.close = __webpack_require__(35);
  112802. exports.fullscreen = __webpack_require__(36);
  112803. exports.helpCircle = __webpack_require__(37);
  112804. exports.loading = __webpack_require__(38);
  112805. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  112806. /***/ }),
  112807. /* 34 */
  112808. /***/ (function(module, exports) {
  112809. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwAAAJiCVbiusw7Xnm/dLVEbAAB4lpgNAAAAjE2VdbCu4/nWfSdqAwAATxKzAQAAgCF7vCbc862HS9QGAAA2iNkAAADAUNRZR+sqwvVYidoAAEASMRsAAADon4fPt66an0+MZXJEbQAAmDgxGwAAAOhSlR9XhR8bCw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AA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  112810. /***/ }),
  112811. /* 35 */
  112812. /***/ (function(module, exports) {
  112813. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  112814. /***/ }),
  112815. /* 36 */
  112816. /***/ (function(module, exports) {
  112817. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  112818. /***/ }),
  112819. /* 37 */
  112820. /***/ (function(module, exports) {
  112821. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  112822. /***/ }),
  112823. /* 38 */
  112824. /***/ (function(module, exports) {
  112825. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZD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nuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/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=="
  112826. /***/ }),
  112827. /* 39 */
  112828. /***/ (function(module, exports, __webpack_require__) {
  112829. "use strict";
  112830. Object.defineProperty(exports, "__esModule", { value: true });
  112831. exports.defaultTemplate = __webpack_require__(40);
  112832. exports.defaultViewer = __webpack_require__(41);
  112833. exports.error = __webpack_require__(42);
  112834. exports.fillContainer = __webpack_require__(43);
  112835. exports.help = __webpack_require__(44);
  112836. exports.loadingScreen = __webpack_require__(45);
  112837. exports.navbar = __webpack_require__(46);
  112838. exports.overlay = __webpack_require__(47);
  112839. exports.share = __webpack_require__(48);
  112840. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  112841. /***/ }),
  112842. /* 40 */
  112843. /***/ (function(module, exports) {
  112844. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  112845. /***/ }),
  112846. /* 41 */
  112847. /***/ (function(module, exports) {
  112848. module.exports = "<style>viewer{position:relative;overflow:hidden;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 touch-action=none> </canvas> <nav-bar></nav-bar>";
  112849. /***/ }),
  112850. /* 42 */
  112851. /***/ (function(module, exports) {
  112852. module.exports = "Error loading the model";
  112853. /***/ }),
  112854. /* 43 */
  112855. /***/ (function(module, exports) {
  112856. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  112857. /***/ }),
  112858. /* 44 */
  112859. /***/ (function(module, exports) {
  112860. module.exports = "HELP";
  112861. /***/ }),
  112862. /* 45 */
  112863. /***/ (function(module, exports) {
  112864. 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 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s 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}}>";
  112865. /***/ }),
  112866. /* 46 */
  112867. /***/ (function(module, exports) {
  112868. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.hd-icon:after{font-size:16px;content:\"\\F765\"}.sd-icon:after{font-size:16px;content:\"\\F766\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#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=\"nav-container navbar-control\"> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container types-button animation-buttons\"> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container label-option-button animation-buttons\" data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control> <button class=\"play-pause play-pause-button\"> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=\"flex-container speed-button\"> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=\"flex-container speed-option-button\" data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHdButton}} <button class=\"hd-button hd-button\" title={{text.hdButton}}> {{#if hdEnabled}} <span class=\"icon sd-icon\"></span> {{else}} <span class=\"icon hd-icon\"></span> {{/if}} </button> {{/unless}} {{#unless hideHelp}} <button class=\"help help-button\" title={{text.helpButton}}> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=\"fullscreen fullscreen-button\" title={{text.fullscreenButton}}> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  112869. /***/ }),
  112870. /* 47 */
  112871. /***/ (function(module, exports) {
  112872. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:none;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>";
  112873. /***/ }),
  112874. /* 48 */
  112875. /***/ (function(module, exports) {
  112876. module.exports = "SHARE";
  112877. /***/ }),
  112878. /* 49 */
  112879. /***/ (function(module, exports, __webpack_require__) {
  112880. "use strict";
  112881. Object.defineProperty(exports, "__esModule", { value: true });
  112882. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  112883. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  112884. var images = __webpack_require__(2);
  112885. /**
  112886. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  112887. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  112888. */
  112889. exports.defaultConfiguration = {
  112890. version: "3.2.0-alpha4",
  112891. templates: {
  112892. main: {
  112893. html: babylonjs_viewer_assets_1.defaultTemplate,
  112894. params: {
  112895. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  112896. noEscape: true
  112897. }
  112898. },
  112899. fillContainer: {
  112900. html: babylonjs_viewer_assets_1.fillContainer,
  112901. params: {
  112902. disable: false
  112903. }
  112904. },
  112905. loadingScreen: {
  112906. html: babylonjs_viewer_assets_1.loadingScreen,
  112907. params: {
  112908. backgroundColor: "#000000",
  112909. loadingImage: images.loading
  112910. }
  112911. },
  112912. viewer: {
  112913. html: babylonjs_viewer_assets_1.defaultViewer,
  112914. params: {
  112915. enableDragAndDrop: false
  112916. }
  112917. },
  112918. navBar: {
  112919. html: babylonjs_viewer_assets_1.navbar,
  112920. params: {
  112921. speedList: {
  112922. "0.5x": "0.5",
  112923. "1.0x": "1.0",
  112924. "1.5x": "1.5",
  112925. "2.0x": "2.0",
  112926. },
  112927. logoImage: images.babylonLogo,
  112928. logoText: 'BabylonJS',
  112929. logoLink: 'https://babylonjs.com',
  112930. hideHelp: true,
  112931. hideHdButton: true,
  112932. disableOnFullscreen: false,
  112933. text: {
  112934. hdButton: "Toggle HD",
  112935. fullscreenButton: "Fullscreen",
  112936. helpButton: "Help"
  112937. }
  112938. },
  112939. events: {
  112940. pointerdown: {
  112941. '.navbar-control': true,
  112942. '.help-button': true
  112943. },
  112944. input: {
  112945. '.progress-wrapper': true
  112946. },
  112947. pointerup: {
  112948. '.progress-wrapper': true
  112949. }
  112950. }
  112951. },
  112952. overlay: {
  112953. html: babylonjs_viewer_assets_1.overlay,
  112954. params: {
  112955. closeImage: images.close,
  112956. closeText: 'Close'
  112957. }
  112958. },
  112959. help: {
  112960. html: babylonjs_viewer_assets_1.help
  112961. },
  112962. share: {
  112963. html: babylonjs_viewer_assets_1.share
  112964. },
  112965. error: {
  112966. html: babylonjs_viewer_assets_1.error
  112967. }
  112968. },
  112969. camera: {
  112970. behaviors: {
  112971. autoRotate: {
  112972. type: 0
  112973. },
  112974. framing: {
  112975. type: 2,
  112976. zoomOnBoundingInfo: true,
  112977. zoomStopsAnimation: false
  112978. },
  112979. bouncing: {
  112980. type: 1
  112981. }
  112982. }
  112983. },
  112984. skybox: {},
  112985. ground: {
  112986. receiveShadows: true
  112987. },
  112988. engine: {
  112989. antialiasing: true
  112990. },
  112991. scene: {}
  112992. };
  112993. //# sourceMappingURL=data:application/json;base64,e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wsSUFBSSxFQUFFLENBQUM7Z0JBQ1Asa0JBQWtCLEVBQUUsSUFBSTtnQkFDeEIsa0JBQWtCLEVBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  112994. /***/ }),
  112995. /* 50 */
  112996. /***/ (function(module, exports, __webpack_require__) {
  112997. "use strict";
  112998. Object.defineProperty(exports, "__esModule", { value: true });
  112999. var babylonjs_1 = __webpack_require__(0);
  113000. /**
  113001. * The viewer's "extended" configuration.
  113002. * This configuration defines specific obejcts and parameters that we think make any model look good.
  113003. */
  113004. exports.extendedConfiguration = {
  113005. version: "3.2.0",
  113006. extends: "default",
  113007. camera: {
  113008. exposure: 3.034578,
  113009. fov: 0.7853981633974483,
  113010. contrast: 1.6,
  113011. toneMappingEnabled: true,
  113012. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  113013. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  113014. behaviors: {
  113015. framing: {
  113016. type: 2,
  113017. mode: 0,
  113018. positionScale: 0.5,
  113019. defaultElevation: 0.2617993877991494,
  113020. elevationReturnWaitTime: 3000,
  113021. elevationReturnTime: 2000,
  113022. framingTime: 500,
  113023. zoomStopsAnimation: false,
  113024. radiusScale: 0.866
  113025. },
  113026. autoRotate: {
  113027. type: 0,
  113028. idleRotationWaitTime: 4000,
  113029. idleRotationSpeed: 0.17453292519943295,
  113030. idleRotationSpinupTime: 2500,
  113031. zoomStopsAnimation: false
  113032. },
  113033. bouncing: {
  113034. type: 1,
  113035. lowerRadiusTransitionRange: 0.05,
  113036. upperRadiusTransitionRange: -0.2
  113037. }
  113038. },
  113039. upperRadiusLimit: 5,
  113040. lowerRadiusLimit: 0.5,
  113041. frameOnModelLoad: true,
  113042. framingElevation: 0.2617993877991494,
  113043. framingRotation: 1.5707963267948966,
  113044. radius: 2,
  113045. alpha: 1.5708,
  113046. beta: Math.PI * 0.5 - 0.2618,
  113047. wheelPrecision: 300,
  113048. minZ: 0.1,
  113049. maxZ: 50,
  113050. fovMode: 0,
  113051. pinchPrecision: 1500,
  113052. panningSensibility: 3000
  113053. },
  113054. lights: {
  113055. light0: {
  113056. type: 0,
  113057. frustumEdgeFalloff: 0,
  113058. intensity: 7,
  113059. intensityMode: 0,
  113060. radius: 0.6,
  113061. range: 0.6,
  113062. spotAngle: 60,
  113063. diffuse: {
  113064. r: 1,
  113065. g: 1,
  113066. b: 1
  113067. },
  113068. position: {
  113069. x: -2,
  113070. y: 2.5,
  113071. z: 2
  113072. },
  113073. target: {
  113074. x: 0,
  113075. y: 0,
  113076. z: 0
  113077. },
  113078. enabled: true,
  113079. shadowEnabled: true,
  113080. shadowBufferSize: 512,
  113081. shadowMinZ: 1,
  113082. shadowMaxZ: 10,
  113083. shadowFieldOfView: 60,
  113084. shadowFrustumSize: 2,
  113085. shadowConfig: {
  113086. useBlurCloseExponentialShadowMap: true,
  113087. useKernelBlur: true,
  113088. blurScale: 1.0,
  113089. bias: 0.001,
  113090. depthScale: 50 * (10 - 1),
  113091. frustumEdgeFalloff: 0
  113092. }
  113093. },
  113094. light1: {
  113095. type: 0,
  113096. frustumEdgeFalloff: 0,
  113097. intensity: 7,
  113098. intensityMode: 0,
  113099. radius: 0.4,
  113100. range: 0.4,
  113101. spotAngle: 57,
  113102. diffuse: {
  113103. r: 1,
  113104. g: 1,
  113105. b: 1
  113106. },
  113107. position: {
  113108. x: 4,
  113109. y: 3,
  113110. z: -0.5
  113111. },
  113112. target: {
  113113. x: 0,
  113114. y: 0,
  113115. z: 0
  113116. },
  113117. enabled: true,
  113118. shadowEnabled: false,
  113119. shadowBufferSize: 512,
  113120. shadowMinZ: 0.2,
  113121. shadowMaxZ: 10,
  113122. shadowFieldOfView: 28,
  113123. shadowFrustumSize: 2
  113124. },
  113125. light2: {
  113126. type: 0,
  113127. frustumEdgeFalloff: 0,
  113128. intensity: 1,
  113129. intensityMode: 0,
  113130. radius: 0.5,
  113131. range: 0.5,
  113132. spotAngle: 42.85,
  113133. diffuse: {
  113134. r: 0.8,
  113135. g: 0.8,
  113136. b: 0.8
  113137. },
  113138. position: {
  113139. x: -1,
  113140. y: 3,
  113141. z: -3
  113142. },
  113143. target: {
  113144. x: 0,
  113145. y: 0,
  113146. z: 0
  113147. },
  113148. enabled: true,
  113149. shadowEnabled: false,
  113150. shadowBufferSize: 512,
  113151. shadowMinZ: 0.2,
  113152. shadowMaxZ: 10,
  113153. shadowFieldOfView: 45,
  113154. shadowFrustumSize: 2
  113155. }
  113156. },
  113157. ground: {
  113158. shadowLevel: 0.9,
  113159. texture: "Ground_2.0-1024.png",
  113160. material: {
  113161. primaryColorHighlightLevel: 0.035,
  113162. primaryColorShadowLevel: 0,
  113163. enableNoise: true,
  113164. useRGBColor: false,
  113165. maxSimultaneousLights: 1,
  113166. diffuseTexture: {
  113167. gammaSpace: true
  113168. }
  113169. },
  113170. opacity: 1,
  113171. mirror: false,
  113172. receiveShadows: true,
  113173. size: 5
  113174. },
  113175. skybox: {
  113176. scale: 11,
  113177. cubeTexture: {
  113178. url: "Skybox_2.0-256.dds"
  113179. },
  113180. material: {
  113181. primaryColorHighlightLevel: 0.03,
  113182. primaryColorShadowLevel: 0.03,
  113183. enableNoise: true,
  113184. useRGBColor: false,
  113185. reflectionTexture: {
  113186. gammaSpace: true
  113187. }
  113188. }
  113189. },
  113190. engine: {
  113191. renderInBackground: true
  113192. },
  113193. scene: {
  113194. flags: {
  113195. shadowsEnabled: true,
  113196. particlesEnabled: false,
  113197. collisionsEnabled: false,
  113198. lightsEnabled: true,
  113199. texturesEnabled: true,
  113200. lensFlaresEnabled: false,
  113201. proceduralTexturesEnabled: false,
  113202. renderTargetsEnabled: true,
  113203. spritesEnabled: false,
  113204. skeletonsEnabled: true,
  113205. audioEnabled: false,
  113206. },
  113207. defaultMaterial: {
  113208. materialType: 'pbr',
  113209. reflectivityColor: {
  113210. r: 0.1,
  113211. g: 0.1,
  113212. b: 0.1
  113213. },
  113214. microSurface: 0.6
  113215. },
  113216. clearColor: {
  113217. r: 0.9,
  113218. g: 0.9,
  113219. b: 0.9,
  113220. a: 1.0
  113221. },
  113222. imageProcessingConfiguration: {
  113223. vignetteCentreX: 0,
  113224. vignetteCentreY: 0,
  113225. vignetteColor: {
  113226. r: 0.086,
  113227. g: 0.184,
  113228. b: 0.259,
  113229. a: 1
  113230. },
  113231. vignetteWeight: 0.855,
  113232. vignetteStretch: 0.5,
  113233. vignetteBlendMode: 0,
  113234. vignetteCameraFov: 0.7853981633974483,
  113235. isEnabled: true,
  113236. colorCurves: {
  113237. shadowsHue: 0,
  113238. shadowsDensity: 0,
  113239. shadowsSaturation: 0,
  113240. shadowsExposure: 0,
  113241. midtonesHue: 0,
  113242. midtonesDensity: 0,
  113243. midtonesExposure: 0,
  113244. midtonesSaturation: 0,
  113245. highlightsHue: 0,
  113246. highlightsDensity: 0,
  113247. highlightsExposure: 0,
  113248. highlightsSaturation: 0
  113249. }
  113250. },
  113251. mainColor: {
  113252. r: 0.8823529411764706,
  113253. g: 0.8823529411764706,
  113254. b: 0.8823529411764706
  113255. }
  113256. },
  113257. loaderPlugins: {
  113258. extendedMaterial: true,
  113259. applyMaterialConfig: true,
  113260. msftLod: true,
  113261. telemetry: true
  113262. },
  113263. model: {
  113264. rotationOffsetAxis: {
  113265. x: 0,
  113266. y: -1,
  113267. z: 0
  113268. },
  113269. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  113270. material: {
  113271. directEnabled: true,
  113272. directIntensity: 0.884,
  113273. emissiveIntensity: 1.04,
  113274. environmentIntensity: 0.6
  113275. },
  113276. entryAnimation: {
  113277. scaling: {
  113278. x: 0,
  113279. y: 0,
  113280. z: 0
  113281. },
  113282. time: 0.5,
  113283. easingFunction: 4,
  113284. easingMode: 1
  113285. },
  113286. exitAnimation: {
  113287. scaling: {
  113288. x: 0,
  113289. y: 0,
  113290. z: 0
  113291. },
  113292. time: 0.5,
  113293. easingFunction: 4,
  113294. easingMode: 1
  113295. },
  113296. normalize: true,
  113297. castShadow: true,
  113298. receiveShadows: true
  113299. },
  113300. lab: {
  113301. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  113302. environmentMap: {
  113303. texture: "EnvMap_2.0-256.env",
  113304. rotationY: 3,
  113305. tintLevel: 0.4
  113306. },
  113307. defaultRenderingPipelines: {
  113308. bloomEnabled: true,
  113309. bloomThreshold: 1.0,
  113310. fxaaEnabled: true,
  113311. bloomWeight: 0.05
  113312. }
  113313. }
  113314. };
  113315. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUUsSUFBSTtRQUN4QixjQUFjLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxDQUFDLEVBQUUsR0FBRyxDQUFDO1FBQ2hELGNBQWMsRUFBRSxDQUFDLGtCQUFrQixHQUFHLElBQUksQ0FBQyx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NqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  113316. /***/ }),
  113317. /* 51 */
  113318. /***/ (function(module, exports, __webpack_require__) {
  113319. "use strict";
  113320. Object.defineProperty(exports, "__esModule", { value: true });
  113321. /**
  113322. * Defines a default directional shadow light for normalized objects (!)
  113323. */
  113324. exports.shadowDirectionalLightConfiguration = {
  113325. model: {
  113326. receiveShadows: true,
  113327. castShadow: true
  113328. },
  113329. ground: {
  113330. receiveShadows: true
  113331. },
  113332. lights: {
  113333. shadowDirectionalLight: {
  113334. type: 1,
  113335. shadowEnabled: true,
  113336. target: { x: 0, y: 0, z: 0.5 },
  113337. position: { x: 1.49, y: 2.39, z: -1.33 },
  113338. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  113339. intensity: 4.887,
  113340. intensityMode: 0,
  113341. shadowBufferSize: 1024,
  113342. shadowFrustumSize: 6.0,
  113343. shadowFieldOfView: 50.977,
  113344. shadowMinZ: 0.1,
  113345. shadowMaxZ: 10.0,
  113346. shadowConfig: {
  113347. blurKernel: 32,
  113348. useBlurCloseExponentialShadowMap: true
  113349. }
  113350. }
  113351. }
  113352. };
  113353. /**
  113354. * Defines a default shadow-enabled spot light for normalized objects.
  113355. */
  113356. exports.shadowSpotlLightConfiguration = {
  113357. model: {
  113358. receiveShadows: true,
  113359. castShadow: true
  113360. },
  113361. ground: {
  113362. receiveShadows: true
  113363. },
  113364. lights: {
  113365. shadowSpotLight: {
  113366. type: 2,
  113367. intensity: 2,
  113368. shadowEnabled: true,
  113369. target: { x: 0, y: 0, z: 0.5 },
  113370. position: { x: 0, y: 3.5, z: 3.7 },
  113371. angle: 1,
  113372. shadowOrthoScale: 0.5,
  113373. shadowBufferSize: 1024,
  113374. shadowMinZ: 0.1,
  113375. shadowMaxZ: 50.0,
  113376. shadowConfig: {
  113377. frustumEdgeFalloff: 0.5,
  113378. blurKernel: 32,
  113379. useBlurExponentialShadowMap: true
  113380. }
  113381. }
  113382. }
  113383. };
  113384. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUUsSUFBSSxFQUFFLENBQUMsRUFBRSxDQUFDLElBQUksRUFBRTtZQUN4QyxPQUFPLEVBQUUsRUFBRSxDQUFDLEVBQUUsS0FBSyxFQUFFLENBQUMsRUFBRSxLQUFLLEVBQUUsQ0FBQyxFQUFFLEtBQUssRUFBRTtZQUN6QyxTQUFTLEVBQUUsS0FBSztZQUNoQixhQUFhLEVBQUUsQ0FBQztZQUNoQixnQkFBZ0IsRUFBRSxJQUFJO1l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DQUFBIn0=
  113385. /***/ }),
  113386. /* 52 */
  113387. /***/ (function(module, exports, __webpack_require__) {
  113388. "use strict";
  113389. Object.defineProperty(exports, "__esModule", { value: true });
  113390. /**
  113391. * Lab-oriented default .env support
  113392. */
  113393. exports.environmentMapConfiguration = {
  113394. lab: {
  113395. assetsRootURL: '/assets/environment/',
  113396. environmentMap: {
  113397. texture: 'EnvMap_2.0-256.env',
  113398. rotationY: 0,
  113399. tintLevel: 0.4
  113400. }
  113401. }
  113402. };
  113403. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  113404. /***/ }),
  113405. /* 53 */
  113406. /***/ (function(module, exports, __webpack_require__) {
  113407. "use strict";
  113408. Object.defineProperty(exports, "__esModule", { value: true });
  113409. var configuration_1 = __webpack_require__(11);
  113410. /**
  113411. * This function will make sure the configuration file is taking deprecated fields into account
  113412. * and is setting them to the correct keys and values.
  113413. *
  113414. * @param configuration The configuration to process. Mutable!
  113415. */
  113416. function processConfigurationCompatibility(configuration) {
  113417. if (configuration.camera) {
  113418. // camera contrast -> image processing contrast
  113419. if (configuration.camera.contrast !== undefined) {
  113420. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  113421. }
  113422. // camera exposure -> image processing exposure
  113423. if (configuration.camera.exposure !== undefined) {
  113424. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  113425. }
  113426. }
  113427. if (configuration.scene) {
  113428. //glow
  113429. if (configuration.scene.glow) {
  113430. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  113431. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  113432. if (enabledProcessing !== false) {
  113433. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  113434. }
  113435. }
  113436. }
  113437. }
  113438. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  113439. function setKeyInObject(object, keys, value, shouldOverwrite) {
  113440. var keySplit = keys.split(".");
  113441. if (keySplit.length === 0)
  113442. return;
  113443. var lastKey = keySplit.pop();
  113444. if (!lastKey)
  113445. return;
  113446. var curObj = object;
  113447. keySplit.forEach(function (key) {
  113448. curObj[key] = curObj[key] || {};
  113449. curObj = curObj[key];
  113450. });
  113451. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  113452. return;
  113453. curObj[lastKey] = value;
  113454. }
  113455. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQUNILDJDQUFrRCxhQUFrQztJQUloRixJQUFJLGFBQWEsQ0FBQyxNQUFNLEVBQUU7UUFDdEIsK0NBQStDO1FBQy9DLElBQUksYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLEtBQUssU0FBU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JLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  113456. /***/ }),
  113457. /* 54 */
  113458. /***/ (function(module, exports, __webpack_require__) {
  113459. "use strict";
  113460. Object.defineProperty(exports, "__esModule", { value: true });
  113461. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  113462. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  113463. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  113464. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  113465. var applyMaterialConfig_1 = __webpack_require__(57);
  113466. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  113467. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  113468. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  113469. var babylonjs_1 = __webpack_require__(0);
  113470. var pluginCache = {};
  113471. /**
  113472. * Get a loader plugin according to its name.
  113473. * The plugin will be cached and will be reused if called for again.
  113474. *
  113475. * @param name the name of the plugin
  113476. */
  113477. function getLoaderPluginByName(name) {
  113478. if (!pluginCache[name]) {
  113479. switch (name) {
  113480. case 'telemetry':
  113481. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  113482. break;
  113483. case 'msftLod':
  113484. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  113485. break;
  113486. case 'applyMaterialConfig':
  113487. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  113488. break;
  113489. case 'extendedMaterial':
  113490. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  113491. break;
  113492. }
  113493. }
  113494. return pluginCache[name];
  113495. }
  113496. exports.getLoaderPluginByName = getLoaderPluginByName;
  113497. /**
  113498. *
  113499. */
  113500. function addLoaderPlugin(name, plugin) {
  113501. if (pluginCache[name]) {
  113502. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  113503. }
  113504. pluginCache[name] = plugin;
  113505. }
  113506. exports.addLoaderPlugin = addLoaderPlugin;
  113507. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  113508. /***/ }),
  113509. /* 55 */
  113510. /***/ (function(module, exports, __webpack_require__) {
  113511. "use strict";
  113512. Object.defineProperty(exports, "__esModule", { value: true });
  113513. var telemetryManager_1 = __webpack_require__(6);
  113514. var babylonjs_1 = __webpack_require__(0);
  113515. var TelemetryLoaderPlugin = /** @class */ (function () {
  113516. function TelemetryLoaderPlugin() {
  113517. }
  113518. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  113519. this._model = model;
  113520. this._loadStart = babylonjs_1.Tools.Now;
  113521. };
  113522. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  113523. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  113524. model: model,
  113525. loadTime: babylonjs_1.Tools.Now - this._loadStart
  113526. });
  113527. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  113528. };
  113529. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  113530. this._loadEnd = babylonjs_1.Tools.Now;
  113531. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  113532. model: this._model,
  113533. loadTime: this._loadEnd - this._loadStart
  113534. });
  113535. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  113536. };
  113537. TelemetryLoaderPlugin.prototype.onComplete = function () {
  113538. this._loadEnd = babylonjs_1.Tools.Now;
  113539. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  113540. model: this._model,
  113541. loadTime: this._loadEnd - this._loadStart
  113542. });
  113543. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  113544. };
  113545. return TelemetryLoaderPlugin;
  113546. }());
  113547. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  113548. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0FBK0U7QUFHL0U7SUFBQTtJQXVDQSxDQUFDO0lBaENVLHNDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQU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LEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  113549. /***/ }),
  113550. /* 56 */
  113551. /***/ (function(module, exports, __webpack_require__) {
  113552. "use strict";
  113553. Object.defineProperty(exports, "__esModule", { value: true });
  113554. /**
  113555. * A loder plugin to use MSFT_lod extension correctly (glTF)
  113556. */
  113557. var MSFTLodLoaderPlugin = /** @class */ (function () {
  113558. function MSFTLodLoaderPlugin() {
  113559. }
  113560. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  113561. this._model = model;
  113562. };
  113563. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  113564. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  113565. var MSFT_lod = extension;
  113566. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  113567. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  113568. }
  113569. };
  113570. return MSFTLodLoaderPlugin;
  113571. }());
  113572. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  113573. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  113574. /***/ }),
  113575. /* 57 */
  113576. /***/ (function(module, exports, __webpack_require__) {
  113577. "use strict";
  113578. Object.defineProperty(exports, "__esModule", { value: true });
  113579. /**
  113580. * Force-apply material configuration right after a material was loaded.
  113581. */
  113582. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  113583. function ApplyMaterialConfigPlugin() {
  113584. }
  113585. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  113586. this._model = model;
  113587. };
  113588. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  113589. this._model && this._model._applyModelMaterialConfiguration(material);
  113590. };
  113591. return ApplyMaterialConfigPlugin;
  113592. }());
  113593. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  113594. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  113595. /***/ }),
  113596. /* 58 */
  113597. /***/ (function(module, exports, __webpack_require__) {
  113598. "use strict";
  113599. Object.defineProperty(exports, "__esModule", { value: true });
  113600. var babylonjs_1 = __webpack_require__(0);
  113601. /**
  113602. * A (PBR) material will be extended using this function.
  113603. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  113604. */
  113605. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  113606. function ExtendedMaterialLoaderPlugin() {
  113607. }
  113608. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  113609. var material = baseMaterial;
  113610. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  113611. };
  113612. return ExtendedMaterialLoaderPlugin;
  113613. }());
  113614. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  113615. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  113616. /***/ }),
  113617. /* 59 */
  113618. /***/ (function(module, exports, __webpack_require__) {
  113619. "use strict";
  113620. Object.defineProperty(exports, "__esModule", { value: true });
  113621. var babylonjs_1 = __webpack_require__(0);
  113622. var ObservablesManager = /** @class */ (function () {
  113623. function ObservablesManager() {
  113624. this.onSceneInitObservable = new babylonjs_1.Observable();
  113625. this.onEngineInitObservable = new babylonjs_1.Observable();
  113626. this.onModelLoadedObservable = new babylonjs_1.Observable();
  113627. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  113628. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  113629. this.onModelAddedObservable = new babylonjs_1.Observable();
  113630. this.onModelRemovedObservable = new babylonjs_1.Observable();
  113631. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  113632. this.onLoaderInitObservable = new babylonjs_1.Observable();
  113633. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  113634. }
  113635. ObservablesManager.prototype.dispose = function () {
  113636. this.onSceneInitObservable.clear();
  113637. this.onEngineInitObservable.clear();
  113638. this.onModelLoadedObservable.clear();
  113639. this.onModelLoadProgressObservable.clear();
  113640. this.onModelLoadErrorObservable.clear();
  113641. this.onModelAddedObservable.clear();
  113642. this.onModelRemovedObservable.clear();
  113643. this.onViewerInitDoneObservable.clear();
  113644. this.onLoaderInitObservable.clear();
  113645. this.onFrameRenderedObservable.clear();
  113646. };
  113647. return ObservablesManager;
  113648. }());
  113649. exports.ObservablesManager = ObservablesManager;
  113650. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUc3SDtJQStDSTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ2hELElBQUksQ0FBQyw2QkFBNkIsR0FBRyxJQUFJ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UM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  113651. /***/ }),
  113652. /* 60 */
  113653. /***/ (function(module, exports, __webpack_require__) {
  113654. "use strict";
  113655. Object.defineProperty(exports, "__esModule", { value: true });
  113656. var babylonjs_1 = __webpack_require__(0);
  113657. var ConfigurationContainer = /** @class */ (function () {
  113658. function ConfigurationContainer() {
  113659. this.mainColor = babylonjs_1.Color3.White();
  113660. this.reflectionColor = babylonjs_1.Color3.White();
  113661. }
  113662. return ConfigurationContainer;
  113663. }());
  113664. exports.ConfigurationContainer = ConfigurationContainer;
  113665. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  113666. /***/ }),
  113667. /* 61 */
  113668. /***/ (function(module, exports, __webpack_require__) {
  113669. "use strict";
  113670. Object.defineProperty(exports, "__esModule", { value: true });
  113671. var babylonjs_1 = __webpack_require__(0);
  113672. var helper_1 = __webpack_require__(1);
  113673. var Handlebars = __webpack_require__(62);
  113674. var eventManager_1 = __webpack_require__(63);
  113675. var _1 = __webpack_require__(1);
  113676. /**
  113677. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  113678. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  113679. */
  113680. var TemplateManager = /** @class */ (function () {
  113681. function TemplateManager(containerElement) {
  113682. this.containerElement = containerElement;
  113683. this.templates = {};
  113684. this.onTemplateInit = new babylonjs_1.Observable();
  113685. this.onTemplateLoaded = new babylonjs_1.Observable();
  113686. this.onTemplateStateChange = new babylonjs_1.Observable();
  113687. this.onAllLoaded = new babylonjs_1.Observable();
  113688. this.onEventTriggered = new babylonjs_1.Observable();
  113689. this.eventManager = new eventManager_1.EventManager(this);
  113690. }
  113691. /**
  113692. * Initialize the template(s) for the viewer. Called bay the Viewer class
  113693. * @param templates the templates to be used to initialize the main template
  113694. */
  113695. TemplateManager.prototype.initTemplate = function (templates) {
  113696. var _this = this;
  113697. var internalInit = function (dependencyMap, name, parentTemplate) {
  113698. //init template
  113699. var template = _this.templates[name];
  113700. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  113701. return internalInit(dependencyMap[childName], childName, template);
  113702. });
  113703. // register the observers
  113704. //template.onLoaded.add(() => {
  113705. var addToParent = function () {
  113706. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  113707. template.appendTo(containingElement);
  113708. _this._checkLoadedState();
  113709. };
  113710. if (parentTemplate && !parentTemplate.parent) {
  113711. parentTemplate.onAppended.add(function () {
  113712. addToParent();
  113713. });
  113714. }
  113715. else {
  113716. addToParent();
  113717. }
  113718. //});
  113719. return template;
  113720. };
  113721. //build the html tree
  113722. return this._buildHTMLTree(templates).then(function (htmlTree) {
  113723. if (_this.templates['main']) {
  113724. internalInit(htmlTree, 'main');
  113725. }
  113726. else {
  113727. _this._checkLoadedState();
  113728. }
  113729. return;
  113730. });
  113731. };
  113732. /**
  113733. *
  113734. * This function will create a simple map with child-dependencies of the template html tree.
  113735. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  113736. * It is expected that the main template will be called main!
  113737. *
  113738. * @param templates
  113739. */
  113740. TemplateManager.prototype._buildHTMLTree = function (templates) {
  113741. var _this = this;
  113742. var promises = Object.keys(templates).map(function (name) {
  113743. // if the template was overridden
  113744. if (!templates[name])
  113745. return Promise.resolve(false);
  113746. // else - we have a template, let's do our job!
  113747. var template = new Template(name, templates[name]);
  113748. template.onLoaded.add(function () {
  113749. _this.onTemplateLoaded.notifyObservers(template);
  113750. });
  113751. template.onStateChange.add(function () {
  113752. _this.onTemplateStateChange.notifyObservers(template);
  113753. });
  113754. _this.onTemplateInit.notifyObservers(template);
  113755. // make sure the global onEventTriggered is called as well
  113756. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  113757. _this.templates[name] = template;
  113758. return template.initPromise;
  113759. });
  113760. return Promise.all(promises).then(function () {
  113761. var templateStructure = {};
  113762. // now iterate through all templates and check for children:
  113763. var buildTree = function (parentObject, name) {
  113764. _this.templates[name].isInHtmlTree = true;
  113765. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  113766. childNodes.forEach(function (element) {
  113767. parentObject[element] = {};
  113768. buildTree(parentObject[element], element);
  113769. });
  113770. };
  113771. if (_this.templates['main']) {
  113772. buildTree(templateStructure, "main");
  113773. }
  113774. return templateStructure;
  113775. });
  113776. };
  113777. /**
  113778. * Get the canvas in the template tree.
  113779. * There must be one and only one canvas inthe template.
  113780. */
  113781. TemplateManager.prototype.getCanvas = function () {
  113782. return this.containerElement.querySelector('canvas');
  113783. };
  113784. /**
  113785. * Get a specific template from the template tree
  113786. * @param name the name of the template to load
  113787. */
  113788. TemplateManager.prototype.getTemplate = function (name) {
  113789. return this.templates[name];
  113790. };
  113791. TemplateManager.prototype._checkLoadedState = function () {
  113792. var _this = this;
  113793. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  113794. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  113795. });
  113796. if (done) {
  113797. this.onAllLoaded.notifyObservers(this);
  113798. }
  113799. };
  113800. /**
  113801. * Dispose the template manager
  113802. */
  113803. TemplateManager.prototype.dispose = function () {
  113804. var _this = this;
  113805. // dispose all templates
  113806. Object.keys(this.templates).forEach(function (template) {
  113807. _this.templates[template].dispose();
  113808. });
  113809. this.templates = {};
  113810. this.eventManager.dispose();
  113811. this.onTemplateInit.clear();
  113812. this.onAllLoaded.clear();
  113813. this.onEventTriggered.clear();
  113814. this.onTemplateLoaded.clear();
  113815. this.onTemplateStateChange.clear();
  113816. };
  113817. return TemplateManager;
  113818. }());
  113819. exports.TemplateManager = TemplateManager;
  113820. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  113821. Handlebars.registerHelper('eachInMap', function (map, block) {
  113822. var out = '';
  113823. Object.keys(map).map(function (prop) {
  113824. var data = map[prop];
  113825. if (typeof data === 'object') {
  113826. data.id = data.id || prop;
  113827. out += block.fn(data);
  113828. }
  113829. else {
  113830. out += block.fn({ id: prop, value: data });
  113831. }
  113832. });
  113833. return out;
  113834. });
  113835. Handlebars.registerHelper('add', function (a, b) {
  113836. var out = a + b;
  113837. return out;
  113838. });
  113839. Handlebars.registerHelper('eq', function (a, b) {
  113840. var out = (a == b);
  113841. return out;
  113842. });
  113843. Handlebars.registerHelper('or', function (a, b) {
  113844. var out = a || b;
  113845. return out;
  113846. });
  113847. Handlebars.registerHelper('not', function (a) {
  113848. var out = !a;
  113849. return out;
  113850. });
  113851. Handlebars.registerHelper('count', function (map) {
  113852. return map.length;
  113853. });
  113854. Handlebars.registerHelper('gt', function (a, b) {
  113855. var out = a > b;
  113856. return out;
  113857. });
  113858. /**
  113859. * This class represents a single template in the viewer's template tree.
  113860. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  113861. * A template is injected using the template manager in the correct position.
  113862. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  113863. *
  113864. * For further information please refer to the documentation page, https://doc.babylonjs.com
  113865. */
  113866. var Template = /** @class */ (function () {
  113867. function Template(name, _configuration) {
  113868. var _this = this;
  113869. this.name = name;
  113870. this._configuration = _configuration;
  113871. this.onLoaded = new babylonjs_1.Observable();
  113872. this.onAppended = new babylonjs_1.Observable();
  113873. this.onStateChange = new babylonjs_1.Observable();
  113874. this.onEventTriggered = new babylonjs_1.Observable();
  113875. this.loadRequests = [];
  113876. this.isLoaded = false;
  113877. this.isShown = false;
  113878. this.isInHtmlTree = false;
  113879. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  113880. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  113881. if (htmlTemplate) {
  113882. _this._htmlTemplate = htmlTemplate;
  113883. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  113884. var config = _this._configuration.params || {};
  113885. _this._rawHtml = compiledTemplate(config);
  113886. try {
  113887. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  113888. }
  113889. catch (e) {
  113890. var test = document.createElement(_this.name);
  113891. test.innerHTML = _this._rawHtml;
  113892. _this._fragment = test;
  113893. }
  113894. _this.isLoaded = true;
  113895. _this.isShown = true;
  113896. _this.onLoaded.notifyObservers(_this);
  113897. }
  113898. return _this;
  113899. });
  113900. }
  113901. /**
  113902. * Some templates have parameters (like background color for example).
  113903. * The parameters are provided to Handlebars which in turn generates the template.
  113904. * This function will update the template with the new parameters
  113905. *
  113906. * Note that when updating parameters the events will be registered again (after being cleared).
  113907. *
  113908. * @param params the new template parameters
  113909. */
  113910. Template.prototype.updateParams = function (params, append) {
  113911. if (append === void 0) { append = true; }
  113912. if (append) {
  113913. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  113914. }
  113915. else {
  113916. this._configuration.params = params;
  113917. }
  113918. // update the template
  113919. if (this.isLoaded) {
  113920. // this.dispose();
  113921. }
  113922. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  113923. var config = this._configuration.params || {};
  113924. this._rawHtml = compiledTemplate(config);
  113925. try {
  113926. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  113927. }
  113928. catch (e) {
  113929. var test = document.createElement(this.name);
  113930. test.innerHTML = this._rawHtml;
  113931. this._fragment = test;
  113932. }
  113933. if (this.parent) {
  113934. this.appendTo(this.parent, true);
  113935. }
  113936. };
  113937. Object.defineProperty(Template.prototype, "configuration", {
  113938. /**
  113939. * Get the template'S configuration
  113940. */
  113941. get: function () {
  113942. return this._configuration;
  113943. },
  113944. enumerable: true,
  113945. configurable: true
  113946. });
  113947. /**
  113948. * A template can be a parent element for other templates or HTML elements.
  113949. * This function will deliver all child HTML elements of this template.
  113950. */
  113951. Template.prototype.getChildElements = function () {
  113952. var childrenArray = [];
  113953. //Edge and IE don't support frage,ent.children
  113954. var children = this._fragment && this._fragment.children;
  113955. if (!this._fragment) {
  113956. var fragment = this.parent.querySelector(this.name);
  113957. if (fragment) {
  113958. children = fragment.querySelectorAll('*');
  113959. }
  113960. }
  113961. if (!children) {
  113962. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  113963. children = this._fragment.querySelectorAll('*');
  113964. }
  113965. for (var i = 0; i < children.length; ++i) {
  113966. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  113967. }
  113968. return childrenArray;
  113969. };
  113970. /**
  113971. * Appending the template to a parent HTML element.
  113972. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  113973. * @param parent the parent to which the template is added
  113974. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  113975. */
  113976. Template.prototype.appendTo = function (parent, forceRemove) {
  113977. var _this = this;
  113978. if (this.parent) {
  113979. if (forceRemove && this._addedFragment) {
  113980. /*let fragement = this.parent.querySelector(this.name)
  113981. if (fragement)
  113982. this.parent.removeChild(fragement);*/
  113983. this.parent.innerHTML = '';
  113984. }
  113985. else {
  113986. return;
  113987. }
  113988. }
  113989. this.parent = parent;
  113990. if (this._configuration.id) {
  113991. this.parent.id = this._configuration.id;
  113992. }
  113993. if (this._fragment) {
  113994. this.parent.appendChild(this._fragment);
  113995. this._addedFragment = this._fragment;
  113996. }
  113997. else {
  113998. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  113999. }
  114000. // appended only one frame after.
  114001. setTimeout(function () {
  114002. _this._registerEvents();
  114003. _this.onAppended.notifyObservers(_this);
  114004. });
  114005. };
  114006. /**
  114007. * Show the template using the provided visibilityFunction, or natively using display: flex.
  114008. * The provided function returns a promise that should be fullfilled when the element is shown.
  114009. * Since it is a promise async operations are more than possible.
  114010. * See the default viewer for an opacity example.
  114011. * @param visibilityFunction The function to execute to show the template.
  114012. */
  114013. Template.prototype.show = function (visibilityFunction) {
  114014. var _this = this;
  114015. if (this._isHiding)
  114016. return Promise.resolve(this);
  114017. return Promise.resolve().then(function () {
  114018. _this._isShowing = true;
  114019. if (visibilityFunction) {
  114020. return visibilityFunction(_this);
  114021. }
  114022. else {
  114023. // flex? box? should this be configurable easier than the visibilityFunction?
  114024. _this.parent.style.display = 'flex';
  114025. // support old browsers with no flex:
  114026. if (_this.parent.style.display !== 'flex') {
  114027. _this.parent.style.display = '';
  114028. }
  114029. return _this;
  114030. }
  114031. }).then(function () {
  114032. _this.isShown = true;
  114033. _this._isShowing = false;
  114034. _this.onStateChange.notifyObservers(_this);
  114035. return _this;
  114036. });
  114037. };
  114038. /**
  114039. * Hide the template using the provided visibilityFunction, or natively using display: none.
  114040. * The provided function returns a promise that should be fullfilled when the element is hidden.
  114041. * Since it is a promise async operations are more than possible.
  114042. * See the default viewer for an opacity example.
  114043. * @param visibilityFunction The function to execute to show the template.
  114044. */
  114045. Template.prototype.hide = function (visibilityFunction) {
  114046. var _this = this;
  114047. if (this._isShowing)
  114048. return Promise.resolve(this);
  114049. return Promise.resolve().then(function () {
  114050. _this._isHiding = true;
  114051. if (visibilityFunction) {
  114052. return visibilityFunction(_this);
  114053. }
  114054. else {
  114055. // flex? box? should this be configurable easier than the visibilityFunction?
  114056. _this.parent.style.display = 'none';
  114057. return _this;
  114058. }
  114059. }).then(function () {
  114060. _this.isShown = false;
  114061. _this._isHiding = false;
  114062. _this.onStateChange.notifyObservers(_this);
  114063. return _this;
  114064. });
  114065. };
  114066. /**
  114067. * Dispose this template
  114068. */
  114069. Template.prototype.dispose = function () {
  114070. this.onAppended.clear();
  114071. this.onEventTriggered.clear();
  114072. this.onLoaded.clear();
  114073. this.onStateChange.clear();
  114074. this.isLoaded = false;
  114075. // remove from parent
  114076. try {
  114077. this.parent.removeChild(this._fragment);
  114078. }
  114079. catch (e) {
  114080. //noop
  114081. }
  114082. this.loadRequests.forEach(function (request) {
  114083. request.abort();
  114084. });
  114085. if (this._registeredEvents) {
  114086. this._registeredEvents.forEach(function (evt) {
  114087. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114088. });
  114089. }
  114090. delete this._fragment;
  114091. };
  114092. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  114093. var _this = this;
  114094. if (!templateConfig) {
  114095. return Promise.reject('No templateConfig provided');
  114096. }
  114097. else if (templateConfig.html !== undefined) {
  114098. return Promise.resolve(templateConfig.html);
  114099. }
  114100. else {
  114101. var location_1 = this._getTemplateLocation(templateConfig);
  114102. if (helper_1.isUrl(location_1)) {
  114103. return new Promise(function (resolve, reject) {
  114104. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  114105. resolve(data);
  114106. }, undefined, undefined, false, function (request, error) {
  114107. reject(error);
  114108. });
  114109. _this.loadRequests.push(fileRequest);
  114110. });
  114111. }
  114112. else {
  114113. location_1 = location_1.replace('#', '');
  114114. var element = document.getElementById(location_1);
  114115. if (element) {
  114116. return Promise.resolve(element.innerHTML);
  114117. }
  114118. else {
  114119. return Promise.reject('Template ID not found');
  114120. }
  114121. }
  114122. }
  114123. };
  114124. Template.prototype._registerEvents = function () {
  114125. var _this = this;
  114126. this._registeredEvents = this._registeredEvents || [];
  114127. if (this._registeredEvents.length) {
  114128. // first remove the registered events
  114129. this._registeredEvents.forEach(function (evt) {
  114130. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  114131. });
  114132. }
  114133. if (this._configuration.events) {
  114134. var _loop_1 = function (eventName) {
  114135. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  114136. var functionToFire_1 = function (selector, event) {
  114137. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  114138. };
  114139. // if boolean, set the parent as the event listener
  114140. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  114141. var selector = this_1.parent.id;
  114142. if (selector) {
  114143. selector = '#' + selector;
  114144. }
  114145. else {
  114146. selector = this_1.parent.tagName;
  114147. }
  114148. var binding = functionToFire_1.bind(this_1, selector);
  114149. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  114150. this_1._registeredEvents.push({
  114151. htmlElement: this_1.parent,
  114152. eventName: eventName,
  114153. function: binding
  114154. });
  114155. }
  114156. else if (typeof this_1._configuration.events[eventName] === 'object') {
  114157. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  114158. // strict null checl is working incorrectly, must override:
  114159. var event_1 = this_1._configuration.events[eventName] || {};
  114160. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  114161. var htmlElement = _this.parent.querySelector(selector);
  114162. if (!htmlElement) {
  114163. // backcompat, fallback to id
  114164. if (selector && selector.indexOf('#') !== 0) {
  114165. selector = '#' + selector;
  114166. }
  114167. try {
  114168. htmlElement = _this.parent.querySelector(selector);
  114169. }
  114170. catch (e) { }
  114171. }
  114172. if (htmlElement) {
  114173. var binding = functionToFire_1.bind(_this, selector);
  114174. htmlElement.addEventListener(eventName, binding, false);
  114175. _this._registeredEvents.push({
  114176. htmlElement: htmlElement,
  114177. eventName: eventName,
  114178. function: binding
  114179. });
  114180. }
  114181. });
  114182. }
  114183. }
  114184. };
  114185. var this_1 = this;
  114186. for (var eventName in this._configuration.events) {
  114187. _loop_1(eventName);
  114188. }
  114189. }
  114190. };
  114191. Template.prototype._getTemplateLocation = function (templateConfig) {
  114192. if (!templateConfig || typeof templateConfig === 'string') {
  114193. return templateConfig;
  114194. }
  114195. else {
  114196. return templateConfig.location;
  114197. }
  114198. };
  114199. return Template;
  114200. }());
  114201. exports.Template = Template;
  114202. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLGdCQUFnQixHQUFHLElBQUksc0JBQVUsRUFBaUIsQ0FBQztRQUV4RCxJQUFJLENBQUMsWUFBWSxHQUFHLElBQUksMkJBQVksQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUMvQyxDQUFDO0lBRUQ7OztPQUdHO0lBQ0ksc0NBQVksR0FBbkIsVUFBb0IsU0FBb0Q7UUFBeEUsaUJBdUNDO1FBckNHLElBQUksWUFBWSxHQUFHLFVBQUMsYU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tZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQXJYRCxJQXFYQztBQXJYWSw0QkFBUSJ9
  114203. /***/ }),
  114204. /* 62 */
  114205. /***/ (function(module, exports, __webpack_require__) {
  114206. /**!
  114207. @license
  114208. handlebars v4.0.11
  114209. Copyright (C) 2011-2017 by Yehuda Katz
  114210. Permission is hereby granted, free of charge, to any person obtaining a copy
  114211. of this software and associated documentation files (the "Software"), to deal
  114212. in the Software without restriction, including without limitation the rights
  114213. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  114214. copies of the Software, and to permit persons to whom the Software is
  114215. furnished to do so, subject to the following conditions:
  114216. The above copyright notice and this permission notice shall be included in
  114217. all copies or substantial portions of the Software.
  114218. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  114219. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  114220. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  114221. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  114222. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  114223. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  114224. THE SOFTWARE.
  114225. */
  114226. (function webpackUniversalModuleDefinition(root, factory) {
  114227. if(true)
  114228. module.exports = factory();
  114229. else if(typeof define === 'function' && define.amd)
  114230. define([], factory);
  114231. else if(typeof exports === 'object')
  114232. exports["Handlebars"] = factory();
  114233. else
  114234. root["Handlebars"] = factory();
  114235. })(this, function() {
  114236. return /******/ (function(modules) { // webpackBootstrap
  114237. /******/ // The module cache
  114238. /******/ var installedModules = {};
  114239. /******/ // The require function
  114240. /******/ function __webpack_require__(moduleId) {
  114241. /******/ // Check if module is in cache
  114242. /******/ if(installedModules[moduleId])
  114243. /******/ return installedModules[moduleId].exports;
  114244. /******/ // Create a new module (and put it into the cache)
  114245. /******/ var module = installedModules[moduleId] = {
  114246. /******/ exports: {},
  114247. /******/ id: moduleId,
  114248. /******/ loaded: false
  114249. /******/ };
  114250. /******/ // Execute the module function
  114251. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  114252. /******/ // Flag the module as loaded
  114253. /******/ module.loaded = true;
  114254. /******/ // Return the exports of the module
  114255. /******/ return module.exports;
  114256. /******/ }
  114257. /******/ // expose the modules object (__webpack_modules__)
  114258. /******/ __webpack_require__.m = modules;
  114259. /******/ // expose the module cache
  114260. /******/ __webpack_require__.c = installedModules;
  114261. /******/ // __webpack_public_path__
  114262. /******/ __webpack_require__.p = "";
  114263. /******/ // Load entry module and return exports
  114264. /******/ return __webpack_require__(0);
  114265. /******/ })
  114266. /************************************************************************/
  114267. /******/ ([
  114268. /* 0 */
  114269. /***/ (function(module, exports, __webpack_require__) {
  114270. 'use strict';
  114271. var _interopRequireDefault = __webpack_require__(1)['default'];
  114272. exports.__esModule = true;
  114273. var _handlebarsRuntime = __webpack_require__(2);
  114274. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  114275. // Compiler imports
  114276. var _handlebarsCompilerAst = __webpack_require__(35);
  114277. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  114278. var _handlebarsCompilerBase = __webpack_require__(36);
  114279. var _handlebarsCompilerCompiler = __webpack_require__(41);
  114280. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  114281. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  114282. var _handlebarsCompilerVisitor = __webpack_require__(39);
  114283. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  114284. var _handlebarsNoConflict = __webpack_require__(34);
  114285. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  114286. var _create = _handlebarsRuntime2['default'].create;
  114287. function create() {
  114288. var hb = _create();
  114289. hb.compile = function (input, options) {
  114290. return _handlebarsCompilerCompiler.compile(input, options, hb);
  114291. };
  114292. hb.precompile = function (input, options) {
  114293. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  114294. };
  114295. hb.AST = _handlebarsCompilerAst2['default'];
  114296. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  114297. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  114298. hb.Parser = _handlebarsCompilerBase.parser;
  114299. hb.parse = _handlebarsCompilerBase.parse;
  114300. return hb;
  114301. }
  114302. var inst = create();
  114303. inst.create = create;
  114304. _handlebarsNoConflict2['default'](inst);
  114305. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  114306. inst['default'] = inst;
  114307. exports['default'] = inst;
  114308. module.exports = exports['default'];
  114309. /***/ }),
  114310. /* 1 */
  114311. /***/ (function(module, exports) {
  114312. "use strict";
  114313. exports["default"] = function (obj) {
  114314. return obj && obj.__esModule ? obj : {
  114315. "default": obj
  114316. };
  114317. };
  114318. exports.__esModule = true;
  114319. /***/ }),
  114320. /* 2 */
  114321. /***/ (function(module, exports, __webpack_require__) {
  114322. 'use strict';
  114323. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114324. var _interopRequireDefault = __webpack_require__(1)['default'];
  114325. exports.__esModule = true;
  114326. var _handlebarsBase = __webpack_require__(4);
  114327. var base = _interopRequireWildcard(_handlebarsBase);
  114328. // Each of these augment the Handlebars object. No need to setup here.
  114329. // (This is done to easily share code between commonjs and browse envs)
  114330. var _handlebarsSafeString = __webpack_require__(21);
  114331. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  114332. var _handlebarsException = __webpack_require__(6);
  114333. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  114334. var _handlebarsUtils = __webpack_require__(5);
  114335. var Utils = _interopRequireWildcard(_handlebarsUtils);
  114336. var _handlebarsRuntime = __webpack_require__(22);
  114337. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  114338. var _handlebarsNoConflict = __webpack_require__(34);
  114339. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  114340. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  114341. function create() {
  114342. var hb = new base.HandlebarsEnvironment();
  114343. Utils.extend(hb, base);
  114344. hb.SafeString = _handlebarsSafeString2['default'];
  114345. hb.Exception = _handlebarsException2['default'];
  114346. hb.Utils = Utils;
  114347. hb.escapeExpression = Utils.escapeExpression;
  114348. hb.VM = runtime;
  114349. hb.template = function (spec) {
  114350. return runtime.template(spec, hb);
  114351. };
  114352. return hb;
  114353. }
  114354. var inst = create();
  114355. inst.create = create;
  114356. _handlebarsNoConflict2['default'](inst);
  114357. inst['default'] = inst;
  114358. exports['default'] = inst;
  114359. module.exports = exports['default'];
  114360. /***/ }),
  114361. /* 3 */
  114362. /***/ (function(module, exports) {
  114363. "use strict";
  114364. exports["default"] = function (obj) {
  114365. if (obj && obj.__esModule) {
  114366. return obj;
  114367. } else {
  114368. var newObj = {};
  114369. if (obj != null) {
  114370. for (var key in obj) {
  114371. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  114372. }
  114373. }
  114374. newObj["default"] = obj;
  114375. return newObj;
  114376. }
  114377. };
  114378. exports.__esModule = true;
  114379. /***/ }),
  114380. /* 4 */
  114381. /***/ (function(module, exports, __webpack_require__) {
  114382. 'use strict';
  114383. var _interopRequireDefault = __webpack_require__(1)['default'];
  114384. exports.__esModule = true;
  114385. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  114386. var _utils = __webpack_require__(5);
  114387. var _exception = __webpack_require__(6);
  114388. var _exception2 = _interopRequireDefault(_exception);
  114389. var _helpers = __webpack_require__(10);
  114390. var _decorators = __webpack_require__(18);
  114391. var _logger = __webpack_require__(20);
  114392. var _logger2 = _interopRequireDefault(_logger);
  114393. var VERSION = '4.0.11';
  114394. exports.VERSION = VERSION;
  114395. var COMPILER_REVISION = 7;
  114396. exports.COMPILER_REVISION = COMPILER_REVISION;
  114397. var REVISION_CHANGES = {
  114398. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  114399. 2: '== 1.0.0-rc.3',
  114400. 3: '== 1.0.0-rc.4',
  114401. 4: '== 1.x.x',
  114402. 5: '== 2.0.0-alpha.x',
  114403. 6: '>= 2.0.0-beta.1',
  114404. 7: '>= 4.0.0'
  114405. };
  114406. exports.REVISION_CHANGES = REVISION_CHANGES;
  114407. var objectType = '[object Object]';
  114408. function HandlebarsEnvironment(helpers, partials, decorators) {
  114409. this.helpers = helpers || {};
  114410. this.partials = partials || {};
  114411. this.decorators = decorators || {};
  114412. _helpers.registerDefaultHelpers(this);
  114413. _decorators.registerDefaultDecorators(this);
  114414. }
  114415. HandlebarsEnvironment.prototype = {
  114416. constructor: HandlebarsEnvironment,
  114417. logger: _logger2['default'],
  114418. log: _logger2['default'].log,
  114419. registerHelper: function registerHelper(name, fn) {
  114420. if (_utils.toString.call(name) === objectType) {
  114421. if (fn) {
  114422. throw new _exception2['default']('Arg not supported with multiple helpers');
  114423. }
  114424. _utils.extend(this.helpers, name);
  114425. } else {
  114426. this.helpers[name] = fn;
  114427. }
  114428. },
  114429. unregisterHelper: function unregisterHelper(name) {
  114430. delete this.helpers[name];
  114431. },
  114432. registerPartial: function registerPartial(name, partial) {
  114433. if (_utils.toString.call(name) === objectType) {
  114434. _utils.extend(this.partials, name);
  114435. } else {
  114436. if (typeof partial === 'undefined') {
  114437. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  114438. }
  114439. this.partials[name] = partial;
  114440. }
  114441. },
  114442. unregisterPartial: function unregisterPartial(name) {
  114443. delete this.partials[name];
  114444. },
  114445. registerDecorator: function registerDecorator(name, fn) {
  114446. if (_utils.toString.call(name) === objectType) {
  114447. if (fn) {
  114448. throw new _exception2['default']('Arg not supported with multiple decorators');
  114449. }
  114450. _utils.extend(this.decorators, name);
  114451. } else {
  114452. this.decorators[name] = fn;
  114453. }
  114454. },
  114455. unregisterDecorator: function unregisterDecorator(name) {
  114456. delete this.decorators[name];
  114457. }
  114458. };
  114459. var log = _logger2['default'].log;
  114460. exports.log = log;
  114461. exports.createFrame = _utils.createFrame;
  114462. exports.logger = _logger2['default'];
  114463. /***/ }),
  114464. /* 5 */
  114465. /***/ (function(module, exports) {
  114466. 'use strict';
  114467. exports.__esModule = true;
  114468. exports.extend = extend;
  114469. exports.indexOf = indexOf;
  114470. exports.escapeExpression = escapeExpression;
  114471. exports.isEmpty = isEmpty;
  114472. exports.createFrame = createFrame;
  114473. exports.blockParams = blockParams;
  114474. exports.appendContextPath = appendContextPath;
  114475. var escape = {
  114476. '&': '&amp;',
  114477. '<': '&lt;',
  114478. '>': '&gt;',
  114479. '"': '&quot;',
  114480. "'": '&#x27;',
  114481. '`': '&#x60;',
  114482. '=': '&#x3D;'
  114483. };
  114484. var badChars = /[&<>"'`=]/g,
  114485. possible = /[&<>"'`=]/;
  114486. function escapeChar(chr) {
  114487. return escape[chr];
  114488. }
  114489. function extend(obj /* , ...source */) {
  114490. for (var i = 1; i < arguments.length; i++) {
  114491. for (var key in arguments[i]) {
  114492. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  114493. obj[key] = arguments[i][key];
  114494. }
  114495. }
  114496. }
  114497. return obj;
  114498. }
  114499. var toString = Object.prototype.toString;
  114500. exports.toString = toString;
  114501. // Sourced from lodash
  114502. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  114503. /* eslint-disable func-style */
  114504. var isFunction = function isFunction(value) {
  114505. return typeof value === 'function';
  114506. };
  114507. // fallback for older versions of Chrome and Safari
  114508. /* istanbul ignore next */
  114509. if (isFunction(/x/)) {
  114510. exports.isFunction = isFunction = function (value) {
  114511. return typeof value === 'function' && toString.call(value) === '[object Function]';
  114512. };
  114513. }
  114514. exports.isFunction = isFunction;
  114515. /* eslint-enable func-style */
  114516. /* istanbul ignore next */
  114517. var isArray = Array.isArray || function (value) {
  114518. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  114519. };
  114520. exports.isArray = isArray;
  114521. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  114522. function indexOf(array, value) {
  114523. for (var i = 0, len = array.length; i < len; i++) {
  114524. if (array[i] === value) {
  114525. return i;
  114526. }
  114527. }
  114528. return -1;
  114529. }
  114530. function escapeExpression(string) {
  114531. if (typeof string !== 'string') {
  114532. // don't escape SafeStrings, since they're already safe
  114533. if (string && string.toHTML) {
  114534. return string.toHTML();
  114535. } else if (string == null) {
  114536. return '';
  114537. } else if (!string) {
  114538. return string + '';
  114539. }
  114540. // Force a string conversion as this will be done by the append regardless and
  114541. // the regex test will do this transparently behind the scenes, causing issues if
  114542. // an object's to string has escaped characters in it.
  114543. string = '' + string;
  114544. }
  114545. if (!possible.test(string)) {
  114546. return string;
  114547. }
  114548. return string.replace(badChars, escapeChar);
  114549. }
  114550. function isEmpty(value) {
  114551. if (!value && value !== 0) {
  114552. return true;
  114553. } else if (isArray(value) && value.length === 0) {
  114554. return true;
  114555. } else {
  114556. return false;
  114557. }
  114558. }
  114559. function createFrame(object) {
  114560. var frame = extend({}, object);
  114561. frame._parent = object;
  114562. return frame;
  114563. }
  114564. function blockParams(params, ids) {
  114565. params.path = ids;
  114566. return params;
  114567. }
  114568. function appendContextPath(contextPath, id) {
  114569. return (contextPath ? contextPath + '.' : '') + id;
  114570. }
  114571. /***/ }),
  114572. /* 6 */
  114573. /***/ (function(module, exports, __webpack_require__) {
  114574. 'use strict';
  114575. var _Object$defineProperty = __webpack_require__(7)['default'];
  114576. exports.__esModule = true;
  114577. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  114578. function Exception(message, node) {
  114579. var loc = node && node.loc,
  114580. line = undefined,
  114581. column = undefined;
  114582. if (loc) {
  114583. line = loc.start.line;
  114584. column = loc.start.column;
  114585. message += ' - ' + line + ':' + column;
  114586. }
  114587. var tmp = Error.prototype.constructor.call(this, message);
  114588. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  114589. for (var idx = 0; idx < errorProps.length; idx++) {
  114590. this[errorProps[idx]] = tmp[errorProps[idx]];
  114591. }
  114592. /* istanbul ignore else */
  114593. if (Error.captureStackTrace) {
  114594. Error.captureStackTrace(this, Exception);
  114595. }
  114596. try {
  114597. if (loc) {
  114598. this.lineNumber = line;
  114599. // Work around issue under safari where we can't directly set the column value
  114600. /* istanbul ignore next */
  114601. if (_Object$defineProperty) {
  114602. Object.defineProperty(this, 'column', {
  114603. value: column,
  114604. enumerable: true
  114605. });
  114606. } else {
  114607. this.column = column;
  114608. }
  114609. }
  114610. } catch (nop) {
  114611. /* Ignore if the browser is very particular */
  114612. }
  114613. }
  114614. Exception.prototype = new Error();
  114615. exports['default'] = Exception;
  114616. module.exports = exports['default'];
  114617. /***/ }),
  114618. /* 7 */
  114619. /***/ (function(module, exports, __webpack_require__) {
  114620. module.exports = { "default": __webpack_require__(8), __esModule: true };
  114621. /***/ }),
  114622. /* 8 */
  114623. /***/ (function(module, exports, __webpack_require__) {
  114624. var $ = __webpack_require__(9);
  114625. module.exports = function defineProperty(it, key, desc){
  114626. return $.setDesc(it, key, desc);
  114627. };
  114628. /***/ }),
  114629. /* 9 */
  114630. /***/ (function(module, exports) {
  114631. var $Object = Object;
  114632. module.exports = {
  114633. create: $Object.create,
  114634. getProto: $Object.getPrototypeOf,
  114635. isEnum: {}.propertyIsEnumerable,
  114636. getDesc: $Object.getOwnPropertyDescriptor,
  114637. setDesc: $Object.defineProperty,
  114638. setDescs: $Object.defineProperties,
  114639. getKeys: $Object.keys,
  114640. getNames: $Object.getOwnPropertyNames,
  114641. getSymbols: $Object.getOwnPropertySymbols,
  114642. each: [].forEach
  114643. };
  114644. /***/ }),
  114645. /* 10 */
  114646. /***/ (function(module, exports, __webpack_require__) {
  114647. 'use strict';
  114648. var _interopRequireDefault = __webpack_require__(1)['default'];
  114649. exports.__esModule = true;
  114650. exports.registerDefaultHelpers = registerDefaultHelpers;
  114651. var _helpersBlockHelperMissing = __webpack_require__(11);
  114652. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  114653. var _helpersEach = __webpack_require__(12);
  114654. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  114655. var _helpersHelperMissing = __webpack_require__(13);
  114656. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  114657. var _helpersIf = __webpack_require__(14);
  114658. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  114659. var _helpersLog = __webpack_require__(15);
  114660. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  114661. var _helpersLookup = __webpack_require__(16);
  114662. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  114663. var _helpersWith = __webpack_require__(17);
  114664. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  114665. function registerDefaultHelpers(instance) {
  114666. _helpersBlockHelperMissing2['default'](instance);
  114667. _helpersEach2['default'](instance);
  114668. _helpersHelperMissing2['default'](instance);
  114669. _helpersIf2['default'](instance);
  114670. _helpersLog2['default'](instance);
  114671. _helpersLookup2['default'](instance);
  114672. _helpersWith2['default'](instance);
  114673. }
  114674. /***/ }),
  114675. /* 11 */
  114676. /***/ (function(module, exports, __webpack_require__) {
  114677. 'use strict';
  114678. exports.__esModule = true;
  114679. var _utils = __webpack_require__(5);
  114680. exports['default'] = function (instance) {
  114681. instance.registerHelper('blockHelperMissing', function (context, options) {
  114682. var inverse = options.inverse,
  114683. fn = options.fn;
  114684. if (context === true) {
  114685. return fn(this);
  114686. } else if (context === false || context == null) {
  114687. return inverse(this);
  114688. } else if (_utils.isArray(context)) {
  114689. if (context.length > 0) {
  114690. if (options.ids) {
  114691. options.ids = [options.name];
  114692. }
  114693. return instance.helpers.each(context, options);
  114694. } else {
  114695. return inverse(this);
  114696. }
  114697. } else {
  114698. if (options.data && options.ids) {
  114699. var data = _utils.createFrame(options.data);
  114700. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  114701. options = { data: data };
  114702. }
  114703. return fn(context, options);
  114704. }
  114705. });
  114706. };
  114707. module.exports = exports['default'];
  114708. /***/ }),
  114709. /* 12 */
  114710. /***/ (function(module, exports, __webpack_require__) {
  114711. 'use strict';
  114712. var _interopRequireDefault = __webpack_require__(1)['default'];
  114713. exports.__esModule = true;
  114714. var _utils = __webpack_require__(5);
  114715. var _exception = __webpack_require__(6);
  114716. var _exception2 = _interopRequireDefault(_exception);
  114717. exports['default'] = function (instance) {
  114718. instance.registerHelper('each', function (context, options) {
  114719. if (!options) {
  114720. throw new _exception2['default']('Must pass iterator to #each');
  114721. }
  114722. var fn = options.fn,
  114723. inverse = options.inverse,
  114724. i = 0,
  114725. ret = '',
  114726. data = undefined,
  114727. contextPath = undefined;
  114728. if (options.data && options.ids) {
  114729. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  114730. }
  114731. if (_utils.isFunction(context)) {
  114732. context = context.call(this);
  114733. }
  114734. if (options.data) {
  114735. data = _utils.createFrame(options.data);
  114736. }
  114737. function execIteration(field, index, last) {
  114738. if (data) {
  114739. data.key = field;
  114740. data.index = index;
  114741. data.first = index === 0;
  114742. data.last = !!last;
  114743. if (contextPath) {
  114744. data.contextPath = contextPath + field;
  114745. }
  114746. }
  114747. ret = ret + fn(context[field], {
  114748. data: data,
  114749. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  114750. });
  114751. }
  114752. if (context && typeof context === 'object') {
  114753. if (_utils.isArray(context)) {
  114754. for (var j = context.length; i < j; i++) {
  114755. if (i in context) {
  114756. execIteration(i, i, i === context.length - 1);
  114757. }
  114758. }
  114759. } else {
  114760. var priorKey = undefined;
  114761. for (var key in context) {
  114762. if (context.hasOwnProperty(key)) {
  114763. // We're running the iterations one step out of sync so we can detect
  114764. // the last iteration without have to scan the object twice and create
  114765. // an itermediate keys array.
  114766. if (priorKey !== undefined) {
  114767. execIteration(priorKey, i - 1);
  114768. }
  114769. priorKey = key;
  114770. i++;
  114771. }
  114772. }
  114773. if (priorKey !== undefined) {
  114774. execIteration(priorKey, i - 1, true);
  114775. }
  114776. }
  114777. }
  114778. if (i === 0) {
  114779. ret = inverse(this);
  114780. }
  114781. return ret;
  114782. });
  114783. };
  114784. module.exports = exports['default'];
  114785. /***/ }),
  114786. /* 13 */
  114787. /***/ (function(module, exports, __webpack_require__) {
  114788. 'use strict';
  114789. var _interopRequireDefault = __webpack_require__(1)['default'];
  114790. exports.__esModule = true;
  114791. var _exception = __webpack_require__(6);
  114792. var _exception2 = _interopRequireDefault(_exception);
  114793. exports['default'] = function (instance) {
  114794. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  114795. if (arguments.length === 1) {
  114796. // A missing field in a {{foo}} construct.
  114797. return undefined;
  114798. } else {
  114799. // Someone is actually trying to call something, blow up.
  114800. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  114801. }
  114802. });
  114803. };
  114804. module.exports = exports['default'];
  114805. /***/ }),
  114806. /* 14 */
  114807. /***/ (function(module, exports, __webpack_require__) {
  114808. 'use strict';
  114809. exports.__esModule = true;
  114810. var _utils = __webpack_require__(5);
  114811. exports['default'] = function (instance) {
  114812. instance.registerHelper('if', function (conditional, options) {
  114813. if (_utils.isFunction(conditional)) {
  114814. conditional = conditional.call(this);
  114815. }
  114816. // Default behavior is to render the positive path if the value is truthy and not empty.
  114817. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  114818. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  114819. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  114820. return options.inverse(this);
  114821. } else {
  114822. return options.fn(this);
  114823. }
  114824. });
  114825. instance.registerHelper('unless', function (conditional, options) {
  114826. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  114827. });
  114828. };
  114829. module.exports = exports['default'];
  114830. /***/ }),
  114831. /* 15 */
  114832. /***/ (function(module, exports) {
  114833. 'use strict';
  114834. exports.__esModule = true;
  114835. exports['default'] = function (instance) {
  114836. instance.registerHelper('log', function () /* message, options */{
  114837. var args = [undefined],
  114838. options = arguments[arguments.length - 1];
  114839. for (var i = 0; i < arguments.length - 1; i++) {
  114840. args.push(arguments[i]);
  114841. }
  114842. var level = 1;
  114843. if (options.hash.level != null) {
  114844. level = options.hash.level;
  114845. } else if (options.data && options.data.level != null) {
  114846. level = options.data.level;
  114847. }
  114848. args[0] = level;
  114849. instance.log.apply(instance, args);
  114850. });
  114851. };
  114852. module.exports = exports['default'];
  114853. /***/ }),
  114854. /* 16 */
  114855. /***/ (function(module, exports) {
  114856. 'use strict';
  114857. exports.__esModule = true;
  114858. exports['default'] = function (instance) {
  114859. instance.registerHelper('lookup', function (obj, field) {
  114860. return obj && obj[field];
  114861. });
  114862. };
  114863. module.exports = exports['default'];
  114864. /***/ }),
  114865. /* 17 */
  114866. /***/ (function(module, exports, __webpack_require__) {
  114867. 'use strict';
  114868. exports.__esModule = true;
  114869. var _utils = __webpack_require__(5);
  114870. exports['default'] = function (instance) {
  114871. instance.registerHelper('with', function (context, options) {
  114872. if (_utils.isFunction(context)) {
  114873. context = context.call(this);
  114874. }
  114875. var fn = options.fn;
  114876. if (!_utils.isEmpty(context)) {
  114877. var data = options.data;
  114878. if (options.data && options.ids) {
  114879. data = _utils.createFrame(options.data);
  114880. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  114881. }
  114882. return fn(context, {
  114883. data: data,
  114884. blockParams: _utils.blockParams([context], [data && data.contextPath])
  114885. });
  114886. } else {
  114887. return options.inverse(this);
  114888. }
  114889. });
  114890. };
  114891. module.exports = exports['default'];
  114892. /***/ }),
  114893. /* 18 */
  114894. /***/ (function(module, exports, __webpack_require__) {
  114895. 'use strict';
  114896. var _interopRequireDefault = __webpack_require__(1)['default'];
  114897. exports.__esModule = true;
  114898. exports.registerDefaultDecorators = registerDefaultDecorators;
  114899. var _decoratorsInline = __webpack_require__(19);
  114900. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  114901. function registerDefaultDecorators(instance) {
  114902. _decoratorsInline2['default'](instance);
  114903. }
  114904. /***/ }),
  114905. /* 19 */
  114906. /***/ (function(module, exports, __webpack_require__) {
  114907. 'use strict';
  114908. exports.__esModule = true;
  114909. var _utils = __webpack_require__(5);
  114910. exports['default'] = function (instance) {
  114911. instance.registerDecorator('inline', function (fn, props, container, options) {
  114912. var ret = fn;
  114913. if (!props.partials) {
  114914. props.partials = {};
  114915. ret = function (context, options) {
  114916. // Create a new partials stack frame prior to exec.
  114917. var original = container.partials;
  114918. container.partials = _utils.extend({}, original, props.partials);
  114919. var ret = fn(context, options);
  114920. container.partials = original;
  114921. return ret;
  114922. };
  114923. }
  114924. props.partials[options.args[0]] = options.fn;
  114925. return ret;
  114926. });
  114927. };
  114928. module.exports = exports['default'];
  114929. /***/ }),
  114930. /* 20 */
  114931. /***/ (function(module, exports, __webpack_require__) {
  114932. 'use strict';
  114933. exports.__esModule = true;
  114934. var _utils = __webpack_require__(5);
  114935. var logger = {
  114936. methodMap: ['debug', 'info', 'warn', 'error'],
  114937. level: 'info',
  114938. // Maps a given level value to the `methodMap` indexes above.
  114939. lookupLevel: function lookupLevel(level) {
  114940. if (typeof level === 'string') {
  114941. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  114942. if (levelMap >= 0) {
  114943. level = levelMap;
  114944. } else {
  114945. level = parseInt(level, 10);
  114946. }
  114947. }
  114948. return level;
  114949. },
  114950. // Can be overridden in the host environment
  114951. log: function log(level) {
  114952. level = logger.lookupLevel(level);
  114953. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  114954. var method = logger.methodMap[level];
  114955. if (!console[method]) {
  114956. // eslint-disable-line no-console
  114957. method = 'log';
  114958. }
  114959. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  114960. message[_key - 1] = arguments[_key];
  114961. }
  114962. console[method].apply(console, message); // eslint-disable-line no-console
  114963. }
  114964. }
  114965. };
  114966. exports['default'] = logger;
  114967. module.exports = exports['default'];
  114968. /***/ }),
  114969. /* 21 */
  114970. /***/ (function(module, exports) {
  114971. // Build out our basic SafeString type
  114972. 'use strict';
  114973. exports.__esModule = true;
  114974. function SafeString(string) {
  114975. this.string = string;
  114976. }
  114977. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  114978. return '' + this.string;
  114979. };
  114980. exports['default'] = SafeString;
  114981. module.exports = exports['default'];
  114982. /***/ }),
  114983. /* 22 */
  114984. /***/ (function(module, exports, __webpack_require__) {
  114985. 'use strict';
  114986. var _Object$seal = __webpack_require__(23)['default'];
  114987. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114988. var _interopRequireDefault = __webpack_require__(1)['default'];
  114989. exports.__esModule = true;
  114990. exports.checkRevision = checkRevision;
  114991. exports.template = template;
  114992. exports.wrapProgram = wrapProgram;
  114993. exports.resolvePartial = resolvePartial;
  114994. exports.invokePartial = invokePartial;
  114995. exports.noop = noop;
  114996. var _utils = __webpack_require__(5);
  114997. var Utils = _interopRequireWildcard(_utils);
  114998. var _exception = __webpack_require__(6);
  114999. var _exception2 = _interopRequireDefault(_exception);
  115000. var _base = __webpack_require__(4);
  115001. function checkRevision(compilerInfo) {
  115002. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  115003. currentRevision = _base.COMPILER_REVISION;
  115004. if (compilerRevision !== currentRevision) {
  115005. if (compilerRevision < currentRevision) {
  115006. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  115007. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  115008. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  115009. } else {
  115010. // Use the embedded version info since the runtime doesn't know about this revision yet
  115011. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  115012. }
  115013. }
  115014. }
  115015. function template(templateSpec, env) {
  115016. /* istanbul ignore next */
  115017. if (!env) {
  115018. throw new _exception2['default']('No environment passed to template');
  115019. }
  115020. if (!templateSpec || !templateSpec.main) {
  115021. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  115022. }
  115023. templateSpec.main.decorator = templateSpec.main_d;
  115024. // Note: Using env.VM references rather than local var references throughout this section to allow
  115025. // for external users to override these as psuedo-supported APIs.
  115026. env.VM.checkRevision(templateSpec.compiler);
  115027. function invokePartialWrapper(partial, context, options) {
  115028. if (options.hash) {
  115029. context = Utils.extend({}, context, options.hash);
  115030. if (options.ids) {
  115031. options.ids[0] = true;
  115032. }
  115033. }
  115034. partial = env.VM.resolvePartial.call(this, partial, context, options);
  115035. var result = env.VM.invokePartial.call(this, partial, context, options);
  115036. if (result == null && env.compile) {
  115037. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  115038. result = options.partials[options.name](context, options);
  115039. }
  115040. if (result != null) {
  115041. if (options.indent) {
  115042. var lines = result.split('\n');
  115043. for (var i = 0, l = lines.length; i < l; i++) {
  115044. if (!lines[i] && i + 1 === l) {
  115045. break;
  115046. }
  115047. lines[i] = options.indent + lines[i];
  115048. }
  115049. result = lines.join('\n');
  115050. }
  115051. return result;
  115052. } else {
  115053. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  115054. }
  115055. }
  115056. // Just add water
  115057. var container = {
  115058. strict: function strict(obj, name) {
  115059. if (!(name in obj)) {
  115060. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  115061. }
  115062. return obj[name];
  115063. },
  115064. lookup: function lookup(depths, name) {
  115065. var len = depths.length;
  115066. for (var i = 0; i < len; i++) {
  115067. if (depths[i] && depths[i][name] != null) {
  115068. return depths[i][name];
  115069. }
  115070. }
  115071. },
  115072. lambda: function lambda(current, context) {
  115073. return typeof current === 'function' ? current.call(context) : current;
  115074. },
  115075. escapeExpression: Utils.escapeExpression,
  115076. invokePartial: invokePartialWrapper,
  115077. fn: function fn(i) {
  115078. var ret = templateSpec[i];
  115079. ret.decorator = templateSpec[i + '_d'];
  115080. return ret;
  115081. },
  115082. programs: [],
  115083. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  115084. var programWrapper = this.programs[i],
  115085. fn = this.fn(i);
  115086. if (data || depths || blockParams || declaredBlockParams) {
  115087. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  115088. } else if (!programWrapper) {
  115089. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  115090. }
  115091. return programWrapper;
  115092. },
  115093. data: function data(value, depth) {
  115094. while (value && depth--) {
  115095. value = value._parent;
  115096. }
  115097. return value;
  115098. },
  115099. merge: function merge(param, common) {
  115100. var obj = param || common;
  115101. if (param && common && param !== common) {
  115102. obj = Utils.extend({}, common, param);
  115103. }
  115104. return obj;
  115105. },
  115106. // An empty object to use as replacement for null-contexts
  115107. nullContext: _Object$seal({}),
  115108. noop: env.VM.noop,
  115109. compilerInfo: templateSpec.compiler
  115110. };
  115111. function ret(context) {
  115112. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115113. var data = options.data;
  115114. ret._setup(options);
  115115. if (!options.partial && templateSpec.useData) {
  115116. data = initData(context, data);
  115117. }
  115118. var depths = undefined,
  115119. blockParams = templateSpec.useBlockParams ? [] : undefined;
  115120. if (templateSpec.useDepths) {
  115121. if (options.depths) {
  115122. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  115123. } else {
  115124. depths = [context];
  115125. }
  115126. }
  115127. function main(context /*, options*/) {
  115128. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  115129. }
  115130. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  115131. return main(context, options);
  115132. }
  115133. ret.isTop = true;
  115134. ret._setup = function (options) {
  115135. if (!options.partial) {
  115136. container.helpers = container.merge(options.helpers, env.helpers);
  115137. if (templateSpec.usePartial) {
  115138. container.partials = container.merge(options.partials, env.partials);
  115139. }
  115140. if (templateSpec.usePartial || templateSpec.useDecorators) {
  115141. container.decorators = container.merge(options.decorators, env.decorators);
  115142. }
  115143. } else {
  115144. container.helpers = options.helpers;
  115145. container.partials = options.partials;
  115146. container.decorators = options.decorators;
  115147. }
  115148. };
  115149. ret._child = function (i, data, blockParams, depths) {
  115150. if (templateSpec.useBlockParams && !blockParams) {
  115151. throw new _exception2['default']('must pass block params');
  115152. }
  115153. if (templateSpec.useDepths && !depths) {
  115154. throw new _exception2['default']('must pass parent depths');
  115155. }
  115156. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  115157. };
  115158. return ret;
  115159. }
  115160. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  115161. function prog(context) {
  115162. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115163. var currentDepths = depths;
  115164. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  115165. currentDepths = [context].concat(depths);
  115166. }
  115167. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  115168. }
  115169. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  115170. prog.program = i;
  115171. prog.depth = depths ? depths.length : 0;
  115172. prog.blockParams = declaredBlockParams || 0;
  115173. return prog;
  115174. }
  115175. function resolvePartial(partial, context, options) {
  115176. if (!partial) {
  115177. if (options.name === '@partial-block') {
  115178. partial = options.data['partial-block'];
  115179. } else {
  115180. partial = options.partials[options.name];
  115181. }
  115182. } else if (!partial.call && !options.name) {
  115183. // This is a dynamic partial that returned a string
  115184. options.name = partial;
  115185. partial = options.partials[partial];
  115186. }
  115187. return partial;
  115188. }
  115189. function invokePartial(partial, context, options) {
  115190. // Use the current closure context to save the partial-block if this partial
  115191. var currentPartialBlock = options.data && options.data['partial-block'];
  115192. options.partial = true;
  115193. if (options.ids) {
  115194. options.data.contextPath = options.ids[0] || options.data.contextPath;
  115195. }
  115196. var partialBlock = undefined;
  115197. if (options.fn && options.fn !== noop) {
  115198. (function () {
  115199. options.data = _base.createFrame(options.data);
  115200. // Wrapper function to get access to currentPartialBlock from the closure
  115201. var fn = options.fn;
  115202. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  115203. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  115204. // Restore the partial-block from the closure for the execution of the block
  115205. // i.e. the part inside the block of the partial call.
  115206. options.data = _base.createFrame(options.data);
  115207. options.data['partial-block'] = currentPartialBlock;
  115208. return fn(context, options);
  115209. };
  115210. if (fn.partials) {
  115211. options.partials = Utils.extend({}, options.partials, fn.partials);
  115212. }
  115213. })();
  115214. }
  115215. if (partial === undefined && partialBlock) {
  115216. partial = partialBlock;
  115217. }
  115218. if (partial === undefined) {
  115219. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  115220. } else if (partial instanceof Function) {
  115221. return partial(context, options);
  115222. }
  115223. }
  115224. function noop() {
  115225. return '';
  115226. }
  115227. function initData(context, data) {
  115228. if (!data || !('root' in data)) {
  115229. data = data ? _base.createFrame(data) : {};
  115230. data.root = context;
  115231. }
  115232. return data;
  115233. }
  115234. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  115235. if (fn.decorator) {
  115236. var props = {};
  115237. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  115238. Utils.extend(prog, props);
  115239. }
  115240. return prog;
  115241. }
  115242. /***/ }),
  115243. /* 23 */
  115244. /***/ (function(module, exports, __webpack_require__) {
  115245. module.exports = { "default": __webpack_require__(24), __esModule: true };
  115246. /***/ }),
  115247. /* 24 */
  115248. /***/ (function(module, exports, __webpack_require__) {
  115249. __webpack_require__(25);
  115250. module.exports = __webpack_require__(30).Object.seal;
  115251. /***/ }),
  115252. /* 25 */
  115253. /***/ (function(module, exports, __webpack_require__) {
  115254. // 19.1.2.17 Object.seal(O)
  115255. var isObject = __webpack_require__(26);
  115256. __webpack_require__(27)('seal', function($seal){
  115257. return function seal(it){
  115258. return $seal && isObject(it) ? $seal(it) : it;
  115259. };
  115260. });
  115261. /***/ }),
  115262. /* 26 */
  115263. /***/ (function(module, exports) {
  115264. module.exports = function(it){
  115265. return typeof it === 'object' ? it !== null : typeof it === 'function';
  115266. };
  115267. /***/ }),
  115268. /* 27 */
  115269. /***/ (function(module, exports, __webpack_require__) {
  115270. // most Object methods by ES6 should accept primitives
  115271. var $export = __webpack_require__(28)
  115272. , core = __webpack_require__(30)
  115273. , fails = __webpack_require__(33);
  115274. module.exports = function(KEY, exec){
  115275. var fn = (core.Object || {})[KEY] || Object[KEY]
  115276. , exp = {};
  115277. exp[KEY] = exec(fn);
  115278. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  115279. };
  115280. /***/ }),
  115281. /* 28 */
  115282. /***/ (function(module, exports, __webpack_require__) {
  115283. var global = __webpack_require__(29)
  115284. , core = __webpack_require__(30)
  115285. , ctx = __webpack_require__(31)
  115286. , PROTOTYPE = 'prototype';
  115287. var $export = function(type, name, source){
  115288. var IS_FORCED = type & $export.F
  115289. , IS_GLOBAL = type & $export.G
  115290. , IS_STATIC = type & $export.S
  115291. , IS_PROTO = type & $export.P
  115292. , IS_BIND = type & $export.B
  115293. , IS_WRAP = type & $export.W
  115294. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  115295. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  115296. , key, own, out;
  115297. if(IS_GLOBAL)source = name;
  115298. for(key in source){
  115299. // contains in native
  115300. own = !IS_FORCED && target && key in target;
  115301. if(own && key in exports)continue;
  115302. // export native or passed
  115303. out = own ? target[key] : source[key];
  115304. // prevent global pollution for namespaces
  115305. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  115306. // bind timers to global for call from export context
  115307. : IS_BIND && own ? ctx(out, global)
  115308. // wrap global constructors for prevent change them in library
  115309. : IS_WRAP && target[key] == out ? (function(C){
  115310. var F = function(param){
  115311. return this instanceof C ? new C(param) : C(param);
  115312. };
  115313. F[PROTOTYPE] = C[PROTOTYPE];
  115314. return F;
  115315. // make static versions for prototype methods
  115316. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  115317. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  115318. }
  115319. };
  115320. // type bitmap
  115321. $export.F = 1; // forced
  115322. $export.G = 2; // global
  115323. $export.S = 4; // static
  115324. $export.P = 8; // proto
  115325. $export.B = 16; // bind
  115326. $export.W = 32; // wrap
  115327. module.exports = $export;
  115328. /***/ }),
  115329. /* 29 */
  115330. /***/ (function(module, exports) {
  115331. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  115332. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  115333. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  115334. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  115335. /***/ }),
  115336. /* 30 */
  115337. /***/ (function(module, exports) {
  115338. var core = module.exports = {version: '1.2.6'};
  115339. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  115340. /***/ }),
  115341. /* 31 */
  115342. /***/ (function(module, exports, __webpack_require__) {
  115343. // optional / simple context binding
  115344. var aFunction = __webpack_require__(32);
  115345. module.exports = function(fn, that, length){
  115346. aFunction(fn);
  115347. if(that === undefined)return fn;
  115348. switch(length){
  115349. case 1: return function(a){
  115350. return fn.call(that, a);
  115351. };
  115352. case 2: return function(a, b){
  115353. return fn.call(that, a, b);
  115354. };
  115355. case 3: return function(a, b, c){
  115356. return fn.call(that, a, b, c);
  115357. };
  115358. }
  115359. return function(/* ...args */){
  115360. return fn.apply(that, arguments);
  115361. };
  115362. };
  115363. /***/ }),
  115364. /* 32 */
  115365. /***/ (function(module, exports) {
  115366. module.exports = function(it){
  115367. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  115368. return it;
  115369. };
  115370. /***/ }),
  115371. /* 33 */
  115372. /***/ (function(module, exports) {
  115373. module.exports = function(exec){
  115374. try {
  115375. return !!exec();
  115376. } catch(e){
  115377. return true;
  115378. }
  115379. };
  115380. /***/ }),
  115381. /* 34 */
  115382. /***/ (function(module, exports) {
  115383. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  115384. 'use strict';
  115385. exports.__esModule = true;
  115386. exports['default'] = function (Handlebars) {
  115387. /* istanbul ignore next */
  115388. var root = typeof global !== 'undefined' ? global : window,
  115389. $Handlebars = root.Handlebars;
  115390. /* istanbul ignore next */
  115391. Handlebars.noConflict = function () {
  115392. if (root.Handlebars === Handlebars) {
  115393. root.Handlebars = $Handlebars;
  115394. }
  115395. return Handlebars;
  115396. };
  115397. };
  115398. module.exports = exports['default'];
  115399. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  115400. /***/ }),
  115401. /* 35 */
  115402. /***/ (function(module, exports) {
  115403. 'use strict';
  115404. exports.__esModule = true;
  115405. var AST = {
  115406. // Public API used to evaluate derived attributes regarding AST nodes
  115407. helpers: {
  115408. // a mustache is definitely a helper if:
  115409. // * it is an eligible helper, and
  115410. // * it has at least one parameter or hash segment
  115411. helperExpression: function helperExpression(node) {
  115412. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  115413. },
  115414. scopedId: function scopedId(path) {
  115415. return (/^\.|this\b/.test(path.original)
  115416. );
  115417. },
  115418. // an ID is simple if it only has one part, and that part is not
  115419. // `..` or `this`.
  115420. simpleId: function simpleId(path) {
  115421. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  115422. }
  115423. }
  115424. };
  115425. // Must be exported as an object rather than the root of the module as the jison lexer
  115426. // must modify the object to operate properly.
  115427. exports['default'] = AST;
  115428. module.exports = exports['default'];
  115429. /***/ }),
  115430. /* 36 */
  115431. /***/ (function(module, exports, __webpack_require__) {
  115432. 'use strict';
  115433. var _interopRequireDefault = __webpack_require__(1)['default'];
  115434. var _interopRequireWildcard = __webpack_require__(3)['default'];
  115435. exports.__esModule = true;
  115436. exports.parse = parse;
  115437. var _parser = __webpack_require__(37);
  115438. var _parser2 = _interopRequireDefault(_parser);
  115439. var _whitespaceControl = __webpack_require__(38);
  115440. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  115441. var _helpers = __webpack_require__(40);
  115442. var Helpers = _interopRequireWildcard(_helpers);
  115443. var _utils = __webpack_require__(5);
  115444. exports.parser = _parser2['default'];
  115445. var yy = {};
  115446. _utils.extend(yy, Helpers);
  115447. function parse(input, options) {
  115448. // Just return if an already-compiled AST was passed in.
  115449. if (input.type === 'Program') {
  115450. return input;
  115451. }
  115452. _parser2['default'].yy = yy;
  115453. // Altering the shared object here, but this is ok as parser is a sync operation
  115454. yy.locInfo = function (locInfo) {
  115455. return new yy.SourceLocation(options && options.srcName, locInfo);
  115456. };
  115457. var strip = new _whitespaceControl2['default'](options);
  115458. return strip.accept(_parser2['default'].parse(input));
  115459. }
  115460. /***/ }),
  115461. /* 37 */
  115462. /***/ (function(module, exports) {
  115463. // File ignored in coverage tests via setting in .istanbul.yml
  115464. /* Jison generated parser */
  115465. "use strict";
  115466. exports.__esModule = true;
  115467. var handlebars = (function () {
  115468. var parser = { trace: function trace() {},
  115469. yy: {},
  115470. 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 },
  115471. 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" },
  115472. 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]],
  115473. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  115474. /**/) {
  115475. var $0 = $$.length - 1;
  115476. switch (yystate) {
  115477. case 1:
  115478. return $$[$0 - 1];
  115479. break;
  115480. case 2:
  115481. this.$ = yy.prepareProgram($$[$0]);
  115482. break;
  115483. case 3:
  115484. this.$ = $$[$0];
  115485. break;
  115486. case 4:
  115487. this.$ = $$[$0];
  115488. break;
  115489. case 5:
  115490. this.$ = $$[$0];
  115491. break;
  115492. case 6:
  115493. this.$ = $$[$0];
  115494. break;
  115495. case 7:
  115496. this.$ = $$[$0];
  115497. break;
  115498. case 8:
  115499. this.$ = $$[$0];
  115500. break;
  115501. case 9:
  115502. this.$ = {
  115503. type: 'CommentStatement',
  115504. value: yy.stripComment($$[$0]),
  115505. strip: yy.stripFlags($$[$0], $$[$0]),
  115506. loc: yy.locInfo(this._$)
  115507. };
  115508. break;
  115509. case 10:
  115510. this.$ = {
  115511. type: 'ContentStatement',
  115512. original: $$[$0],
  115513. value: $$[$0],
  115514. loc: yy.locInfo(this._$)
  115515. };
  115516. break;
  115517. case 11:
  115518. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  115519. break;
  115520. case 12:
  115521. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  115522. break;
  115523. case 13:
  115524. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  115525. break;
  115526. case 14:
  115527. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  115528. break;
  115529. case 15:
  115530. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115531. break;
  115532. case 16:
  115533. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115534. break;
  115535. case 17:
  115536. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  115537. break;
  115538. case 18:
  115539. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  115540. break;
  115541. case 19:
  115542. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  115543. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  115544. program.chained = true;
  115545. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  115546. break;
  115547. case 20:
  115548. this.$ = $$[$0];
  115549. break;
  115550. case 21:
  115551. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  115552. break;
  115553. case 22:
  115554. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  115555. break;
  115556. case 23:
  115557. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  115558. break;
  115559. case 24:
  115560. this.$ = {
  115561. type: 'PartialStatement',
  115562. name: $$[$0 - 3],
  115563. params: $$[$0 - 2],
  115564. hash: $$[$0 - 1],
  115565. indent: '',
  115566. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  115567. loc: yy.locInfo(this._$)
  115568. };
  115569. break;
  115570. case 25:
  115571. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  115572. break;
  115573. case 26:
  115574. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  115575. break;
  115576. case 27:
  115577. this.$ = $$[$0];
  115578. break;
  115579. case 28:
  115580. this.$ = $$[$0];
  115581. break;
  115582. case 29:
  115583. this.$ = {
  115584. type: 'SubExpression',
  115585. path: $$[$0 - 3],
  115586. params: $$[$0 - 2],
  115587. hash: $$[$0 - 1],
  115588. loc: yy.locInfo(this._$)
  115589. };
  115590. break;
  115591. case 30:
  115592. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  115593. break;
  115594. case 31:
  115595. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  115596. break;
  115597. case 32:
  115598. this.$ = yy.id($$[$0 - 1]);
  115599. break;
  115600. case 33:
  115601. this.$ = $$[$0];
  115602. break;
  115603. case 34:
  115604. this.$ = $$[$0];
  115605. break;
  115606. case 35:
  115607. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  115608. break;
  115609. case 36:
  115610. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  115611. break;
  115612. case 37:
  115613. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  115614. break;
  115615. case 38:
  115616. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  115617. break;
  115618. case 39:
  115619. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  115620. break;
  115621. case 40:
  115622. this.$ = $$[$0];
  115623. break;
  115624. case 41:
  115625. this.$ = $$[$0];
  115626. break;
  115627. case 42:
  115628. this.$ = yy.preparePath(true, $$[$0], this._$);
  115629. break;
  115630. case 43:
  115631. this.$ = yy.preparePath(false, $$[$0], this._$);
  115632. break;
  115633. case 44:
  115634. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  115635. break;
  115636. case 45:
  115637. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  115638. break;
  115639. case 46:
  115640. this.$ = [];
  115641. break;
  115642. case 47:
  115643. $$[$0 - 1].push($$[$0]);
  115644. break;
  115645. case 48:
  115646. this.$ = [$$[$0]];
  115647. break;
  115648. case 49:
  115649. $$[$0 - 1].push($$[$0]);
  115650. break;
  115651. case 50:
  115652. this.$ = [];
  115653. break;
  115654. case 51:
  115655. $$[$0 - 1].push($$[$0]);
  115656. break;
  115657. case 58:
  115658. this.$ = [];
  115659. break;
  115660. case 59:
  115661. $$[$0 - 1].push($$[$0]);
  115662. break;
  115663. case 64:
  115664. this.$ = [];
  115665. break;
  115666. case 65:
  115667. $$[$0 - 1].push($$[$0]);
  115668. break;
  115669. case 70:
  115670. this.$ = [];
  115671. break;
  115672. case 71:
  115673. $$[$0 - 1].push($$[$0]);
  115674. break;
  115675. case 78:
  115676. this.$ = [];
  115677. break;
  115678. case 79:
  115679. $$[$0 - 1].push($$[$0]);
  115680. break;
  115681. case 82:
  115682. this.$ = [];
  115683. break;
  115684. case 83:
  115685. $$[$0 - 1].push($$[$0]);
  115686. break;
  115687. case 86:
  115688. this.$ = [];
  115689. break;
  115690. case 87:
  115691. $$[$0 - 1].push($$[$0]);
  115692. break;
  115693. case 90:
  115694. this.$ = [];
  115695. break;
  115696. case 91:
  115697. $$[$0 - 1].push($$[$0]);
  115698. break;
  115699. case 94:
  115700. this.$ = [];
  115701. break;
  115702. case 95:
  115703. $$[$0 - 1].push($$[$0]);
  115704. break;
  115705. case 98:
  115706. this.$ = [$$[$0]];
  115707. break;
  115708. case 99:
  115709. $$[$0 - 1].push($$[$0]);
  115710. break;
  115711. case 100:
  115712. this.$ = [$$[$0]];
  115713. break;
  115714. case 101:
  115715. $$[$0 - 1].push($$[$0]);
  115716. break;
  115717. }
  115718. },
  115719. 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], 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] }],
  115720. 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] },
  115721. parseError: function parseError(str, hash) {
  115722. throw new Error(str);
  115723. },
  115724. parse: function parse(input) {
  115725. var self = this,
  115726. stack = [0],
  115727. vstack = [null],
  115728. lstack = [],
  115729. table = this.table,
  115730. yytext = "",
  115731. yylineno = 0,
  115732. yyleng = 0,
  115733. recovering = 0,
  115734. TERROR = 2,
  115735. EOF = 1;
  115736. this.lexer.setInput(input);
  115737. this.lexer.yy = this.yy;
  115738. this.yy.lexer = this.lexer;
  115739. this.yy.parser = this;
  115740. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  115741. var yyloc = this.lexer.yylloc;
  115742. lstack.push(yyloc);
  115743. var ranges = this.lexer.options && this.lexer.options.ranges;
  115744. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  115745. function popStack(n) {
  115746. stack.length = stack.length - 2 * n;
  115747. vstack.length = vstack.length - n;
  115748. lstack.length = lstack.length - n;
  115749. }
  115750. function lex() {
  115751. var token;
  115752. token = self.lexer.lex() || 1;
  115753. if (typeof token !== "number") {
  115754. token = self.symbols_[token] || token;
  115755. }
  115756. return token;
  115757. }
  115758. var symbol,
  115759. preErrorSymbol,
  115760. state,
  115761. action,
  115762. a,
  115763. r,
  115764. yyval = {},
  115765. p,
  115766. len,
  115767. newState,
  115768. expected;
  115769. while (true) {
  115770. state = stack[stack.length - 1];
  115771. if (this.defaultActions[state]) {
  115772. action = this.defaultActions[state];
  115773. } else {
  115774. if (symbol === null || typeof symbol == "undefined") {
  115775. symbol = lex();
  115776. }
  115777. action = table[state] && table[state][symbol];
  115778. }
  115779. if (typeof action === "undefined" || !action.length || !action[0]) {
  115780. var errStr = "";
  115781. if (!recovering) {
  115782. expected = [];
  115783. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  115784. expected.push("'" + this.terminals_[p] + "'");
  115785. }
  115786. if (this.lexer.showPosition) {
  115787. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  115788. } else {
  115789. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  115790. }
  115791. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  115792. }
  115793. }
  115794. if (action[0] instanceof Array && action.length > 1) {
  115795. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  115796. }
  115797. switch (action[0]) {
  115798. case 1:
  115799. stack.push(symbol);
  115800. vstack.push(this.lexer.yytext);
  115801. lstack.push(this.lexer.yylloc);
  115802. stack.push(action[1]);
  115803. symbol = null;
  115804. if (!preErrorSymbol) {
  115805. yyleng = this.lexer.yyleng;
  115806. yytext = this.lexer.yytext;
  115807. yylineno = this.lexer.yylineno;
  115808. yyloc = this.lexer.yylloc;
  115809. if (recovering > 0) recovering--;
  115810. } else {
  115811. symbol = preErrorSymbol;
  115812. preErrorSymbol = null;
  115813. }
  115814. break;
  115815. case 2:
  115816. len = this.productions_[action[1]][1];
  115817. yyval.$ = vstack[vstack.length - len];
  115818. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  115819. if (ranges) {
  115820. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  115821. }
  115822. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  115823. if (typeof r !== "undefined") {
  115824. return r;
  115825. }
  115826. if (len) {
  115827. stack = stack.slice(0, -1 * len * 2);
  115828. vstack = vstack.slice(0, -1 * len);
  115829. lstack = lstack.slice(0, -1 * len);
  115830. }
  115831. stack.push(this.productions_[action[1]][0]);
  115832. vstack.push(yyval.$);
  115833. lstack.push(yyval._$);
  115834. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  115835. stack.push(newState);
  115836. break;
  115837. case 3:
  115838. return true;
  115839. }
  115840. }
  115841. return true;
  115842. }
  115843. };
  115844. /* Jison generated lexer */
  115845. var lexer = (function () {
  115846. var lexer = { EOF: 1,
  115847. parseError: function parseError(str, hash) {
  115848. if (this.yy.parser) {
  115849. this.yy.parser.parseError(str, hash);
  115850. } else {
  115851. throw new Error(str);
  115852. }
  115853. },
  115854. setInput: function setInput(input) {
  115855. this._input = input;
  115856. this._more = this._less = this.done = false;
  115857. this.yylineno = this.yyleng = 0;
  115858. this.yytext = this.matched = this.match = '';
  115859. this.conditionStack = ['INITIAL'];
  115860. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  115861. if (this.options.ranges) this.yylloc.range = [0, 0];
  115862. this.offset = 0;
  115863. return this;
  115864. },
  115865. input: function input() {
  115866. var ch = this._input[0];
  115867. this.yytext += ch;
  115868. this.yyleng++;
  115869. this.offset++;
  115870. this.match += ch;
  115871. this.matched += ch;
  115872. var lines = ch.match(/(?:\r\n?|\n).*/g);
  115873. if (lines) {
  115874. this.yylineno++;
  115875. this.yylloc.last_line++;
  115876. } else {
  115877. this.yylloc.last_column++;
  115878. }
  115879. if (this.options.ranges) this.yylloc.range[1]++;
  115880. this._input = this._input.slice(1);
  115881. return ch;
  115882. },
  115883. unput: function unput(ch) {
  115884. var len = ch.length;
  115885. var lines = ch.split(/(?:\r\n?|\n)/g);
  115886. this._input = ch + this._input;
  115887. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  115888. //this.yyleng -= len;
  115889. this.offset -= len;
  115890. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  115891. this.match = this.match.substr(0, this.match.length - 1);
  115892. this.matched = this.matched.substr(0, this.matched.length - 1);
  115893. if (lines.length - 1) this.yylineno -= lines.length - 1;
  115894. var r = this.yylloc.range;
  115895. this.yylloc = { first_line: this.yylloc.first_line,
  115896. last_line: this.yylineno + 1,
  115897. first_column: this.yylloc.first_column,
  115898. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  115899. };
  115900. if (this.options.ranges) {
  115901. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  115902. }
  115903. return this;
  115904. },
  115905. more: function more() {
  115906. this._more = true;
  115907. return this;
  115908. },
  115909. less: function less(n) {
  115910. this.unput(this.match.slice(n));
  115911. },
  115912. pastInput: function pastInput() {
  115913. var past = this.matched.substr(0, this.matched.length - this.match.length);
  115914. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  115915. },
  115916. upcomingInput: function upcomingInput() {
  115917. var next = this.match;
  115918. if (next.length < 20) {
  115919. next += this._input.substr(0, 20 - next.length);
  115920. }
  115921. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  115922. },
  115923. showPosition: function showPosition() {
  115924. var pre = this.pastInput();
  115925. var c = new Array(pre.length + 1).join("-");
  115926. return pre + this.upcomingInput() + "\n" + c + "^";
  115927. },
  115928. next: function next() {
  115929. if (this.done) {
  115930. return this.EOF;
  115931. }
  115932. if (!this._input) this.done = true;
  115933. var token, match, tempMatch, index, col, lines;
  115934. if (!this._more) {
  115935. this.yytext = '';
  115936. this.match = '';
  115937. }
  115938. var rules = this._currentRules();
  115939. for (var i = 0; i < rules.length; i++) {
  115940. tempMatch = this._input.match(this.rules[rules[i]]);
  115941. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  115942. match = tempMatch;
  115943. index = i;
  115944. if (!this.options.flex) break;
  115945. }
  115946. }
  115947. if (match) {
  115948. lines = match[0].match(/(?:\r\n?|\n).*/g);
  115949. if (lines) this.yylineno += lines.length;
  115950. this.yylloc = { first_line: this.yylloc.last_line,
  115951. last_line: this.yylineno + 1,
  115952. first_column: this.yylloc.last_column,
  115953. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  115954. this.yytext += match[0];
  115955. this.match += match[0];
  115956. this.matches = match;
  115957. this.yyleng = this.yytext.length;
  115958. if (this.options.ranges) {
  115959. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  115960. }
  115961. this._more = false;
  115962. this._input = this._input.slice(match[0].length);
  115963. this.matched += match[0];
  115964. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  115965. if (this.done && this._input) this.done = false;
  115966. if (token) return token;else return;
  115967. }
  115968. if (this._input === "") {
  115969. return this.EOF;
  115970. } else {
  115971. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  115972. }
  115973. },
  115974. lex: function lex() {
  115975. var r = this.next();
  115976. if (typeof r !== 'undefined') {
  115977. return r;
  115978. } else {
  115979. return this.lex();
  115980. }
  115981. },
  115982. begin: function begin(condition) {
  115983. this.conditionStack.push(condition);
  115984. },
  115985. popState: function popState() {
  115986. return this.conditionStack.pop();
  115987. },
  115988. _currentRules: function _currentRules() {
  115989. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  115990. },
  115991. topState: function topState() {
  115992. return this.conditionStack[this.conditionStack.length - 2];
  115993. },
  115994. pushState: function begin(condition) {
  115995. this.begin(condition);
  115996. } };
  115997. lexer.options = {};
  115998. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  115999. /**/) {
  116000. function strip(start, end) {
  116001. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  116002. }
  116003. var YYSTATE = YY_START;
  116004. switch ($avoiding_name_collisions) {
  116005. case 0:
  116006. if (yy_.yytext.slice(-2) === "\\\\") {
  116007. strip(0, 1);
  116008. this.begin("mu");
  116009. } else if (yy_.yytext.slice(-1) === "\\") {
  116010. strip(0, 1);
  116011. this.begin("emu");
  116012. } else {
  116013. this.begin("mu");
  116014. }
  116015. if (yy_.yytext) return 15;
  116016. break;
  116017. case 1:
  116018. return 15;
  116019. break;
  116020. case 2:
  116021. this.popState();
  116022. return 15;
  116023. break;
  116024. case 3:
  116025. this.begin('raw');return 15;
  116026. break;
  116027. case 4:
  116028. this.popState();
  116029. // Should be using `this.topState()` below, but it currently
  116030. // returns the second top instead of the first top. Opened an
  116031. // issue about it at https://github.com/zaach/jison/issues/291
  116032. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  116033. return 15;
  116034. } else {
  116035. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  116036. return 'END_RAW_BLOCK';
  116037. }
  116038. break;
  116039. case 5:
  116040. return 15;
  116041. break;
  116042. case 6:
  116043. this.popState();
  116044. return 14;
  116045. break;
  116046. case 7:
  116047. return 65;
  116048. break;
  116049. case 8:
  116050. return 68;
  116051. break;
  116052. case 9:
  116053. return 19;
  116054. break;
  116055. case 10:
  116056. this.popState();
  116057. this.begin('raw');
  116058. return 23;
  116059. break;
  116060. case 11:
  116061. return 55;
  116062. break;
  116063. case 12:
  116064. return 60;
  116065. break;
  116066. case 13:
  116067. return 29;
  116068. break;
  116069. case 14:
  116070. return 47;
  116071. break;
  116072. case 15:
  116073. this.popState();return 44;
  116074. break;
  116075. case 16:
  116076. this.popState();return 44;
  116077. break;
  116078. case 17:
  116079. return 34;
  116080. break;
  116081. case 18:
  116082. return 39;
  116083. break;
  116084. case 19:
  116085. return 51;
  116086. break;
  116087. case 20:
  116088. return 48;
  116089. break;
  116090. case 21:
  116091. this.unput(yy_.yytext);
  116092. this.popState();
  116093. this.begin('com');
  116094. break;
  116095. case 22:
  116096. this.popState();
  116097. return 14;
  116098. break;
  116099. case 23:
  116100. return 48;
  116101. break;
  116102. case 24:
  116103. return 73;
  116104. break;
  116105. case 25:
  116106. return 72;
  116107. break;
  116108. case 26:
  116109. return 72;
  116110. break;
  116111. case 27:
  116112. return 87;
  116113. break;
  116114. case 28:
  116115. // ignore whitespace
  116116. break;
  116117. case 29:
  116118. this.popState();return 54;
  116119. break;
  116120. case 30:
  116121. this.popState();return 33;
  116122. break;
  116123. case 31:
  116124. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  116125. break;
  116126. case 32:
  116127. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  116128. break;
  116129. case 33:
  116130. return 85;
  116131. break;
  116132. case 34:
  116133. return 82;
  116134. break;
  116135. case 35:
  116136. return 82;
  116137. break;
  116138. case 36:
  116139. return 83;
  116140. break;
  116141. case 37:
  116142. return 84;
  116143. break;
  116144. case 38:
  116145. return 81;
  116146. break;
  116147. case 39:
  116148. return 75;
  116149. break;
  116150. case 40:
  116151. return 77;
  116152. break;
  116153. case 41:
  116154. return 72;
  116155. break;
  116156. case 42:
  116157. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  116158. break;
  116159. case 43:
  116160. return 'INVALID';
  116161. break;
  116162. case 44:
  116163. return 5;
  116164. break;
  116165. }
  116166. };
  116167. lexer.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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  116168. lexer.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": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  116169. return lexer;
  116170. })();
  116171. parser.lexer = lexer;
  116172. function Parser() {
  116173. this.yy = {};
  116174. }Parser.prototype = parser;parser.Parser = Parser;
  116175. return new Parser();
  116176. })();exports["default"] = handlebars;
  116177. module.exports = exports["default"];
  116178. /***/ }),
  116179. /* 38 */
  116180. /***/ (function(module, exports, __webpack_require__) {
  116181. 'use strict';
  116182. var _interopRequireDefault = __webpack_require__(1)['default'];
  116183. exports.__esModule = true;
  116184. var _visitor = __webpack_require__(39);
  116185. var _visitor2 = _interopRequireDefault(_visitor);
  116186. function WhitespaceControl() {
  116187. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  116188. this.options = options;
  116189. }
  116190. WhitespaceControl.prototype = new _visitor2['default']();
  116191. WhitespaceControl.prototype.Program = function (program) {
  116192. var doStandalone = !this.options.ignoreStandalone;
  116193. var isRoot = !this.isRootSeen;
  116194. this.isRootSeen = true;
  116195. var body = program.body;
  116196. for (var i = 0, l = body.length; i < l; i++) {
  116197. var current = body[i],
  116198. strip = this.accept(current);
  116199. if (!strip) {
  116200. continue;
  116201. }
  116202. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  116203. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  116204. openStandalone = strip.openStandalone && _isPrevWhitespace,
  116205. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  116206. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  116207. if (strip.close) {
  116208. omitRight(body, i, true);
  116209. }
  116210. if (strip.open) {
  116211. omitLeft(body, i, true);
  116212. }
  116213. if (doStandalone && inlineStandalone) {
  116214. omitRight(body, i);
  116215. if (omitLeft(body, i)) {
  116216. // If we are on a standalone node, save the indent info for partials
  116217. if (current.type === 'PartialStatement') {
  116218. // Pull out the whitespace from the final line
  116219. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  116220. }
  116221. }
  116222. }
  116223. if (doStandalone && openStandalone) {
  116224. omitRight((current.program || current.inverse).body);
  116225. // Strip out the previous content node if it's whitespace only
  116226. omitLeft(body, i);
  116227. }
  116228. if (doStandalone && closeStandalone) {
  116229. // Always strip the next node
  116230. omitRight(body, i);
  116231. omitLeft((current.inverse || current.program).body);
  116232. }
  116233. }
  116234. return program;
  116235. };
  116236. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  116237. this.accept(block.program);
  116238. this.accept(block.inverse);
  116239. // Find the inverse program that is involed with whitespace stripping.
  116240. var program = block.program || block.inverse,
  116241. inverse = block.program && block.inverse,
  116242. firstInverse = inverse,
  116243. lastInverse = inverse;
  116244. if (inverse && inverse.chained) {
  116245. firstInverse = inverse.body[0].program;
  116246. // Walk the inverse chain to find the last inverse that is actually in the chain.
  116247. while (lastInverse.chained) {
  116248. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  116249. }
  116250. }
  116251. var strip = {
  116252. open: block.openStrip.open,
  116253. close: block.closeStrip.close,
  116254. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  116255. // so our parent can determine if we actually are standalone
  116256. openStandalone: isNextWhitespace(program.body),
  116257. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  116258. };
  116259. if (block.openStrip.close) {
  116260. omitRight(program.body, null, true);
  116261. }
  116262. if (inverse) {
  116263. var inverseStrip = block.inverseStrip;
  116264. if (inverseStrip.open) {
  116265. omitLeft(program.body, null, true);
  116266. }
  116267. if (inverseStrip.close) {
  116268. omitRight(firstInverse.body, null, true);
  116269. }
  116270. if (block.closeStrip.open) {
  116271. omitLeft(lastInverse.body, null, true);
  116272. }
  116273. // Find standalone else statments
  116274. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  116275. omitLeft(program.body);
  116276. omitRight(firstInverse.body);
  116277. }
  116278. } else if (block.closeStrip.open) {
  116279. omitLeft(program.body, null, true);
  116280. }
  116281. return strip;
  116282. };
  116283. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  116284. return mustache.strip;
  116285. };
  116286. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  116287. /* istanbul ignore next */
  116288. var strip = node.strip || {};
  116289. return {
  116290. inlineStandalone: true,
  116291. open: strip.open,
  116292. close: strip.close
  116293. };
  116294. };
  116295. function isPrevWhitespace(body, i, isRoot) {
  116296. if (i === undefined) {
  116297. i = body.length;
  116298. }
  116299. // Nodes that end with newlines are considered whitespace (but are special
  116300. // cased for strip operations)
  116301. var prev = body[i - 1],
  116302. sibling = body[i - 2];
  116303. if (!prev) {
  116304. return isRoot;
  116305. }
  116306. if (prev.type === 'ContentStatement') {
  116307. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  116308. }
  116309. }
  116310. function isNextWhitespace(body, i, isRoot) {
  116311. if (i === undefined) {
  116312. i = -1;
  116313. }
  116314. var next = body[i + 1],
  116315. sibling = body[i + 2];
  116316. if (!next) {
  116317. return isRoot;
  116318. }
  116319. if (next.type === 'ContentStatement') {
  116320. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  116321. }
  116322. }
  116323. // Marks the node to the right of the position as omitted.
  116324. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  116325. //
  116326. // If i is undefined, then the first child will be marked as such.
  116327. //
  116328. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  116329. // content is met.
  116330. function omitRight(body, i, multiple) {
  116331. var current = body[i == null ? 0 : i + 1];
  116332. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  116333. return;
  116334. }
  116335. var original = current.value;
  116336. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  116337. current.rightStripped = current.value !== original;
  116338. }
  116339. // Marks the node to the left of the position as omitted.
  116340. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  116341. //
  116342. // If i is undefined then the last child will be marked as such.
  116343. //
  116344. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  116345. // content is met.
  116346. function omitLeft(body, i, multiple) {
  116347. var current = body[i == null ? body.length - 1 : i - 1];
  116348. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  116349. return;
  116350. }
  116351. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  116352. var original = current.value;
  116353. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  116354. current.leftStripped = current.value !== original;
  116355. return current.leftStripped;
  116356. }
  116357. exports['default'] = WhitespaceControl;
  116358. module.exports = exports['default'];
  116359. /***/ }),
  116360. /* 39 */
  116361. /***/ (function(module, exports, __webpack_require__) {
  116362. 'use strict';
  116363. var _interopRequireDefault = __webpack_require__(1)['default'];
  116364. exports.__esModule = true;
  116365. var _exception = __webpack_require__(6);
  116366. var _exception2 = _interopRequireDefault(_exception);
  116367. function Visitor() {
  116368. this.parents = [];
  116369. }
  116370. Visitor.prototype = {
  116371. constructor: Visitor,
  116372. mutating: false,
  116373. // Visits a given value. If mutating, will replace the value if necessary.
  116374. acceptKey: function acceptKey(node, name) {
  116375. var value = this.accept(node[name]);
  116376. if (this.mutating) {
  116377. // Hacky sanity check: This may have a few false positives for type for the helper
  116378. // methods but will generally do the right thing without a lot of overhead.
  116379. if (value && !Visitor.prototype[value.type]) {
  116380. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  116381. }
  116382. node[name] = value;
  116383. }
  116384. },
  116385. // Performs an accept operation with added sanity check to ensure
  116386. // required keys are not removed.
  116387. acceptRequired: function acceptRequired(node, name) {
  116388. this.acceptKey(node, name);
  116389. if (!node[name]) {
  116390. throw new _exception2['default'](node.type + ' requires ' + name);
  116391. }
  116392. },
  116393. // Traverses a given array. If mutating, empty respnses will be removed
  116394. // for child elements.
  116395. acceptArray: function acceptArray(array) {
  116396. for (var i = 0, l = array.length; i < l; i++) {
  116397. this.acceptKey(array, i);
  116398. if (!array[i]) {
  116399. array.splice(i, 1);
  116400. i--;
  116401. l--;
  116402. }
  116403. }
  116404. },
  116405. accept: function accept(object) {
  116406. if (!object) {
  116407. return;
  116408. }
  116409. /* istanbul ignore next: Sanity code */
  116410. if (!this[object.type]) {
  116411. throw new _exception2['default']('Unknown type: ' + object.type, object);
  116412. }
  116413. if (this.current) {
  116414. this.parents.unshift(this.current);
  116415. }
  116416. this.current = object;
  116417. var ret = this[object.type](object);
  116418. this.current = this.parents.shift();
  116419. if (!this.mutating || ret) {
  116420. return ret;
  116421. } else if (ret !== false) {
  116422. return object;
  116423. }
  116424. },
  116425. Program: function Program(program) {
  116426. this.acceptArray(program.body);
  116427. },
  116428. MustacheStatement: visitSubExpression,
  116429. Decorator: visitSubExpression,
  116430. BlockStatement: visitBlock,
  116431. DecoratorBlock: visitBlock,
  116432. PartialStatement: visitPartial,
  116433. PartialBlockStatement: function PartialBlockStatement(partial) {
  116434. visitPartial.call(this, partial);
  116435. this.acceptKey(partial, 'program');
  116436. },
  116437. ContentStatement: function ContentStatement() /* content */{},
  116438. CommentStatement: function CommentStatement() /* comment */{},
  116439. SubExpression: visitSubExpression,
  116440. PathExpression: function PathExpression() /* path */{},
  116441. StringLiteral: function StringLiteral() /* string */{},
  116442. NumberLiteral: function NumberLiteral() /* number */{},
  116443. BooleanLiteral: function BooleanLiteral() /* bool */{},
  116444. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  116445. NullLiteral: function NullLiteral() /* literal */{},
  116446. Hash: function Hash(hash) {
  116447. this.acceptArray(hash.pairs);
  116448. },
  116449. HashPair: function HashPair(pair) {
  116450. this.acceptRequired(pair, 'value');
  116451. }
  116452. };
  116453. function visitSubExpression(mustache) {
  116454. this.acceptRequired(mustache, 'path');
  116455. this.acceptArray(mustache.params);
  116456. this.acceptKey(mustache, 'hash');
  116457. }
  116458. function visitBlock(block) {
  116459. visitSubExpression.call(this, block);
  116460. this.acceptKey(block, 'program');
  116461. this.acceptKey(block, 'inverse');
  116462. }
  116463. function visitPartial(partial) {
  116464. this.acceptRequired(partial, 'name');
  116465. this.acceptArray(partial.params);
  116466. this.acceptKey(partial, 'hash');
  116467. }
  116468. exports['default'] = Visitor;
  116469. module.exports = exports['default'];
  116470. /***/ }),
  116471. /* 40 */
  116472. /***/ (function(module, exports, __webpack_require__) {
  116473. 'use strict';
  116474. var _interopRequireDefault = __webpack_require__(1)['default'];
  116475. exports.__esModule = true;
  116476. exports.SourceLocation = SourceLocation;
  116477. exports.id = id;
  116478. exports.stripFlags = stripFlags;
  116479. exports.stripComment = stripComment;
  116480. exports.preparePath = preparePath;
  116481. exports.prepareMustache = prepareMustache;
  116482. exports.prepareRawBlock = prepareRawBlock;
  116483. exports.prepareBlock = prepareBlock;
  116484. exports.prepareProgram = prepareProgram;
  116485. exports.preparePartialBlock = preparePartialBlock;
  116486. var _exception = __webpack_require__(6);
  116487. var _exception2 = _interopRequireDefault(_exception);
  116488. function validateClose(open, close) {
  116489. close = close.path ? close.path.original : close;
  116490. if (open.path.original !== close) {
  116491. var errorNode = { loc: open.path.loc };
  116492. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  116493. }
  116494. }
  116495. function SourceLocation(source, locInfo) {
  116496. this.source = source;
  116497. this.start = {
  116498. line: locInfo.first_line,
  116499. column: locInfo.first_column
  116500. };
  116501. this.end = {
  116502. line: locInfo.last_line,
  116503. column: locInfo.last_column
  116504. };
  116505. }
  116506. function id(token) {
  116507. if (/^\[.*\]$/.test(token)) {
  116508. return token.substr(1, token.length - 2);
  116509. } else {
  116510. return token;
  116511. }
  116512. }
  116513. function stripFlags(open, close) {
  116514. return {
  116515. open: open.charAt(2) === '~',
  116516. close: close.charAt(close.length - 3) === '~'
  116517. };
  116518. }
  116519. function stripComment(comment) {
  116520. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  116521. }
  116522. function preparePath(data, parts, loc) {
  116523. loc = this.locInfo(loc);
  116524. var original = data ? '@' : '',
  116525. dig = [],
  116526. depth = 0,
  116527. depthString = '';
  116528. for (var i = 0, l = parts.length; i < l; i++) {
  116529. var part = parts[i].part,
  116530. // If we have [] syntax then we do not treat path references as operators,
  116531. // i.e. foo.[this] resolves to approximately context.foo['this']
  116532. isLiteral = parts[i].original !== part;
  116533. original += (parts[i].separator || '') + part;
  116534. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  116535. if (dig.length > 0) {
  116536. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  116537. } else if (part === '..') {
  116538. depth++;
  116539. depthString += '../';
  116540. }
  116541. } else {
  116542. dig.push(part);
  116543. }
  116544. }
  116545. return {
  116546. type: 'PathExpression',
  116547. data: data,
  116548. depth: depth,
  116549. parts: dig,
  116550. original: original,
  116551. loc: loc
  116552. };
  116553. }
  116554. function prepareMustache(path, params, hash, open, strip, locInfo) {
  116555. // Must use charAt to support IE pre-10
  116556. var escapeFlag = open.charAt(3) || open.charAt(2),
  116557. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  116558. var decorator = /\*/.test(open);
  116559. return {
  116560. type: decorator ? 'Decorator' : 'MustacheStatement',
  116561. path: path,
  116562. params: params,
  116563. hash: hash,
  116564. escaped: escaped,
  116565. strip: strip,
  116566. loc: this.locInfo(locInfo)
  116567. };
  116568. }
  116569. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  116570. validateClose(openRawBlock, close);
  116571. locInfo = this.locInfo(locInfo);
  116572. var program = {
  116573. type: 'Program',
  116574. body: contents,
  116575. strip: {},
  116576. loc: locInfo
  116577. };
  116578. return {
  116579. type: 'BlockStatement',
  116580. path: openRawBlock.path,
  116581. params: openRawBlock.params,
  116582. hash: openRawBlock.hash,
  116583. program: program,
  116584. openStrip: {},
  116585. inverseStrip: {},
  116586. closeStrip: {},
  116587. loc: locInfo
  116588. };
  116589. }
  116590. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  116591. if (close && close.path) {
  116592. validateClose(openBlock, close);
  116593. }
  116594. var decorator = /\*/.test(openBlock.open);
  116595. program.blockParams = openBlock.blockParams;
  116596. var inverse = undefined,
  116597. inverseStrip = undefined;
  116598. if (inverseAndProgram) {
  116599. if (decorator) {
  116600. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  116601. }
  116602. if (inverseAndProgram.chain) {
  116603. inverseAndProgram.program.body[0].closeStrip = close.strip;
  116604. }
  116605. inverseStrip = inverseAndProgram.strip;
  116606. inverse = inverseAndProgram.program;
  116607. }
  116608. if (inverted) {
  116609. inverted = inverse;
  116610. inverse = program;
  116611. program = inverted;
  116612. }
  116613. return {
  116614. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  116615. path: openBlock.path,
  116616. params: openBlock.params,
  116617. hash: openBlock.hash,
  116618. program: program,
  116619. inverse: inverse,
  116620. openStrip: openBlock.strip,
  116621. inverseStrip: inverseStrip,
  116622. closeStrip: close && close.strip,
  116623. loc: this.locInfo(locInfo)
  116624. };
  116625. }
  116626. function prepareProgram(statements, loc) {
  116627. if (!loc && statements.length) {
  116628. var firstLoc = statements[0].loc,
  116629. lastLoc = statements[statements.length - 1].loc;
  116630. /* istanbul ignore else */
  116631. if (firstLoc && lastLoc) {
  116632. loc = {
  116633. source: firstLoc.source,
  116634. start: {
  116635. line: firstLoc.start.line,
  116636. column: firstLoc.start.column
  116637. },
  116638. end: {
  116639. line: lastLoc.end.line,
  116640. column: lastLoc.end.column
  116641. }
  116642. };
  116643. }
  116644. }
  116645. return {
  116646. type: 'Program',
  116647. body: statements,
  116648. strip: {},
  116649. loc: loc
  116650. };
  116651. }
  116652. function preparePartialBlock(open, program, close, locInfo) {
  116653. validateClose(open, close);
  116654. return {
  116655. type: 'PartialBlockStatement',
  116656. name: open.path,
  116657. params: open.params,
  116658. hash: open.hash,
  116659. program: program,
  116660. openStrip: open.strip,
  116661. closeStrip: close && close.strip,
  116662. loc: this.locInfo(locInfo)
  116663. };
  116664. }
  116665. /***/ }),
  116666. /* 41 */
  116667. /***/ (function(module, exports, __webpack_require__) {
  116668. /* eslint-disable new-cap */
  116669. 'use strict';
  116670. var _interopRequireDefault = __webpack_require__(1)['default'];
  116671. exports.__esModule = true;
  116672. exports.Compiler = Compiler;
  116673. exports.precompile = precompile;
  116674. exports.compile = compile;
  116675. var _exception = __webpack_require__(6);
  116676. var _exception2 = _interopRequireDefault(_exception);
  116677. var _utils = __webpack_require__(5);
  116678. var _ast = __webpack_require__(35);
  116679. var _ast2 = _interopRequireDefault(_ast);
  116680. var slice = [].slice;
  116681. function Compiler() {}
  116682. // the foundHelper register will disambiguate helper lookup from finding a
  116683. // function in a context. This is necessary for mustache compatibility, which
  116684. // requires that context functions in blocks are evaluated by blockHelperMissing,
  116685. // and then proceed as if the resulting value was provided to blockHelperMissing.
  116686. Compiler.prototype = {
  116687. compiler: Compiler,
  116688. equals: function equals(other) {
  116689. var len = this.opcodes.length;
  116690. if (other.opcodes.length !== len) {
  116691. return false;
  116692. }
  116693. for (var i = 0; i < len; i++) {
  116694. var opcode = this.opcodes[i],
  116695. otherOpcode = other.opcodes[i];
  116696. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  116697. return false;
  116698. }
  116699. }
  116700. // We know that length is the same between the two arrays because they are directly tied
  116701. // to the opcode behavior above.
  116702. len = this.children.length;
  116703. for (var i = 0; i < len; i++) {
  116704. if (!this.children[i].equals(other.children[i])) {
  116705. return false;
  116706. }
  116707. }
  116708. return true;
  116709. },
  116710. guid: 0,
  116711. compile: function compile(program, options) {
  116712. this.sourceNode = [];
  116713. this.opcodes = [];
  116714. this.children = [];
  116715. this.options = options;
  116716. this.stringParams = options.stringParams;
  116717. this.trackIds = options.trackIds;
  116718. options.blockParams = options.blockParams || [];
  116719. // These changes will propagate to the other compiler components
  116720. var knownHelpers = options.knownHelpers;
  116721. options.knownHelpers = {
  116722. 'helperMissing': true,
  116723. 'blockHelperMissing': true,
  116724. 'each': true,
  116725. 'if': true,
  116726. 'unless': true,
  116727. 'with': true,
  116728. 'log': true,
  116729. 'lookup': true
  116730. };
  116731. if (knownHelpers) {
  116732. for (var _name in knownHelpers) {
  116733. /* istanbul ignore else */
  116734. if (_name in knownHelpers) {
  116735. this.options.knownHelpers[_name] = knownHelpers[_name];
  116736. }
  116737. }
  116738. }
  116739. return this.accept(program);
  116740. },
  116741. compileProgram: function compileProgram(program) {
  116742. var childCompiler = new this.compiler(),
  116743. // eslint-disable-line new-cap
  116744. result = childCompiler.compile(program, this.options),
  116745. guid = this.guid++;
  116746. this.usePartial = this.usePartial || result.usePartial;
  116747. this.children[guid] = result;
  116748. this.useDepths = this.useDepths || result.useDepths;
  116749. return guid;
  116750. },
  116751. accept: function accept(node) {
  116752. /* istanbul ignore next: Sanity code */
  116753. if (!this[node.type]) {
  116754. throw new _exception2['default']('Unknown type: ' + node.type, node);
  116755. }
  116756. this.sourceNode.unshift(node);
  116757. var ret = this[node.type](node);
  116758. this.sourceNode.shift();
  116759. return ret;
  116760. },
  116761. Program: function Program(program) {
  116762. this.options.blockParams.unshift(program.blockParams);
  116763. var body = program.body,
  116764. bodyLength = body.length;
  116765. for (var i = 0; i < bodyLength; i++) {
  116766. this.accept(body[i]);
  116767. }
  116768. this.options.blockParams.shift();
  116769. this.isSimple = bodyLength === 1;
  116770. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  116771. return this;
  116772. },
  116773. BlockStatement: function BlockStatement(block) {
  116774. transformLiteralToPath(block);
  116775. var program = block.program,
  116776. inverse = block.inverse;
  116777. program = program && this.compileProgram(program);
  116778. inverse = inverse && this.compileProgram(inverse);
  116779. var type = this.classifySexpr(block);
  116780. if (type === 'helper') {
  116781. this.helperSexpr(block, program, inverse);
  116782. } else if (type === 'simple') {
  116783. this.simpleSexpr(block);
  116784. // now that the simple mustache is resolved, we need to
  116785. // evaluate it by executing `blockHelperMissing`
  116786. this.opcode('pushProgram', program);
  116787. this.opcode('pushProgram', inverse);
  116788. this.opcode('emptyHash');
  116789. this.opcode('blockValue', block.path.original);
  116790. } else {
  116791. this.ambiguousSexpr(block, program, inverse);
  116792. // now that the simple mustache is resolved, we need to
  116793. // evaluate it by executing `blockHelperMissing`
  116794. this.opcode('pushProgram', program);
  116795. this.opcode('pushProgram', inverse);
  116796. this.opcode('emptyHash');
  116797. this.opcode('ambiguousBlockValue');
  116798. }
  116799. this.opcode('append');
  116800. },
  116801. DecoratorBlock: function DecoratorBlock(decorator) {
  116802. var program = decorator.program && this.compileProgram(decorator.program);
  116803. var params = this.setupFullMustacheParams(decorator, program, undefined),
  116804. path = decorator.path;
  116805. this.useDecorators = true;
  116806. this.opcode('registerDecorator', params.length, path.original);
  116807. },
  116808. PartialStatement: function PartialStatement(partial) {
  116809. this.usePartial = true;
  116810. var program = partial.program;
  116811. if (program) {
  116812. program = this.compileProgram(partial.program);
  116813. }
  116814. var params = partial.params;
  116815. if (params.length > 1) {
  116816. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  116817. } else if (!params.length) {
  116818. if (this.options.explicitPartialContext) {
  116819. this.opcode('pushLiteral', 'undefined');
  116820. } else {
  116821. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  116822. }
  116823. }
  116824. var partialName = partial.name.original,
  116825. isDynamic = partial.name.type === 'SubExpression';
  116826. if (isDynamic) {
  116827. this.accept(partial.name);
  116828. }
  116829. this.setupFullMustacheParams(partial, program, undefined, true);
  116830. var indent = partial.indent || '';
  116831. if (this.options.preventIndent && indent) {
  116832. this.opcode('appendContent', indent);
  116833. indent = '';
  116834. }
  116835. this.opcode('invokePartial', isDynamic, partialName, indent);
  116836. this.opcode('append');
  116837. },
  116838. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  116839. this.PartialStatement(partialBlock);
  116840. },
  116841. MustacheStatement: function MustacheStatement(mustache) {
  116842. this.SubExpression(mustache);
  116843. if (mustache.escaped && !this.options.noEscape) {
  116844. this.opcode('appendEscaped');
  116845. } else {
  116846. this.opcode('append');
  116847. }
  116848. },
  116849. Decorator: function Decorator(decorator) {
  116850. this.DecoratorBlock(decorator);
  116851. },
  116852. ContentStatement: function ContentStatement(content) {
  116853. if (content.value) {
  116854. this.opcode('appendContent', content.value);
  116855. }
  116856. },
  116857. CommentStatement: function CommentStatement() {},
  116858. SubExpression: function SubExpression(sexpr) {
  116859. transformLiteralToPath(sexpr);
  116860. var type = this.classifySexpr(sexpr);
  116861. if (type === 'simple') {
  116862. this.simpleSexpr(sexpr);
  116863. } else if (type === 'helper') {
  116864. this.helperSexpr(sexpr);
  116865. } else {
  116866. this.ambiguousSexpr(sexpr);
  116867. }
  116868. },
  116869. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  116870. var path = sexpr.path,
  116871. name = path.parts[0],
  116872. isBlock = program != null || inverse != null;
  116873. this.opcode('getContext', path.depth);
  116874. this.opcode('pushProgram', program);
  116875. this.opcode('pushProgram', inverse);
  116876. path.strict = true;
  116877. this.accept(path);
  116878. this.opcode('invokeAmbiguous', name, isBlock);
  116879. },
  116880. simpleSexpr: function simpleSexpr(sexpr) {
  116881. var path = sexpr.path;
  116882. path.strict = true;
  116883. this.accept(path);
  116884. this.opcode('resolvePossibleLambda');
  116885. },
  116886. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  116887. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  116888. path = sexpr.path,
  116889. name = path.parts[0];
  116890. if (this.options.knownHelpers[name]) {
  116891. this.opcode('invokeKnownHelper', params.length, name);
  116892. } else if (this.options.knownHelpersOnly) {
  116893. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  116894. } else {
  116895. path.strict = true;
  116896. path.falsy = true;
  116897. this.accept(path);
  116898. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  116899. }
  116900. },
  116901. PathExpression: function PathExpression(path) {
  116902. this.addDepth(path.depth);
  116903. this.opcode('getContext', path.depth);
  116904. var name = path.parts[0],
  116905. scoped = _ast2['default'].helpers.scopedId(path),
  116906. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  116907. if (blockParamId) {
  116908. this.opcode('lookupBlockParam', blockParamId, path.parts);
  116909. } else if (!name) {
  116910. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  116911. this.opcode('pushContext');
  116912. } else if (path.data) {
  116913. this.options.data = true;
  116914. this.opcode('lookupData', path.depth, path.parts, path.strict);
  116915. } else {
  116916. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  116917. }
  116918. },
  116919. StringLiteral: function StringLiteral(string) {
  116920. this.opcode('pushString', string.value);
  116921. },
  116922. NumberLiteral: function NumberLiteral(number) {
  116923. this.opcode('pushLiteral', number.value);
  116924. },
  116925. BooleanLiteral: function BooleanLiteral(bool) {
  116926. this.opcode('pushLiteral', bool.value);
  116927. },
  116928. UndefinedLiteral: function UndefinedLiteral() {
  116929. this.opcode('pushLiteral', 'undefined');
  116930. },
  116931. NullLiteral: function NullLiteral() {
  116932. this.opcode('pushLiteral', 'null');
  116933. },
  116934. Hash: function Hash(hash) {
  116935. var pairs = hash.pairs,
  116936. i = 0,
  116937. l = pairs.length;
  116938. this.opcode('pushHash');
  116939. for (; i < l; i++) {
  116940. this.pushParam(pairs[i].value);
  116941. }
  116942. while (i--) {
  116943. this.opcode('assignToHash', pairs[i].key);
  116944. }
  116945. this.opcode('popHash');
  116946. },
  116947. // HELPERS
  116948. opcode: function opcode(name) {
  116949. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  116950. },
  116951. addDepth: function addDepth(depth) {
  116952. if (!depth) {
  116953. return;
  116954. }
  116955. this.useDepths = true;
  116956. },
  116957. classifySexpr: function classifySexpr(sexpr) {
  116958. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  116959. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  116960. // a mustache is an eligible helper if:
  116961. // * its id is simple (a single part, not `this` or `..`)
  116962. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  116963. // if a mustache is an eligible helper but not a definite
  116964. // helper, it is ambiguous, and will be resolved in a later
  116965. // pass or at runtime.
  116966. var isEligible = !isBlockParam && (isHelper || isSimple);
  116967. // if ambiguous, we can possibly resolve the ambiguity now
  116968. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  116969. if (isEligible && !isHelper) {
  116970. var _name2 = sexpr.path.parts[0],
  116971. options = this.options;
  116972. if (options.knownHelpers[_name2]) {
  116973. isHelper = true;
  116974. } else if (options.knownHelpersOnly) {
  116975. isEligible = false;
  116976. }
  116977. }
  116978. if (isHelper) {
  116979. return 'helper';
  116980. } else if (isEligible) {
  116981. return 'ambiguous';
  116982. } else {
  116983. return 'simple';
  116984. }
  116985. },
  116986. pushParams: function pushParams(params) {
  116987. for (var i = 0, l = params.length; i < l; i++) {
  116988. this.pushParam(params[i]);
  116989. }
  116990. },
  116991. pushParam: function pushParam(val) {
  116992. var value = val.value != null ? val.value : val.original || '';
  116993. if (this.stringParams) {
  116994. if (value.replace) {
  116995. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  116996. }
  116997. if (val.depth) {
  116998. this.addDepth(val.depth);
  116999. }
  117000. this.opcode('getContext', val.depth || 0);
  117001. this.opcode('pushStringParam', value, val.type);
  117002. if (val.type === 'SubExpression') {
  117003. // SubExpressions get evaluated and passed in
  117004. // in string params mode.
  117005. this.accept(val);
  117006. }
  117007. } else {
  117008. if (this.trackIds) {
  117009. var blockParamIndex = undefined;
  117010. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  117011. blockParamIndex = this.blockParamIndex(val.parts[0]);
  117012. }
  117013. if (blockParamIndex) {
  117014. var blockParamChild = val.parts.slice(1).join('.');
  117015. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  117016. } else {
  117017. value = val.original || value;
  117018. if (value.replace) {
  117019. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  117020. }
  117021. this.opcode('pushId', val.type, value);
  117022. }
  117023. }
  117024. this.accept(val);
  117025. }
  117026. },
  117027. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  117028. var params = sexpr.params;
  117029. this.pushParams(params);
  117030. this.opcode('pushProgram', program);
  117031. this.opcode('pushProgram', inverse);
  117032. if (sexpr.hash) {
  117033. this.accept(sexpr.hash);
  117034. } else {
  117035. this.opcode('emptyHash', omitEmpty);
  117036. }
  117037. return params;
  117038. },
  117039. blockParamIndex: function blockParamIndex(name) {
  117040. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  117041. var blockParams = this.options.blockParams[depth],
  117042. param = blockParams && _utils.indexOf(blockParams, name);
  117043. if (blockParams && param >= 0) {
  117044. return [depth, param];
  117045. }
  117046. }
  117047. }
  117048. };
  117049. function precompile(input, options, env) {
  117050. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117051. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  117052. }
  117053. options = options || {};
  117054. if (!('data' in options)) {
  117055. options.data = true;
  117056. }
  117057. if (options.compat) {
  117058. options.useDepths = true;
  117059. }
  117060. var ast = env.parse(input, options),
  117061. environment = new env.Compiler().compile(ast, options);
  117062. return new env.JavaScriptCompiler().compile(environment, options);
  117063. }
  117064. function compile(input, options, env) {
  117065. if (options === undefined) options = {};
  117066. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  117067. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  117068. }
  117069. options = _utils.extend({}, options);
  117070. if (!('data' in options)) {
  117071. options.data = true;
  117072. }
  117073. if (options.compat) {
  117074. options.useDepths = true;
  117075. }
  117076. var compiled = undefined;
  117077. function compileInput() {
  117078. var ast = env.parse(input, options),
  117079. environment = new env.Compiler().compile(ast, options),
  117080. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  117081. return env.template(templateSpec);
  117082. }
  117083. // Template is only compiled on first use and cached after that point.
  117084. function ret(context, execOptions) {
  117085. if (!compiled) {
  117086. compiled = compileInput();
  117087. }
  117088. return compiled.call(this, context, execOptions);
  117089. }
  117090. ret._setup = function (setupOptions) {
  117091. if (!compiled) {
  117092. compiled = compileInput();
  117093. }
  117094. return compiled._setup(setupOptions);
  117095. };
  117096. ret._child = function (i, data, blockParams, depths) {
  117097. if (!compiled) {
  117098. compiled = compileInput();
  117099. }
  117100. return compiled._child(i, data, blockParams, depths);
  117101. };
  117102. return ret;
  117103. }
  117104. function argEquals(a, b) {
  117105. if (a === b) {
  117106. return true;
  117107. }
  117108. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  117109. for (var i = 0; i < a.length; i++) {
  117110. if (!argEquals(a[i], b[i])) {
  117111. return false;
  117112. }
  117113. }
  117114. return true;
  117115. }
  117116. }
  117117. function transformLiteralToPath(sexpr) {
  117118. if (!sexpr.path.parts) {
  117119. var literal = sexpr.path;
  117120. // Casting to string here to make false and 0 literal values play nicely with the rest
  117121. // of the system.
  117122. sexpr.path = {
  117123. type: 'PathExpression',
  117124. data: false,
  117125. depth: 0,
  117126. parts: [literal.original + ''],
  117127. original: literal.original + '',
  117128. loc: literal.loc
  117129. };
  117130. }
  117131. }
  117132. /***/ }),
  117133. /* 42 */
  117134. /***/ (function(module, exports, __webpack_require__) {
  117135. 'use strict';
  117136. var _interopRequireDefault = __webpack_require__(1)['default'];
  117137. exports.__esModule = true;
  117138. var _base = __webpack_require__(4);
  117139. var _exception = __webpack_require__(6);
  117140. var _exception2 = _interopRequireDefault(_exception);
  117141. var _utils = __webpack_require__(5);
  117142. var _codeGen = __webpack_require__(43);
  117143. var _codeGen2 = _interopRequireDefault(_codeGen);
  117144. function Literal(value) {
  117145. this.value = value;
  117146. }
  117147. function JavaScriptCompiler() {}
  117148. JavaScriptCompiler.prototype = {
  117149. // PUBLIC API: You can override these methods in a subclass to provide
  117150. // alternative compiled forms for name lookup and buffering semantics
  117151. nameLookup: function nameLookup(parent, name /* , type*/) {
  117152. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  117153. return [parent, '.', name];
  117154. } else {
  117155. return [parent, '[', JSON.stringify(name), ']'];
  117156. }
  117157. },
  117158. depthedLookup: function depthedLookup(name) {
  117159. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  117160. },
  117161. compilerInfo: function compilerInfo() {
  117162. var revision = _base.COMPILER_REVISION,
  117163. versions = _base.REVISION_CHANGES[revision];
  117164. return [revision, versions];
  117165. },
  117166. appendToBuffer: function appendToBuffer(source, location, explicit) {
  117167. // Force a source as this simplifies the merge logic.
  117168. if (!_utils.isArray(source)) {
  117169. source = [source];
  117170. }
  117171. source = this.source.wrap(source, location);
  117172. if (this.environment.isSimple) {
  117173. return ['return ', source, ';'];
  117174. } else if (explicit) {
  117175. // This is a case where the buffer operation occurs as a child of another
  117176. // construct, generally braces. We have to explicitly output these buffer
  117177. // operations to ensure that the emitted code goes in the correct location.
  117178. return ['buffer += ', source, ';'];
  117179. } else {
  117180. source.appendToBuffer = true;
  117181. return source;
  117182. }
  117183. },
  117184. initializeBuffer: function initializeBuffer() {
  117185. return this.quotedString('');
  117186. },
  117187. // END PUBLIC API
  117188. compile: function compile(environment, options, context, asObject) {
  117189. this.environment = environment;
  117190. this.options = options;
  117191. this.stringParams = this.options.stringParams;
  117192. this.trackIds = this.options.trackIds;
  117193. this.precompile = !asObject;
  117194. this.name = this.environment.name;
  117195. this.isChild = !!context;
  117196. this.context = context || {
  117197. decorators: [],
  117198. programs: [],
  117199. environments: []
  117200. };
  117201. this.preamble();
  117202. this.stackSlot = 0;
  117203. this.stackVars = [];
  117204. this.aliases = {};
  117205. this.registers = { list: [] };
  117206. this.hashes = [];
  117207. this.compileStack = [];
  117208. this.inlineStack = [];
  117209. this.blockParams = [];
  117210. this.compileChildren(environment, options);
  117211. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  117212. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  117213. var opcodes = environment.opcodes,
  117214. opcode = undefined,
  117215. firstLoc = undefined,
  117216. i = undefined,
  117217. l = undefined;
  117218. for (i = 0, l = opcodes.length; i < l; i++) {
  117219. opcode = opcodes[i];
  117220. this.source.currentLocation = opcode.loc;
  117221. firstLoc = firstLoc || opcode.loc;
  117222. this[opcode.opcode].apply(this, opcode.args);
  117223. }
  117224. // Flush any trailing content that might be pending.
  117225. this.source.currentLocation = firstLoc;
  117226. this.pushSource('');
  117227. /* istanbul ignore next */
  117228. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  117229. throw new _exception2['default']('Compile completed with content left on stack');
  117230. }
  117231. if (!this.decorators.isEmpty()) {
  117232. this.useDecorators = true;
  117233. this.decorators.prepend('var decorators = container.decorators;\n');
  117234. this.decorators.push('return fn;');
  117235. if (asObject) {
  117236. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  117237. } else {
  117238. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  117239. this.decorators.push('}\n');
  117240. this.decorators = this.decorators.merge();
  117241. }
  117242. } else {
  117243. this.decorators = undefined;
  117244. }
  117245. var fn = this.createFunctionContext(asObject);
  117246. if (!this.isChild) {
  117247. var ret = {
  117248. compiler: this.compilerInfo(),
  117249. main: fn
  117250. };
  117251. if (this.decorators) {
  117252. ret.main_d = this.decorators; // eslint-disable-line camelcase
  117253. ret.useDecorators = true;
  117254. }
  117255. var _context = this.context;
  117256. var programs = _context.programs;
  117257. var decorators = _context.decorators;
  117258. for (i = 0, l = programs.length; i < l; i++) {
  117259. if (programs[i]) {
  117260. ret[i] = programs[i];
  117261. if (decorators[i]) {
  117262. ret[i + '_d'] = decorators[i];
  117263. ret.useDecorators = true;
  117264. }
  117265. }
  117266. }
  117267. if (this.environment.usePartial) {
  117268. ret.usePartial = true;
  117269. }
  117270. if (this.options.data) {
  117271. ret.useData = true;
  117272. }
  117273. if (this.useDepths) {
  117274. ret.useDepths = true;
  117275. }
  117276. if (this.useBlockParams) {
  117277. ret.useBlockParams = true;
  117278. }
  117279. if (this.options.compat) {
  117280. ret.compat = true;
  117281. }
  117282. if (!asObject) {
  117283. ret.compiler = JSON.stringify(ret.compiler);
  117284. this.source.currentLocation = { start: { line: 1, column: 0 } };
  117285. ret = this.objectLiteral(ret);
  117286. if (options.srcName) {
  117287. ret = ret.toStringWithSourceMap({ file: options.destName });
  117288. ret.map = ret.map && ret.map.toString();
  117289. } else {
  117290. ret = ret.toString();
  117291. }
  117292. } else {
  117293. ret.compilerOptions = this.options;
  117294. }
  117295. return ret;
  117296. } else {
  117297. return fn;
  117298. }
  117299. },
  117300. preamble: function preamble() {
  117301. // track the last context pushed into place to allow skipping the
  117302. // getContext opcode when it would be a noop
  117303. this.lastContext = 0;
  117304. this.source = new _codeGen2['default'](this.options.srcName);
  117305. this.decorators = new _codeGen2['default'](this.options.srcName);
  117306. },
  117307. createFunctionContext: function createFunctionContext(asObject) {
  117308. var varDeclarations = '';
  117309. var locals = this.stackVars.concat(this.registers.list);
  117310. if (locals.length > 0) {
  117311. varDeclarations += ', ' + locals.join(', ');
  117312. }
  117313. // Generate minimizer alias mappings
  117314. //
  117315. // When using true SourceNodes, this will update all references to the given alias
  117316. // as the source nodes are reused in situ. For the non-source node compilation mode,
  117317. // aliases will not be used, but this case is already being run on the client and
  117318. // we aren't concern about minimizing the template size.
  117319. var aliasCount = 0;
  117320. for (var alias in this.aliases) {
  117321. // eslint-disable-line guard-for-in
  117322. var node = this.aliases[alias];
  117323. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  117324. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  117325. node.children[0] = 'alias' + aliasCount;
  117326. }
  117327. }
  117328. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  117329. if (this.useBlockParams || this.useDepths) {
  117330. params.push('blockParams');
  117331. }
  117332. if (this.useDepths) {
  117333. params.push('depths');
  117334. }
  117335. // Perform a second pass over the output to merge content when possible
  117336. var source = this.mergeSource(varDeclarations);
  117337. if (asObject) {
  117338. params.push(source);
  117339. return Function.apply(this, params);
  117340. } else {
  117341. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  117342. }
  117343. },
  117344. mergeSource: function mergeSource(varDeclarations) {
  117345. var isSimple = this.environment.isSimple,
  117346. appendOnly = !this.forceBuffer,
  117347. appendFirst = undefined,
  117348. sourceSeen = undefined,
  117349. bufferStart = undefined,
  117350. bufferEnd = undefined;
  117351. this.source.each(function (line) {
  117352. if (line.appendToBuffer) {
  117353. if (bufferStart) {
  117354. line.prepend(' + ');
  117355. } else {
  117356. bufferStart = line;
  117357. }
  117358. bufferEnd = line;
  117359. } else {
  117360. if (bufferStart) {
  117361. if (!sourceSeen) {
  117362. appendFirst = true;
  117363. } else {
  117364. bufferStart.prepend('buffer += ');
  117365. }
  117366. bufferEnd.add(';');
  117367. bufferStart = bufferEnd = undefined;
  117368. }
  117369. sourceSeen = true;
  117370. if (!isSimple) {
  117371. appendOnly = false;
  117372. }
  117373. }
  117374. });
  117375. if (appendOnly) {
  117376. if (bufferStart) {
  117377. bufferStart.prepend('return ');
  117378. bufferEnd.add(';');
  117379. } else if (!sourceSeen) {
  117380. this.source.push('return "";');
  117381. }
  117382. } else {
  117383. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  117384. if (bufferStart) {
  117385. bufferStart.prepend('return buffer + ');
  117386. bufferEnd.add(';');
  117387. } else {
  117388. this.source.push('return buffer;');
  117389. }
  117390. }
  117391. if (varDeclarations) {
  117392. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  117393. }
  117394. return this.source.merge();
  117395. },
  117396. // [blockValue]
  117397. //
  117398. // On stack, before: hash, inverse, program, value
  117399. // On stack, after: return value of blockHelperMissing
  117400. //
  117401. // The purpose of this opcode is to take a block of the form
  117402. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  117403. // replace it on the stack with the result of properly
  117404. // invoking blockHelperMissing.
  117405. blockValue: function blockValue(name) {
  117406. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  117407. params = [this.contextName(0)];
  117408. this.setupHelperArgs(name, 0, params);
  117409. var blockName = this.popStack();
  117410. params.splice(1, 0, blockName);
  117411. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  117412. },
  117413. // [ambiguousBlockValue]
  117414. //
  117415. // On stack, before: hash, inverse, program, value
  117416. // Compiler value, before: lastHelper=value of last found helper, if any
  117417. // On stack, after, if no lastHelper: same as [blockValue]
  117418. // On stack, after, if lastHelper: value
  117419. ambiguousBlockValue: function ambiguousBlockValue() {
  117420. // We're being a bit cheeky and reusing the options value from the prior exec
  117421. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  117422. params = [this.contextName(0)];
  117423. this.setupHelperArgs('', 0, params, true);
  117424. this.flushInline();
  117425. var current = this.topStack();
  117426. params.splice(1, 0, current);
  117427. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  117428. },
  117429. // [appendContent]
  117430. //
  117431. // On stack, before: ...
  117432. // On stack, after: ...
  117433. //
  117434. // Appends the string value of `content` to the current buffer
  117435. appendContent: function appendContent(content) {
  117436. if (this.pendingContent) {
  117437. content = this.pendingContent + content;
  117438. } else {
  117439. this.pendingLocation = this.source.currentLocation;
  117440. }
  117441. this.pendingContent = content;
  117442. },
  117443. // [append]
  117444. //
  117445. // On stack, before: value, ...
  117446. // On stack, after: ...
  117447. //
  117448. // Coerces `value` to a String and appends it to the current buffer.
  117449. //
  117450. // If `value` is truthy, or 0, it is coerced into a string and appended
  117451. // Otherwise, the empty string is appended
  117452. append: function append() {
  117453. if (this.isInline()) {
  117454. this.replaceStack(function (current) {
  117455. return [' != null ? ', current, ' : ""'];
  117456. });
  117457. this.pushSource(this.appendToBuffer(this.popStack()));
  117458. } else {
  117459. var local = this.popStack();
  117460. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  117461. if (this.environment.isSimple) {
  117462. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  117463. }
  117464. }
  117465. },
  117466. // [appendEscaped]
  117467. //
  117468. // On stack, before: value, ...
  117469. // On stack, after: ...
  117470. //
  117471. // Escape `value` and append it to the buffer
  117472. appendEscaped: function appendEscaped() {
  117473. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  117474. },
  117475. // [getContext]
  117476. //
  117477. // On stack, before: ...
  117478. // On stack, after: ...
  117479. // Compiler value, after: lastContext=depth
  117480. //
  117481. // Set the value of the `lastContext` compiler value to the depth
  117482. getContext: function getContext(depth) {
  117483. this.lastContext = depth;
  117484. },
  117485. // [pushContext]
  117486. //
  117487. // On stack, before: ...
  117488. // On stack, after: currentContext, ...
  117489. //
  117490. // Pushes the value of the current context onto the stack.
  117491. pushContext: function pushContext() {
  117492. this.pushStackLiteral(this.contextName(this.lastContext));
  117493. },
  117494. // [lookupOnContext]
  117495. //
  117496. // On stack, before: ...
  117497. // On stack, after: currentContext[name], ...
  117498. //
  117499. // Looks up the value of `name` on the current context and pushes
  117500. // it onto the stack.
  117501. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  117502. var i = 0;
  117503. if (!scoped && this.options.compat && !this.lastContext) {
  117504. // The depthed query is expected to handle the undefined logic for the root level that
  117505. // is implemented below, so we evaluate that directly in compat mode
  117506. this.push(this.depthedLookup(parts[i++]));
  117507. } else {
  117508. this.pushContext();
  117509. }
  117510. this.resolvePath('context', parts, i, falsy, strict);
  117511. },
  117512. // [lookupBlockParam]
  117513. //
  117514. // On stack, before: ...
  117515. // On stack, after: blockParam[name], ...
  117516. //
  117517. // Looks up the value of `parts` on the given block param and pushes
  117518. // it onto the stack.
  117519. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  117520. this.useBlockParams = true;
  117521. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  117522. this.resolvePath('context', parts, 1);
  117523. },
  117524. // [lookupData]
  117525. //
  117526. // On stack, before: ...
  117527. // On stack, after: data, ...
  117528. //
  117529. // Push the data lookup operator
  117530. lookupData: function lookupData(depth, parts, strict) {
  117531. if (!depth) {
  117532. this.pushStackLiteral('data');
  117533. } else {
  117534. this.pushStackLiteral('container.data(data, ' + depth + ')');
  117535. }
  117536. this.resolvePath('data', parts, 0, true, strict);
  117537. },
  117538. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  117539. // istanbul ignore next
  117540. var _this = this;
  117541. if (this.options.strict || this.options.assumeObjects) {
  117542. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  117543. return;
  117544. }
  117545. var len = parts.length;
  117546. for (; i < len; i++) {
  117547. /* eslint-disable no-loop-func */
  117548. this.replaceStack(function (current) {
  117549. var lookup = _this.nameLookup(current, parts[i], type);
  117550. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  117551. // needs to have the special handling for these values.
  117552. if (!falsy) {
  117553. return [' != null ? ', lookup, ' : ', current];
  117554. } else {
  117555. // Otherwise we can use generic falsy handling
  117556. return [' && ', lookup];
  117557. }
  117558. });
  117559. /* eslint-enable no-loop-func */
  117560. }
  117561. },
  117562. // [resolvePossibleLambda]
  117563. //
  117564. // On stack, before: value, ...
  117565. // On stack, after: resolved value, ...
  117566. //
  117567. // If the `value` is a lambda, replace it on the stack by
  117568. // the return value of the lambda
  117569. resolvePossibleLambda: function resolvePossibleLambda() {
  117570. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  117571. },
  117572. // [pushStringParam]
  117573. //
  117574. // On stack, before: ...
  117575. // On stack, after: string, currentContext, ...
  117576. //
  117577. // This opcode is designed for use in string mode, which
  117578. // provides the string value of a parameter along with its
  117579. // depth rather than resolving it immediately.
  117580. pushStringParam: function pushStringParam(string, type) {
  117581. this.pushContext();
  117582. this.pushString(type);
  117583. // If it's a subexpression, the string result
  117584. // will be pushed after this opcode.
  117585. if (type !== 'SubExpression') {
  117586. if (typeof string === 'string') {
  117587. this.pushString(string);
  117588. } else {
  117589. this.pushStackLiteral(string);
  117590. }
  117591. }
  117592. },
  117593. emptyHash: function emptyHash(omitEmpty) {
  117594. if (this.trackIds) {
  117595. this.push('{}'); // hashIds
  117596. }
  117597. if (this.stringParams) {
  117598. this.push('{}'); // hashContexts
  117599. this.push('{}'); // hashTypes
  117600. }
  117601. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  117602. },
  117603. pushHash: function pushHash() {
  117604. if (this.hash) {
  117605. this.hashes.push(this.hash);
  117606. }
  117607. this.hash = { values: [], types: [], contexts: [], ids: [] };
  117608. },
  117609. popHash: function popHash() {
  117610. var hash = this.hash;
  117611. this.hash = this.hashes.pop();
  117612. if (this.trackIds) {
  117613. this.push(this.objectLiteral(hash.ids));
  117614. }
  117615. if (this.stringParams) {
  117616. this.push(this.objectLiteral(hash.contexts));
  117617. this.push(this.objectLiteral(hash.types));
  117618. }
  117619. this.push(this.objectLiteral(hash.values));
  117620. },
  117621. // [pushString]
  117622. //
  117623. // On stack, before: ...
  117624. // On stack, after: quotedString(string), ...
  117625. //
  117626. // Push a quoted version of `string` onto the stack
  117627. pushString: function pushString(string) {
  117628. this.pushStackLiteral(this.quotedString(string));
  117629. },
  117630. // [pushLiteral]
  117631. //
  117632. // On stack, before: ...
  117633. // On stack, after: value, ...
  117634. //
  117635. // Pushes a value onto the stack. This operation prevents
  117636. // the compiler from creating a temporary variable to hold
  117637. // it.
  117638. pushLiteral: function pushLiteral(value) {
  117639. this.pushStackLiteral(value);
  117640. },
  117641. // [pushProgram]
  117642. //
  117643. // On stack, before: ...
  117644. // On stack, after: program(guid), ...
  117645. //
  117646. // Push a program expression onto the stack. This takes
  117647. // a compile-time guid and converts it into a runtime-accessible
  117648. // expression.
  117649. pushProgram: function pushProgram(guid) {
  117650. if (guid != null) {
  117651. this.pushStackLiteral(this.programExpression(guid));
  117652. } else {
  117653. this.pushStackLiteral(null);
  117654. }
  117655. },
  117656. // [registerDecorator]
  117657. //
  117658. // On stack, before: hash, program, params..., ...
  117659. // On stack, after: ...
  117660. //
  117661. // Pops off the decorator's parameters, invokes the decorator,
  117662. // and inserts the decorator into the decorators list.
  117663. registerDecorator: function registerDecorator(paramSize, name) {
  117664. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  117665. options = this.setupHelperArgs(name, paramSize);
  117666. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  117667. },
  117668. // [invokeHelper]
  117669. //
  117670. // On stack, before: hash, inverse, program, params..., ...
  117671. // On stack, after: result of helper invocation
  117672. //
  117673. // Pops off the helper's parameters, invokes the helper,
  117674. // and pushes the helper's return value onto the stack.
  117675. //
  117676. // If the helper is not found, `helperMissing` is called.
  117677. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  117678. var nonHelper = this.popStack(),
  117679. helper = this.setupHelper(paramSize, name),
  117680. simple = isSimple ? [helper.name, ' || '] : '';
  117681. var lookup = ['('].concat(simple, nonHelper);
  117682. if (!this.options.strict) {
  117683. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  117684. }
  117685. lookup.push(')');
  117686. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  117687. },
  117688. // [invokeKnownHelper]
  117689. //
  117690. // On stack, before: hash, inverse, program, params..., ...
  117691. // On stack, after: result of helper invocation
  117692. //
  117693. // This operation is used when the helper is known to exist,
  117694. // so a `helperMissing` fallback is not required.
  117695. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  117696. var helper = this.setupHelper(paramSize, name);
  117697. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  117698. },
  117699. // [invokeAmbiguous]
  117700. //
  117701. // On stack, before: hash, inverse, program, params..., ...
  117702. // On stack, after: result of disambiguation
  117703. //
  117704. // This operation is used when an expression like `{{foo}}`
  117705. // is provided, but we don't know at compile-time whether it
  117706. // is a helper or a path.
  117707. //
  117708. // This operation emits more code than the other options,
  117709. // and can be avoided by passing the `knownHelpers` and
  117710. // `knownHelpersOnly` flags at compile-time.
  117711. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  117712. this.useRegister('helper');
  117713. var nonHelper = this.popStack();
  117714. this.emptyHash();
  117715. var helper = this.setupHelper(0, name, helperCall);
  117716. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  117717. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  117718. if (!this.options.strict) {
  117719. lookup[0] = '(helper = ';
  117720. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  117721. }
  117722. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  117723. },
  117724. // [invokePartial]
  117725. //
  117726. // On stack, before: context, ...
  117727. // On stack after: result of partial invocation
  117728. //
  117729. // This operation pops off a context, invokes a partial with that context,
  117730. // and pushes the result of the invocation back.
  117731. invokePartial: function invokePartial(isDynamic, name, indent) {
  117732. var params = [],
  117733. options = this.setupParams(name, 1, params);
  117734. if (isDynamic) {
  117735. name = this.popStack();
  117736. delete options.name;
  117737. }
  117738. if (indent) {
  117739. options.indent = JSON.stringify(indent);
  117740. }
  117741. options.helpers = 'helpers';
  117742. options.partials = 'partials';
  117743. options.decorators = 'container.decorators';
  117744. if (!isDynamic) {
  117745. params.unshift(this.nameLookup('partials', name, 'partial'));
  117746. } else {
  117747. params.unshift(name);
  117748. }
  117749. if (this.options.compat) {
  117750. options.depths = 'depths';
  117751. }
  117752. options = this.objectLiteral(options);
  117753. params.push(options);
  117754. this.push(this.source.functionCall('container.invokePartial', '', params));
  117755. },
  117756. // [assignToHash]
  117757. //
  117758. // On stack, before: value, ..., hash, ...
  117759. // On stack, after: ..., hash, ...
  117760. //
  117761. // Pops a value off the stack and assigns it to the current hash
  117762. assignToHash: function assignToHash(key) {
  117763. var value = this.popStack(),
  117764. context = undefined,
  117765. type = undefined,
  117766. id = undefined;
  117767. if (this.trackIds) {
  117768. id = this.popStack();
  117769. }
  117770. if (this.stringParams) {
  117771. type = this.popStack();
  117772. context = this.popStack();
  117773. }
  117774. var hash = this.hash;
  117775. if (context) {
  117776. hash.contexts[key] = context;
  117777. }
  117778. if (type) {
  117779. hash.types[key] = type;
  117780. }
  117781. if (id) {
  117782. hash.ids[key] = id;
  117783. }
  117784. hash.values[key] = value;
  117785. },
  117786. pushId: function pushId(type, name, child) {
  117787. if (type === 'BlockParam') {
  117788. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  117789. } else if (type === 'PathExpression') {
  117790. this.pushString(name);
  117791. } else if (type === 'SubExpression') {
  117792. this.pushStackLiteral('true');
  117793. } else {
  117794. this.pushStackLiteral('null');
  117795. }
  117796. },
  117797. // HELPERS
  117798. compiler: JavaScriptCompiler,
  117799. compileChildren: function compileChildren(environment, options) {
  117800. var children = environment.children,
  117801. child = undefined,
  117802. compiler = undefined;
  117803. for (var i = 0, l = children.length; i < l; i++) {
  117804. child = children[i];
  117805. compiler = new this.compiler(); // eslint-disable-line new-cap
  117806. var existing = this.matchExistingProgram(child);
  117807. if (existing == null) {
  117808. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  117809. var index = this.context.programs.length;
  117810. child.index = index;
  117811. child.name = 'program' + index;
  117812. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  117813. this.context.decorators[index] = compiler.decorators;
  117814. this.context.environments[index] = child;
  117815. this.useDepths = this.useDepths || compiler.useDepths;
  117816. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  117817. child.useDepths = this.useDepths;
  117818. child.useBlockParams = this.useBlockParams;
  117819. } else {
  117820. child.index = existing.index;
  117821. child.name = 'program' + existing.index;
  117822. this.useDepths = this.useDepths || existing.useDepths;
  117823. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  117824. }
  117825. }
  117826. },
  117827. matchExistingProgram: function matchExistingProgram(child) {
  117828. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  117829. var environment = this.context.environments[i];
  117830. if (environment && environment.equals(child)) {
  117831. return environment;
  117832. }
  117833. }
  117834. },
  117835. programExpression: function programExpression(guid) {
  117836. var child = this.environment.children[guid],
  117837. programParams = [child.index, 'data', child.blockParams];
  117838. if (this.useBlockParams || this.useDepths) {
  117839. programParams.push('blockParams');
  117840. }
  117841. if (this.useDepths) {
  117842. programParams.push('depths');
  117843. }
  117844. return 'container.program(' + programParams.join(', ') + ')';
  117845. },
  117846. useRegister: function useRegister(name) {
  117847. if (!this.registers[name]) {
  117848. this.registers[name] = true;
  117849. this.registers.list.push(name);
  117850. }
  117851. },
  117852. push: function push(expr) {
  117853. if (!(expr instanceof Literal)) {
  117854. expr = this.source.wrap(expr);
  117855. }
  117856. this.inlineStack.push(expr);
  117857. return expr;
  117858. },
  117859. pushStackLiteral: function pushStackLiteral(item) {
  117860. this.push(new Literal(item));
  117861. },
  117862. pushSource: function pushSource(source) {
  117863. if (this.pendingContent) {
  117864. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  117865. this.pendingContent = undefined;
  117866. }
  117867. if (source) {
  117868. this.source.push(source);
  117869. }
  117870. },
  117871. replaceStack: function replaceStack(callback) {
  117872. var prefix = ['('],
  117873. stack = undefined,
  117874. createdStack = undefined,
  117875. usedLiteral = undefined;
  117876. /* istanbul ignore next */
  117877. if (!this.isInline()) {
  117878. throw new _exception2['default']('replaceStack on non-inline');
  117879. }
  117880. // We want to merge the inline statement into the replacement statement via ','
  117881. var top = this.popStack(true);
  117882. if (top instanceof Literal) {
  117883. // Literals do not need to be inlined
  117884. stack = [top.value];
  117885. prefix = ['(', stack];
  117886. usedLiteral = true;
  117887. } else {
  117888. // Get or create the current stack name for use by the inline
  117889. createdStack = true;
  117890. var _name = this.incrStack();
  117891. prefix = ['((', this.push(_name), ' = ', top, ')'];
  117892. stack = this.topStack();
  117893. }
  117894. var item = callback.call(this, stack);
  117895. if (!usedLiteral) {
  117896. this.popStack();
  117897. }
  117898. if (createdStack) {
  117899. this.stackSlot--;
  117900. }
  117901. this.push(prefix.concat(item, ')'));
  117902. },
  117903. incrStack: function incrStack() {
  117904. this.stackSlot++;
  117905. if (this.stackSlot > this.stackVars.length) {
  117906. this.stackVars.push('stack' + this.stackSlot);
  117907. }
  117908. return this.topStackName();
  117909. },
  117910. topStackName: function topStackName() {
  117911. return 'stack' + this.stackSlot;
  117912. },
  117913. flushInline: function flushInline() {
  117914. var inlineStack = this.inlineStack;
  117915. this.inlineStack = [];
  117916. for (var i = 0, len = inlineStack.length; i < len; i++) {
  117917. var entry = inlineStack[i];
  117918. /* istanbul ignore if */
  117919. if (entry instanceof Literal) {
  117920. this.compileStack.push(entry);
  117921. } else {
  117922. var stack = this.incrStack();
  117923. this.pushSource([stack, ' = ', entry, ';']);
  117924. this.compileStack.push(stack);
  117925. }
  117926. }
  117927. },
  117928. isInline: function isInline() {
  117929. return this.inlineStack.length;
  117930. },
  117931. popStack: function popStack(wrapped) {
  117932. var inline = this.isInline(),
  117933. item = (inline ? this.inlineStack : this.compileStack).pop();
  117934. if (!wrapped && item instanceof Literal) {
  117935. return item.value;
  117936. } else {
  117937. if (!inline) {
  117938. /* istanbul ignore next */
  117939. if (!this.stackSlot) {
  117940. throw new _exception2['default']('Invalid stack pop');
  117941. }
  117942. this.stackSlot--;
  117943. }
  117944. return item;
  117945. }
  117946. },
  117947. topStack: function topStack() {
  117948. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  117949. item = stack[stack.length - 1];
  117950. /* istanbul ignore if */
  117951. if (item instanceof Literal) {
  117952. return item.value;
  117953. } else {
  117954. return item;
  117955. }
  117956. },
  117957. contextName: function contextName(context) {
  117958. if (this.useDepths && context) {
  117959. return 'depths[' + context + ']';
  117960. } else {
  117961. return 'depth' + context;
  117962. }
  117963. },
  117964. quotedString: function quotedString(str) {
  117965. return this.source.quotedString(str);
  117966. },
  117967. objectLiteral: function objectLiteral(obj) {
  117968. return this.source.objectLiteral(obj);
  117969. },
  117970. aliasable: function aliasable(name) {
  117971. var ret = this.aliases[name];
  117972. if (ret) {
  117973. ret.referenceCount++;
  117974. return ret;
  117975. }
  117976. ret = this.aliases[name] = this.source.wrap(name);
  117977. ret.aliasable = true;
  117978. ret.referenceCount = 1;
  117979. return ret;
  117980. },
  117981. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  117982. var params = [],
  117983. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  117984. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  117985. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  117986. return {
  117987. params: params,
  117988. paramsInit: paramsInit,
  117989. name: foundHelper,
  117990. callParams: [callContext].concat(params)
  117991. };
  117992. },
  117993. setupParams: function setupParams(helper, paramSize, params) {
  117994. var options = {},
  117995. contexts = [],
  117996. types = [],
  117997. ids = [],
  117998. objectArgs = !params,
  117999. param = undefined;
  118000. if (objectArgs) {
  118001. params = [];
  118002. }
  118003. options.name = this.quotedString(helper);
  118004. options.hash = this.popStack();
  118005. if (this.trackIds) {
  118006. options.hashIds = this.popStack();
  118007. }
  118008. if (this.stringParams) {
  118009. options.hashTypes = this.popStack();
  118010. options.hashContexts = this.popStack();
  118011. }
  118012. var inverse = this.popStack(),
  118013. program = this.popStack();
  118014. // Avoid setting fn and inverse if neither are set. This allows
  118015. // helpers to do a check for `if (options.fn)`
  118016. if (program || inverse) {
  118017. options.fn = program || 'container.noop';
  118018. options.inverse = inverse || 'container.noop';
  118019. }
  118020. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  118021. // so we need to pop them off the stack in reverse order
  118022. var i = paramSize;
  118023. while (i--) {
  118024. param = this.popStack();
  118025. params[i] = param;
  118026. if (this.trackIds) {
  118027. ids[i] = this.popStack();
  118028. }
  118029. if (this.stringParams) {
  118030. types[i] = this.popStack();
  118031. contexts[i] = this.popStack();
  118032. }
  118033. }
  118034. if (objectArgs) {
  118035. options.args = this.source.generateArray(params);
  118036. }
  118037. if (this.trackIds) {
  118038. options.ids = this.source.generateArray(ids);
  118039. }
  118040. if (this.stringParams) {
  118041. options.types = this.source.generateArray(types);
  118042. options.contexts = this.source.generateArray(contexts);
  118043. }
  118044. if (this.options.data) {
  118045. options.data = 'data';
  118046. }
  118047. if (this.useBlockParams) {
  118048. options.blockParams = 'blockParams';
  118049. }
  118050. return options;
  118051. },
  118052. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  118053. var options = this.setupParams(helper, paramSize, params);
  118054. options = this.objectLiteral(options);
  118055. if (useRegister) {
  118056. this.useRegister('options');
  118057. params.push('options');
  118058. return ['options=', options];
  118059. } else if (params) {
  118060. params.push(options);
  118061. return '';
  118062. } else {
  118063. return options;
  118064. }
  118065. }
  118066. };
  118067. (function () {
  118068. var reservedWords = ('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(' ');
  118069. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  118070. for (var i = 0, l = reservedWords.length; i < l; i++) {
  118071. compilerWords[reservedWords[i]] = true;
  118072. }
  118073. })();
  118074. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  118075. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  118076. };
  118077. function strictLookup(requireTerminal, compiler, parts, type) {
  118078. var stack = compiler.popStack(),
  118079. i = 0,
  118080. len = parts.length;
  118081. if (requireTerminal) {
  118082. len--;
  118083. }
  118084. for (; i < len; i++) {
  118085. stack = compiler.nameLookup(stack, parts[i], type);
  118086. }
  118087. if (requireTerminal) {
  118088. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  118089. } else {
  118090. return stack;
  118091. }
  118092. }
  118093. exports['default'] = JavaScriptCompiler;
  118094. module.exports = exports['default'];
  118095. /***/ }),
  118096. /* 43 */
  118097. /***/ (function(module, exports, __webpack_require__) {
  118098. /* global define */
  118099. 'use strict';
  118100. exports.__esModule = true;
  118101. var _utils = __webpack_require__(5);
  118102. var SourceNode = undefined;
  118103. try {
  118104. /* istanbul ignore next */
  118105. if (false) {
  118106. // We don't support this in AMD environments. For these environments, we asusme that
  118107. // they are running on the browser and thus have no need for the source-map library.
  118108. var SourceMap = require('source-map');
  118109. SourceNode = SourceMap.SourceNode;
  118110. }
  118111. } catch (err) {}
  118112. /* NOP */
  118113. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  118114. if (!SourceNode) {
  118115. SourceNode = function (line, column, srcFile, chunks) {
  118116. this.src = '';
  118117. if (chunks) {
  118118. this.add(chunks);
  118119. }
  118120. };
  118121. /* istanbul ignore next */
  118122. SourceNode.prototype = {
  118123. add: function add(chunks) {
  118124. if (_utils.isArray(chunks)) {
  118125. chunks = chunks.join('');
  118126. }
  118127. this.src += chunks;
  118128. },
  118129. prepend: function prepend(chunks) {
  118130. if (_utils.isArray(chunks)) {
  118131. chunks = chunks.join('');
  118132. }
  118133. this.src = chunks + this.src;
  118134. },
  118135. toStringWithSourceMap: function toStringWithSourceMap() {
  118136. return { code: this.toString() };
  118137. },
  118138. toString: function toString() {
  118139. return this.src;
  118140. }
  118141. };
  118142. }
  118143. function castChunk(chunk, codeGen, loc) {
  118144. if (_utils.isArray(chunk)) {
  118145. var ret = [];
  118146. for (var i = 0, len = chunk.length; i < len; i++) {
  118147. ret.push(codeGen.wrap(chunk[i], loc));
  118148. }
  118149. return ret;
  118150. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  118151. // Handle primitives that the SourceNode will throw up on
  118152. return chunk + '';
  118153. }
  118154. return chunk;
  118155. }
  118156. function CodeGen(srcFile) {
  118157. this.srcFile = srcFile;
  118158. this.source = [];
  118159. }
  118160. CodeGen.prototype = {
  118161. isEmpty: function isEmpty() {
  118162. return !this.source.length;
  118163. },
  118164. prepend: function prepend(source, loc) {
  118165. this.source.unshift(this.wrap(source, loc));
  118166. },
  118167. push: function push(source, loc) {
  118168. this.source.push(this.wrap(source, loc));
  118169. },
  118170. merge: function merge() {
  118171. var source = this.empty();
  118172. this.each(function (line) {
  118173. source.add([' ', line, '\n']);
  118174. });
  118175. return source;
  118176. },
  118177. each: function each(iter) {
  118178. for (var i = 0, len = this.source.length; i < len; i++) {
  118179. iter(this.source[i]);
  118180. }
  118181. },
  118182. empty: function empty() {
  118183. var loc = this.currentLocation || { start: {} };
  118184. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  118185. },
  118186. wrap: function wrap(chunk) {
  118187. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  118188. if (chunk instanceof SourceNode) {
  118189. return chunk;
  118190. }
  118191. chunk = castChunk(chunk, this, loc);
  118192. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  118193. },
  118194. functionCall: function functionCall(fn, type, params) {
  118195. params = this.generateList(params);
  118196. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  118197. },
  118198. quotedString: function quotedString(str) {
  118199. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  118200. .replace(/\u2029/g, '\\u2029') + '"';
  118201. },
  118202. objectLiteral: function objectLiteral(obj) {
  118203. var pairs = [];
  118204. for (var key in obj) {
  118205. if (obj.hasOwnProperty(key)) {
  118206. var value = castChunk(obj[key], this);
  118207. if (value !== 'undefined') {
  118208. pairs.push([this.quotedString(key), ':', value]);
  118209. }
  118210. }
  118211. }
  118212. var ret = this.generateList(pairs);
  118213. ret.prepend('{');
  118214. ret.add('}');
  118215. return ret;
  118216. },
  118217. generateList: function generateList(entries) {
  118218. var ret = this.empty();
  118219. for (var i = 0, len = entries.length; i < len; i++) {
  118220. if (i) {
  118221. ret.add(',');
  118222. }
  118223. ret.add(castChunk(entries[i], this));
  118224. }
  118225. return ret;
  118226. },
  118227. generateArray: function generateArray(entries) {
  118228. var ret = this.generateList(entries);
  118229. ret.prepend('[');
  118230. ret.add(']');
  118231. return ret;
  118232. }
  118233. };
  118234. exports['default'] = CodeGen;
  118235. module.exports = exports['default'];
  118236. /***/ })
  118237. /******/ ])
  118238. });
  118239. ;
  118240. /***/ }),
  118241. /* 63 */
  118242. /***/ (function(module, exports, __webpack_require__) {
  118243. "use strict";
  118244. Object.defineProperty(exports, "__esModule", { value: true });
  118245. /**
  118246. * The EventManager is in charge of registering user interctions with the viewer.
  118247. * It is used in the TemplateManager
  118248. */
  118249. var EventManager = /** @class */ (function () {
  118250. function EventManager(_templateManager) {
  118251. var _this = this;
  118252. this._templateManager = _templateManager;
  118253. this._callbacksContainer = {};
  118254. this._templateManager.onEventTriggered.add(function (eventData) {
  118255. _this._eventTriggered(eventData);
  118256. });
  118257. }
  118258. /**
  118259. * Register a new callback to a specific template.
  118260. * The best example for the usage can be found in the DefaultViewer
  118261. *
  118262. * @param templateName the templateName to register the event to
  118263. * @param callback The callback to be executed
  118264. * @param eventType the type of event to register
  118265. * @param selector an optional selector. if not defined the parent object in the template will be selected
  118266. */
  118267. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  118268. if (!this._callbacksContainer[templateName]) {
  118269. this._callbacksContainer[templateName] = [];
  118270. }
  118271. this._callbacksContainer[templateName].push({
  118272. eventType: eventType,
  118273. callback: callback,
  118274. selector: selector
  118275. });
  118276. };
  118277. /**
  118278. * This will remove a registered event from the defined template.
  118279. * Each one of the variables apart from the template name are optional, but one must be provided.
  118280. *
  118281. * @param templateName the templateName
  118282. * @param callback the callback to remove (optional)
  118283. * @param eventType the event type to remove (optional)
  118284. * @param selector the selector from which to remove the event (optional)
  118285. */
  118286. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  118287. var callbackDefs = this._callbacksContainer[templateName] || [];
  118288. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  118289. };
  118290. EventManager.prototype._eventTriggered = function (data) {
  118291. var templateName = data.template.name;
  118292. var eventType = data.event.type;
  118293. var selector = data.selector;
  118294. var callbackDefs = this._callbacksContainer[templateName] || [];
  118295. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  118296. callbackDef.callback(data);
  118297. });
  118298. };
  118299. /**
  118300. * Dispose the event manager
  118301. */
  118302. EventManager.prototype.dispose = function () {
  118303. this._callbacksContainer = {};
  118304. };
  118305. return EventManager;
  118306. }());
  118307. exports.EventManager = EventManager;
  118308. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLFVBQUEsU0FBUztZQUNoRCxLQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBQ3BDLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVEOzs7Ozs7OztPQVFHO0lBQ0ksdUNBQWdCLEdBQXZCLFVBQXdCLFlBQW9CLEVBQUUsUUFBNEMsRUFBRSxTQUFrQixFQUFFLFFBQWlCO1FBQzdILElBQUks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0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  118309. /***/ }),
  118310. /* 64 */
  118311. /***/ (function(module, exports, __webpack_require__) {
  118312. /*!
  118313. * PEP v0.4.3 | https://github.com/jquery/PEP
  118314. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  118315. */
  118316. (function (global, factory) {
  118317. true ? module.exports = factory() :
  118318. typeof define === 'function' && define.amd ? define(factory) :
  118319. (global.PointerEventsPolyfill = factory());
  118320. }(this, function () { 'use strict';
  118321. /**
  118322. * This is the constructor for new PointerEvents.
  118323. *
  118324. * New Pointer Events must be given a type, and an optional dictionary of
  118325. * initialization properties.
  118326. *
  118327. * Due to certain platform requirements, events returned from the constructor
  118328. * identify as MouseEvents.
  118329. *
  118330. * @constructor
  118331. * @param {String} inType The type of the event to create.
  118332. * @param {Object} [inDict] An optional dictionary of initial event properties.
  118333. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  118334. */
  118335. var MOUSE_PROPS = [
  118336. 'bubbles',
  118337. 'cancelable',
  118338. 'view',
  118339. 'detail',
  118340. 'screenX',
  118341. 'screenY',
  118342. 'clientX',
  118343. 'clientY',
  118344. 'ctrlKey',
  118345. 'altKey',
  118346. 'shiftKey',
  118347. 'metaKey',
  118348. 'button',
  118349. 'relatedTarget',
  118350. 'pageX',
  118351. 'pageY'
  118352. ];
  118353. var MOUSE_DEFAULTS = [
  118354. false,
  118355. false,
  118356. null,
  118357. null,
  118358. 0,
  118359. 0,
  118360. 0,
  118361. 0,
  118362. false,
  118363. false,
  118364. false,
  118365. false,
  118366. 0,
  118367. null,
  118368. 0,
  118369. 0
  118370. ];
  118371. function PointerEvent(inType, inDict) {
  118372. inDict = inDict || Object.create(null);
  118373. var e = document.createEvent('Event');
  118374. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  118375. // define inherited MouseEvent properties
  118376. // skip bubbles and cancelable since they're set above in initEvent()
  118377. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  118378. p = MOUSE_PROPS[i];
  118379. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  118380. }
  118381. e.buttons = inDict.buttons || 0;
  118382. // Spec requires that pointers without pressure specified use 0.5 for down
  118383. // state and 0 for up state.
  118384. var pressure = 0;
  118385. if (inDict.pressure && e.buttons) {
  118386. pressure = inDict.pressure;
  118387. } else {
  118388. pressure = e.buttons ? 0.5 : 0;
  118389. }
  118390. // add x/y properties aliased to clientX/Y
  118391. e.x = e.clientX;
  118392. e.y = e.clientY;
  118393. // define the properties of the PointerEvent interface
  118394. e.pointerId = inDict.pointerId || 0;
  118395. e.width = inDict.width || 0;
  118396. e.height = inDict.height || 0;
  118397. e.pressure = pressure;
  118398. e.tiltX = inDict.tiltX || 0;
  118399. e.tiltY = inDict.tiltY || 0;
  118400. e.twist = inDict.twist || 0;
  118401. e.tangentialPressure = inDict.tangentialPressure || 0;
  118402. e.pointerType = inDict.pointerType || '';
  118403. e.hwTimestamp = inDict.hwTimestamp || 0;
  118404. e.isPrimary = inDict.isPrimary || false;
  118405. return e;
  118406. }
  118407. /**
  118408. * This module implements a map of pointer states
  118409. */
  118410. var USE_MAP = window.Map && window.Map.prototype.forEach;
  118411. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  118412. function SparseArrayMap() {
  118413. this.array = [];
  118414. this.size = 0;
  118415. }
  118416. SparseArrayMap.prototype = {
  118417. set: function(k, v) {
  118418. if (v === undefined) {
  118419. return this.delete(k);
  118420. }
  118421. if (!this.has(k)) {
  118422. this.size++;
  118423. }
  118424. this.array[k] = v;
  118425. },
  118426. has: function(k) {
  118427. return this.array[k] !== undefined;
  118428. },
  118429. delete: function(k) {
  118430. if (this.has(k)) {
  118431. delete this.array[k];
  118432. this.size--;
  118433. }
  118434. },
  118435. get: function(k) {
  118436. return this.array[k];
  118437. },
  118438. clear: function() {
  118439. this.array.length = 0;
  118440. this.size = 0;
  118441. },
  118442. // return value, key, map
  118443. forEach: function(callback, thisArg) {
  118444. return this.array.forEach(function(v, k) {
  118445. callback.call(thisArg, v, k, this);
  118446. }, this);
  118447. }
  118448. };
  118449. var CLONE_PROPS = [
  118450. // MouseEvent
  118451. 'bubbles',
  118452. 'cancelable',
  118453. 'view',
  118454. 'detail',
  118455. 'screenX',
  118456. 'screenY',
  118457. 'clientX',
  118458. 'clientY',
  118459. 'ctrlKey',
  118460. 'altKey',
  118461. 'shiftKey',
  118462. 'metaKey',
  118463. 'button',
  118464. 'relatedTarget',
  118465. // DOM Level 3
  118466. 'buttons',
  118467. // PointerEvent
  118468. 'pointerId',
  118469. 'width',
  118470. 'height',
  118471. 'pressure',
  118472. 'tiltX',
  118473. 'tiltY',
  118474. 'pointerType',
  118475. 'hwTimestamp',
  118476. 'isPrimary',
  118477. // event instance
  118478. 'type',
  118479. 'target',
  118480. 'currentTarget',
  118481. 'which',
  118482. 'pageX',
  118483. 'pageY',
  118484. 'timeStamp'
  118485. ];
  118486. var CLONE_DEFAULTS = [
  118487. // MouseEvent
  118488. false,
  118489. false,
  118490. null,
  118491. null,
  118492. 0,
  118493. 0,
  118494. 0,
  118495. 0,
  118496. false,
  118497. false,
  118498. false,
  118499. false,
  118500. 0,
  118501. null,
  118502. // DOM Level 3
  118503. 0,
  118504. // PointerEvent
  118505. 0,
  118506. 0,
  118507. 0,
  118508. 0,
  118509. 0,
  118510. 0,
  118511. '',
  118512. 0,
  118513. false,
  118514. // event instance
  118515. '',
  118516. null,
  118517. null,
  118518. 0,
  118519. 0,
  118520. 0,
  118521. 0
  118522. ];
  118523. var BOUNDARY_EVENTS = {
  118524. 'pointerover': 1,
  118525. 'pointerout': 1,
  118526. 'pointerenter': 1,
  118527. 'pointerleave': 1
  118528. };
  118529. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  118530. /**
  118531. * This module is for normalizing events. Mouse and Touch events will be
  118532. * collected here, and fire PointerEvents that have the same semantics, no
  118533. * matter the source.
  118534. * Events fired:
  118535. * - pointerdown: a pointing is added
  118536. * - pointerup: a pointer is removed
  118537. * - pointermove: a pointer is moved
  118538. * - pointerover: a pointer crosses into an element
  118539. * - pointerout: a pointer leaves an element
  118540. * - pointercancel: a pointer will no longer generate events
  118541. */
  118542. var dispatcher = {
  118543. pointermap: new PointerMap(),
  118544. eventMap: Object.create(null),
  118545. captureInfo: Object.create(null),
  118546. // Scope objects for native events.
  118547. // This exists for ease of testing.
  118548. eventSources: Object.create(null),
  118549. eventSourceList: [],
  118550. /**
  118551. * Add a new event source that will generate pointer events.
  118552. *
  118553. * `inSource` must contain an array of event names named `events`, and
  118554. * functions with the names specified in the `events` array.
  118555. * @param {string} name A name for the event source
  118556. * @param {Object} source A new source of platform events.
  118557. */
  118558. registerSource: function(name, source) {
  118559. var s = source;
  118560. var newEvents = s.events;
  118561. if (newEvents) {
  118562. newEvents.forEach(function(e) {
  118563. if (s[e]) {
  118564. this.eventMap[e] = s[e].bind(s);
  118565. }
  118566. }, this);
  118567. this.eventSources[name] = s;
  118568. this.eventSourceList.push(s);
  118569. }
  118570. },
  118571. register: function(element) {
  118572. var l = this.eventSourceList.length;
  118573. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  118574. // call eventsource register
  118575. es.register.call(es, element);
  118576. }
  118577. },
  118578. unregister: function(element) {
  118579. var l = this.eventSourceList.length;
  118580. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  118581. // call eventsource register
  118582. es.unregister.call(es, element);
  118583. }
  118584. },
  118585. contains: /*scope.external.contains || */function(container, contained) {
  118586. try {
  118587. return container.contains(contained);
  118588. } catch (ex) {
  118589. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  118590. return false;
  118591. }
  118592. },
  118593. // EVENTS
  118594. down: function(inEvent) {
  118595. inEvent.bubbles = true;
  118596. this.fireEvent('pointerdown', inEvent);
  118597. },
  118598. move: function(inEvent) {
  118599. inEvent.bubbles = true;
  118600. this.fireEvent('pointermove', inEvent);
  118601. },
  118602. up: function(inEvent) {
  118603. inEvent.bubbles = true;
  118604. this.fireEvent('pointerup', inEvent);
  118605. },
  118606. enter: function(inEvent) {
  118607. inEvent.bubbles = false;
  118608. this.fireEvent('pointerenter', inEvent);
  118609. },
  118610. leave: function(inEvent) {
  118611. inEvent.bubbles = false;
  118612. this.fireEvent('pointerleave', inEvent);
  118613. },
  118614. over: function(inEvent) {
  118615. inEvent.bubbles = true;
  118616. this.fireEvent('pointerover', inEvent);
  118617. },
  118618. out: function(inEvent) {
  118619. inEvent.bubbles = true;
  118620. this.fireEvent('pointerout', inEvent);
  118621. },
  118622. cancel: function(inEvent) {
  118623. inEvent.bubbles = true;
  118624. this.fireEvent('pointercancel', inEvent);
  118625. },
  118626. leaveOut: function(event) {
  118627. this.out(event);
  118628. this.propagate(event, this.leave, false);
  118629. },
  118630. enterOver: function(event) {
  118631. this.over(event);
  118632. this.propagate(event, this.enter, true);
  118633. },
  118634. // LISTENER LOGIC
  118635. eventHandler: function(inEvent) {
  118636. // This is used to prevent multiple dispatch of pointerevents from
  118637. // platform events. This can happen when two elements in different scopes
  118638. // are set up to create pointer events, which is relevant to Shadow DOM.
  118639. if (inEvent._handledByPE) {
  118640. return;
  118641. }
  118642. var type = inEvent.type;
  118643. var fn = this.eventMap && this.eventMap[type];
  118644. if (fn) {
  118645. fn(inEvent);
  118646. }
  118647. inEvent._handledByPE = true;
  118648. },
  118649. // set up event listeners
  118650. listen: function(target, events) {
  118651. events.forEach(function(e) {
  118652. this.addEvent(target, e);
  118653. }, this);
  118654. },
  118655. // remove event listeners
  118656. unlisten: function(target, events) {
  118657. events.forEach(function(e) {
  118658. this.removeEvent(target, e);
  118659. }, this);
  118660. },
  118661. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  118662. target.addEventListener(eventName, this.boundHandler);
  118663. },
  118664. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  118665. target.removeEventListener(eventName, this.boundHandler);
  118666. },
  118667. // EVENT CREATION AND TRACKING
  118668. /**
  118669. * Creates a new Event of type `inType`, based on the information in
  118670. * `inEvent`.
  118671. *
  118672. * @param {string} inType A string representing the type of event to create
  118673. * @param {Event} inEvent A platform event with a target
  118674. * @return {Event} A PointerEvent of type `inType`
  118675. */
  118676. makeEvent: function(inType, inEvent) {
  118677. // relatedTarget must be null if pointer is captured
  118678. if (this.captureInfo[inEvent.pointerId]) {
  118679. inEvent.relatedTarget = null;
  118680. }
  118681. var e = new PointerEvent(inType, inEvent);
  118682. if (inEvent.preventDefault) {
  118683. e.preventDefault = inEvent.preventDefault;
  118684. }
  118685. e._target = e._target || inEvent.target;
  118686. return e;
  118687. },
  118688. // make and dispatch an event in one call
  118689. fireEvent: function(inType, inEvent) {
  118690. var e = this.makeEvent(inType, inEvent);
  118691. return this.dispatchEvent(e);
  118692. },
  118693. /**
  118694. * Returns a snapshot of inEvent, with writable properties.
  118695. *
  118696. * @param {Event} inEvent An event that contains properties to copy.
  118697. * @return {Object} An object containing shallow copies of `inEvent`'s
  118698. * properties.
  118699. */
  118700. cloneEvent: function(inEvent) {
  118701. var eventCopy = Object.create(null);
  118702. var p;
  118703. for (var i = 0; i < CLONE_PROPS.length; i++) {
  118704. p = CLONE_PROPS[i];
  118705. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  118706. // Work around SVGInstanceElement shadow tree
  118707. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  118708. // This is the behavior implemented by Firefox.
  118709. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  118710. if (eventCopy[p] instanceof SVGElementInstance) {
  118711. eventCopy[p] = eventCopy[p].correspondingUseElement;
  118712. }
  118713. }
  118714. }
  118715. // keep the semantics of preventDefault
  118716. if (inEvent.preventDefault) {
  118717. eventCopy.preventDefault = function() {
  118718. inEvent.preventDefault();
  118719. };
  118720. }
  118721. return eventCopy;
  118722. },
  118723. getTarget: function(inEvent) {
  118724. var capture = this.captureInfo[inEvent.pointerId];
  118725. if (!capture) {
  118726. return inEvent._target;
  118727. }
  118728. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  118729. return capture;
  118730. }
  118731. },
  118732. propagate: function(event, fn, propagateDown) {
  118733. var target = event.target;
  118734. var targets = [];
  118735. // Order of conditions due to document.contains() missing in IE.
  118736. while (target !== document && !target.contains(event.relatedTarget)) {
  118737. targets.push(target);
  118738. target = target.parentNode;
  118739. // Touch: Do not propagate if node is detached.
  118740. if (!target) {
  118741. return;
  118742. }
  118743. }
  118744. if (propagateDown) {
  118745. targets.reverse();
  118746. }
  118747. targets.forEach(function(target) {
  118748. event.target = target;
  118749. fn.call(this, event);
  118750. }, this);
  118751. },
  118752. setCapture: function(inPointerId, inTarget, skipDispatch) {
  118753. if (this.captureInfo[inPointerId]) {
  118754. this.releaseCapture(inPointerId, skipDispatch);
  118755. }
  118756. this.captureInfo[inPointerId] = inTarget;
  118757. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  118758. document.addEventListener('pointerup', this.implicitRelease);
  118759. document.addEventListener('pointercancel', this.implicitRelease);
  118760. var e = new PointerEvent('gotpointercapture');
  118761. e.pointerId = inPointerId;
  118762. e._target = inTarget;
  118763. if (!skipDispatch) {
  118764. this.asyncDispatchEvent(e);
  118765. }
  118766. },
  118767. releaseCapture: function(inPointerId, skipDispatch) {
  118768. var t = this.captureInfo[inPointerId];
  118769. if (!t) {
  118770. return;
  118771. }
  118772. this.captureInfo[inPointerId] = undefined;
  118773. document.removeEventListener('pointerup', this.implicitRelease);
  118774. document.removeEventListener('pointercancel', this.implicitRelease);
  118775. var e = new PointerEvent('lostpointercapture');
  118776. e.pointerId = inPointerId;
  118777. e._target = t;
  118778. if (!skipDispatch) {
  118779. this.asyncDispatchEvent(e);
  118780. }
  118781. },
  118782. /**
  118783. * Dispatches the event to its target.
  118784. *
  118785. * @param {Event} inEvent The event to be dispatched.
  118786. * @return {Boolean} True if an event handler returns true, false otherwise.
  118787. */
  118788. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  118789. var t = this.getTarget(inEvent);
  118790. if (t) {
  118791. return t.dispatchEvent(inEvent);
  118792. }
  118793. },
  118794. asyncDispatchEvent: function(inEvent) {
  118795. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  118796. }
  118797. };
  118798. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  118799. var targeting = {
  118800. shadow: function(inEl) {
  118801. if (inEl) {
  118802. return inEl.shadowRoot || inEl.webkitShadowRoot;
  118803. }
  118804. },
  118805. canTarget: function(shadow) {
  118806. return shadow && Boolean(shadow.elementFromPoint);
  118807. },
  118808. targetingShadow: function(inEl) {
  118809. var s = this.shadow(inEl);
  118810. if (this.canTarget(s)) {
  118811. return s;
  118812. }
  118813. },
  118814. olderShadow: function(shadow) {
  118815. var os = shadow.olderShadowRoot;
  118816. if (!os) {
  118817. var se = shadow.querySelector('shadow');
  118818. if (se) {
  118819. os = se.olderShadowRoot;
  118820. }
  118821. }
  118822. return os;
  118823. },
  118824. allShadows: function(element) {
  118825. var shadows = [];
  118826. var s = this.shadow(element);
  118827. while (s) {
  118828. shadows.push(s);
  118829. s = this.olderShadow(s);
  118830. }
  118831. return shadows;
  118832. },
  118833. searchRoot: function(inRoot, x, y) {
  118834. if (inRoot) {
  118835. var t = inRoot.elementFromPoint(x, y);
  118836. var st, sr;
  118837. // is element a shadow host?
  118838. sr = this.targetingShadow(t);
  118839. while (sr) {
  118840. // find the the element inside the shadow root
  118841. st = sr.elementFromPoint(x, y);
  118842. if (!st) {
  118843. // check for older shadows
  118844. sr = this.olderShadow(sr);
  118845. } else {
  118846. // shadowed element may contain a shadow root
  118847. var ssr = this.targetingShadow(st);
  118848. return this.searchRoot(ssr, x, y) || st;
  118849. }
  118850. }
  118851. // light dom element is the target
  118852. return t;
  118853. }
  118854. },
  118855. owner: function(element) {
  118856. var s = element;
  118857. // walk up until you hit the shadow root or document
  118858. while (s.parentNode) {
  118859. s = s.parentNode;
  118860. }
  118861. // the owner element is expected to be a Document or ShadowRoot
  118862. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  118863. s = document;
  118864. }
  118865. return s;
  118866. },
  118867. findTarget: function(inEvent) {
  118868. var x = inEvent.clientX;
  118869. var y = inEvent.clientY;
  118870. // if the listener is in the shadow root, it is much faster to start there
  118871. var s = this.owner(inEvent.target);
  118872. // if x, y is not in this root, fall back to document search
  118873. if (!s.elementFromPoint(x, y)) {
  118874. s = document;
  118875. }
  118876. return this.searchRoot(s, x, y);
  118877. }
  118878. };
  118879. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  118880. var map = Array.prototype.map.call.bind(Array.prototype.map);
  118881. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  118882. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  118883. var MO = window.MutationObserver || window.WebKitMutationObserver;
  118884. var SELECTOR = '[touch-action]';
  118885. var OBSERVER_INIT = {
  118886. subtree: true,
  118887. childList: true,
  118888. attributes: true,
  118889. attributeOldValue: true,
  118890. attributeFilter: ['touch-action']
  118891. };
  118892. function Installer(add, remove, changed, binder) {
  118893. this.addCallback = add.bind(binder);
  118894. this.removeCallback = remove.bind(binder);
  118895. this.changedCallback = changed.bind(binder);
  118896. if (MO) {
  118897. this.observer = new MO(this.mutationWatcher.bind(this));
  118898. }
  118899. }
  118900. Installer.prototype = {
  118901. watchSubtree: function(target) {
  118902. // Only watch scopes that can target find, as these are top-level.
  118903. // Otherwise we can see duplicate additions and removals that add noise.
  118904. //
  118905. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  118906. // a removal without an insertion when a node is redistributed among
  118907. // shadows. Since it all ends up correct in the document, watching only
  118908. // the document will yield the correct mutations to watch.
  118909. if (this.observer && targeting.canTarget(target)) {
  118910. this.observer.observe(target, OBSERVER_INIT);
  118911. }
  118912. },
  118913. enableOnSubtree: function(target) {
  118914. this.watchSubtree(target);
  118915. if (target === document && document.readyState !== 'complete') {
  118916. this.installOnLoad();
  118917. } else {
  118918. this.installNewSubtree(target);
  118919. }
  118920. },
  118921. installNewSubtree: function(target) {
  118922. forEach(this.findElements(target), this.addElement, this);
  118923. },
  118924. findElements: function(target) {
  118925. if (target.querySelectorAll) {
  118926. return target.querySelectorAll(SELECTOR);
  118927. }
  118928. return [];
  118929. },
  118930. removeElement: function(el) {
  118931. this.removeCallback(el);
  118932. },
  118933. addElement: function(el) {
  118934. this.addCallback(el);
  118935. },
  118936. elementChanged: function(el, oldValue) {
  118937. this.changedCallback(el, oldValue);
  118938. },
  118939. concatLists: function(accum, list) {
  118940. return accum.concat(toArray(list));
  118941. },
  118942. // register all touch-action = none nodes on document load
  118943. installOnLoad: function() {
  118944. document.addEventListener('readystatechange', function() {
  118945. if (document.readyState === 'complete') {
  118946. this.installNewSubtree(document);
  118947. }
  118948. }.bind(this));
  118949. },
  118950. isElement: function(n) {
  118951. return n.nodeType === Node.ELEMENT_NODE;
  118952. },
  118953. flattenMutationTree: function(inNodes) {
  118954. // find children with touch-action
  118955. var tree = map(inNodes, this.findElements, this);
  118956. // make sure the added nodes are accounted for
  118957. tree.push(filter(inNodes, this.isElement));
  118958. // flatten the list
  118959. return tree.reduce(this.concatLists, []);
  118960. },
  118961. mutationWatcher: function(mutations) {
  118962. mutations.forEach(this.mutationHandler, this);
  118963. },
  118964. mutationHandler: function(m) {
  118965. if (m.type === 'childList') {
  118966. var added = this.flattenMutationTree(m.addedNodes);
  118967. added.forEach(this.addElement, this);
  118968. var removed = this.flattenMutationTree(m.removedNodes);
  118969. removed.forEach(this.removeElement, this);
  118970. } else if (m.type === 'attributes') {
  118971. this.elementChanged(m.target, m.oldValue);
  118972. }
  118973. }
  118974. };
  118975. function shadowSelector(v) {
  118976. return 'body /shadow-deep/ ' + selector(v);
  118977. }
  118978. function selector(v) {
  118979. return '[touch-action="' + v + '"]';
  118980. }
  118981. function rule(v) {
  118982. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  118983. }
  118984. var attrib2css = [
  118985. 'none',
  118986. 'auto',
  118987. 'pan-x',
  118988. 'pan-y',
  118989. {
  118990. rule: 'pan-x pan-y',
  118991. selectors: [
  118992. 'pan-x pan-y',
  118993. 'pan-y pan-x'
  118994. ]
  118995. }
  118996. ];
  118997. var styles = '';
  118998. // only install stylesheet if the browser has touch action support
  118999. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  119000. // only add shadow selectors if shadowdom is supported
  119001. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  119002. function applyAttributeStyles() {
  119003. if (hasNativePE) {
  119004. attrib2css.forEach(function(r) {
  119005. if (String(r) === r) {
  119006. styles += selector(r) + rule(r) + '\n';
  119007. if (hasShadowRoot) {
  119008. styles += shadowSelector(r) + rule(r) + '\n';
  119009. }
  119010. } else {
  119011. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  119012. if (hasShadowRoot) {
  119013. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  119014. }
  119015. }
  119016. });
  119017. var el = document.createElement('style');
  119018. el.textContent = styles;
  119019. document.head.appendChild(el);
  119020. }
  119021. }
  119022. var pointermap = dispatcher.pointermap;
  119023. // radius around touchend that swallows mouse events
  119024. var DEDUP_DIST = 25;
  119025. // left, middle, right, back, forward
  119026. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  119027. var HAS_BUTTONS = false;
  119028. try {
  119029. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  119030. } catch (e) {}
  119031. // handler block for native mouse events
  119032. var mouseEvents = {
  119033. POINTER_ID: 1,
  119034. POINTER_TYPE: 'mouse',
  119035. events: [
  119036. 'mousedown',
  119037. 'mousemove',
  119038. 'mouseup',
  119039. 'mouseover',
  119040. 'mouseout'
  119041. ],
  119042. register: function(target) {
  119043. dispatcher.listen(target, this.events);
  119044. },
  119045. unregister: function(target) {
  119046. dispatcher.unlisten(target, this.events);
  119047. },
  119048. lastTouches: [],
  119049. // collide with the global mouse listener
  119050. isEventSimulatedFromTouch: function(inEvent) {
  119051. var lts = this.lastTouches;
  119052. var x = inEvent.clientX;
  119053. var y = inEvent.clientY;
  119054. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  119055. // simulated mouse events will be swallowed near a primary touchend
  119056. var dx = Math.abs(x - t.x);
  119057. var dy = Math.abs(y - t.y);
  119058. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  119059. return true;
  119060. }
  119061. }
  119062. },
  119063. prepareEvent: function(inEvent) {
  119064. var e = dispatcher.cloneEvent(inEvent);
  119065. // forward mouse preventDefault
  119066. var pd = e.preventDefault;
  119067. e.preventDefault = function() {
  119068. inEvent.preventDefault();
  119069. pd();
  119070. };
  119071. e.pointerId = this.POINTER_ID;
  119072. e.isPrimary = true;
  119073. e.pointerType = this.POINTER_TYPE;
  119074. return e;
  119075. },
  119076. prepareButtonsForMove: function(e, inEvent) {
  119077. var p = pointermap.get(this.POINTER_ID);
  119078. // Update buttons state after possible out-of-document mouseup.
  119079. if (inEvent.which === 0 || !p) {
  119080. e.buttons = 0;
  119081. } else {
  119082. e.buttons = p.buttons;
  119083. }
  119084. inEvent.buttons = e.buttons;
  119085. },
  119086. mousedown: function(inEvent) {
  119087. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119088. var p = pointermap.get(this.POINTER_ID);
  119089. var e = this.prepareEvent(inEvent);
  119090. if (!HAS_BUTTONS) {
  119091. e.buttons = BUTTON_TO_BUTTONS[e.button];
  119092. if (p) { e.buttons |= p.buttons; }
  119093. inEvent.buttons = e.buttons;
  119094. }
  119095. pointermap.set(this.POINTER_ID, inEvent);
  119096. if (!p || p.buttons === 0) {
  119097. dispatcher.down(e);
  119098. } else {
  119099. dispatcher.move(e);
  119100. }
  119101. }
  119102. },
  119103. mousemove: function(inEvent) {
  119104. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119105. var e = this.prepareEvent(inEvent);
  119106. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119107. e.button = -1;
  119108. pointermap.set(this.POINTER_ID, inEvent);
  119109. dispatcher.move(e);
  119110. }
  119111. },
  119112. mouseup: function(inEvent) {
  119113. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119114. var p = pointermap.get(this.POINTER_ID);
  119115. var e = this.prepareEvent(inEvent);
  119116. if (!HAS_BUTTONS) {
  119117. var up = BUTTON_TO_BUTTONS[e.button];
  119118. // Produces wrong state of buttons in Browsers without `buttons` support
  119119. // when a mouse button that was pressed outside the document is released
  119120. // inside and other buttons are still pressed down.
  119121. e.buttons = p ? p.buttons & ~up : 0;
  119122. inEvent.buttons = e.buttons;
  119123. }
  119124. pointermap.set(this.POINTER_ID, inEvent);
  119125. // Support: Firefox <=44 only
  119126. // FF Ubuntu includes the lifted button in the `buttons` property on
  119127. // mouseup.
  119128. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  119129. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  119130. if (e.buttons === 0) {
  119131. dispatcher.up(e);
  119132. } else {
  119133. dispatcher.move(e);
  119134. }
  119135. }
  119136. },
  119137. mouseover: function(inEvent) {
  119138. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119139. var e = this.prepareEvent(inEvent);
  119140. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119141. e.button = -1;
  119142. pointermap.set(this.POINTER_ID, inEvent);
  119143. dispatcher.enterOver(e);
  119144. }
  119145. },
  119146. mouseout: function(inEvent) {
  119147. if (!this.isEventSimulatedFromTouch(inEvent)) {
  119148. var e = this.prepareEvent(inEvent);
  119149. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  119150. e.button = -1;
  119151. dispatcher.leaveOut(e);
  119152. }
  119153. },
  119154. cancel: function(inEvent) {
  119155. var e = this.prepareEvent(inEvent);
  119156. dispatcher.cancel(e);
  119157. this.deactivateMouse();
  119158. },
  119159. deactivateMouse: function() {
  119160. pointermap.delete(this.POINTER_ID);
  119161. }
  119162. };
  119163. var captureInfo = dispatcher.captureInfo;
  119164. var findTarget = targeting.findTarget.bind(targeting);
  119165. var allShadows = targeting.allShadows.bind(targeting);
  119166. var pointermap$1 = dispatcher.pointermap;
  119167. // This should be long enough to ignore compat mouse events made by touch
  119168. var DEDUP_TIMEOUT = 2500;
  119169. var CLICK_COUNT_TIMEOUT = 200;
  119170. var ATTRIB = 'touch-action';
  119171. var INSTALLER;
  119172. // handler block for native touch events
  119173. var touchEvents = {
  119174. events: [
  119175. 'touchstart',
  119176. 'touchmove',
  119177. 'touchend',
  119178. 'touchcancel'
  119179. ],
  119180. register: function(target) {
  119181. INSTALLER.enableOnSubtree(target);
  119182. },
  119183. unregister: function() {
  119184. // TODO(dfreedman): is it worth it to disconnect the MO?
  119185. },
  119186. elementAdded: function(el) {
  119187. var a = el.getAttribute(ATTRIB);
  119188. var st = this.touchActionToScrollType(a);
  119189. if (st) {
  119190. el._scrollType = st;
  119191. dispatcher.listen(el, this.events);
  119192. // set touch-action on shadows as well
  119193. allShadows(el).forEach(function(s) {
  119194. s._scrollType = st;
  119195. dispatcher.listen(s, this.events);
  119196. }, this);
  119197. }
  119198. },
  119199. elementRemoved: function(el) {
  119200. el._scrollType = undefined;
  119201. dispatcher.unlisten(el, this.events);
  119202. // remove touch-action from shadow
  119203. allShadows(el).forEach(function(s) {
  119204. s._scrollType = undefined;
  119205. dispatcher.unlisten(s, this.events);
  119206. }, this);
  119207. },
  119208. elementChanged: function(el, oldValue) {
  119209. var a = el.getAttribute(ATTRIB);
  119210. var st = this.touchActionToScrollType(a);
  119211. var oldSt = this.touchActionToScrollType(oldValue);
  119212. // simply update scrollType if listeners are already established
  119213. if (st && oldSt) {
  119214. el._scrollType = st;
  119215. allShadows(el).forEach(function(s) {
  119216. s._scrollType = st;
  119217. }, this);
  119218. } else if (oldSt) {
  119219. this.elementRemoved(el);
  119220. } else if (st) {
  119221. this.elementAdded(el);
  119222. }
  119223. },
  119224. scrollTypes: {
  119225. EMITTER: 'none',
  119226. XSCROLLER: 'pan-x',
  119227. YSCROLLER: 'pan-y',
  119228. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  119229. },
  119230. touchActionToScrollType: function(touchAction) {
  119231. var t = touchAction;
  119232. var st = this.scrollTypes;
  119233. if (t === 'none') {
  119234. return 'none';
  119235. } else if (t === st.XSCROLLER) {
  119236. return 'X';
  119237. } else if (t === st.YSCROLLER) {
  119238. return 'Y';
  119239. } else if (st.SCROLLER.exec(t)) {
  119240. return 'XY';
  119241. }
  119242. },
  119243. POINTER_TYPE: 'touch',
  119244. firstTouch: null,
  119245. isPrimaryTouch: function(inTouch) {
  119246. return this.firstTouch === inTouch.identifier;
  119247. },
  119248. setPrimaryTouch: function(inTouch) {
  119249. // set primary touch if there no pointers, or the only pointer is the mouse
  119250. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  119251. this.firstTouch = inTouch.identifier;
  119252. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  119253. this.scrolling = false;
  119254. this.cancelResetClickCount();
  119255. }
  119256. },
  119257. removePrimaryPointer: function(inPointer) {
  119258. if (inPointer.isPrimary) {
  119259. this.firstTouch = null;
  119260. this.firstXY = null;
  119261. this.resetClickCount();
  119262. }
  119263. },
  119264. clickCount: 0,
  119265. resetId: null,
  119266. resetClickCount: function() {
  119267. var fn = function() {
  119268. this.clickCount = 0;
  119269. this.resetId = null;
  119270. }.bind(this);
  119271. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  119272. },
  119273. cancelResetClickCount: function() {
  119274. if (this.resetId) {
  119275. clearTimeout(this.resetId);
  119276. }
  119277. },
  119278. typeToButtons: function(type) {
  119279. var ret = 0;
  119280. if (type === 'touchstart' || type === 'touchmove') {
  119281. ret = 1;
  119282. }
  119283. return ret;
  119284. },
  119285. touchToPointer: function(inTouch) {
  119286. var cte = this.currentTouchEvent;
  119287. var e = dispatcher.cloneEvent(inTouch);
  119288. // We reserve pointerId 1 for Mouse.
  119289. // Touch identifiers can start at 0.
  119290. // Add 2 to the touch identifier for compatibility.
  119291. var id = e.pointerId = inTouch.identifier + 2;
  119292. e.target = captureInfo[id] || findTarget(e);
  119293. e.bubbles = true;
  119294. e.cancelable = true;
  119295. e.detail = this.clickCount;
  119296. e.button = 0;
  119297. e.buttons = this.typeToButtons(cte.type);
  119298. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  119299. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  119300. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  119301. e.isPrimary = this.isPrimaryTouch(inTouch);
  119302. e.pointerType = this.POINTER_TYPE;
  119303. // forward modifier keys
  119304. e.altKey = cte.altKey;
  119305. e.ctrlKey = cte.ctrlKey;
  119306. e.metaKey = cte.metaKey;
  119307. e.shiftKey = cte.shiftKey;
  119308. // forward touch preventDefaults
  119309. var self = this;
  119310. e.preventDefault = function() {
  119311. self.scrolling = false;
  119312. self.firstXY = null;
  119313. cte.preventDefault();
  119314. };
  119315. return e;
  119316. },
  119317. processTouches: function(inEvent, inFunction) {
  119318. var tl = inEvent.changedTouches;
  119319. this.currentTouchEvent = inEvent;
  119320. for (var i = 0, t; i < tl.length; i++) {
  119321. t = tl[i];
  119322. inFunction.call(this, this.touchToPointer(t));
  119323. }
  119324. },
  119325. // For single axis scrollers, determines whether the element should emit
  119326. // pointer events or behave as a scroller
  119327. shouldScroll: function(inEvent) {
  119328. if (this.firstXY) {
  119329. var ret;
  119330. var scrollAxis = inEvent.currentTarget._scrollType;
  119331. if (scrollAxis === 'none') {
  119332. // this element is a touch-action: none, should never scroll
  119333. ret = false;
  119334. } else if (scrollAxis === 'XY') {
  119335. // this element should always scroll
  119336. ret = true;
  119337. } else {
  119338. var t = inEvent.changedTouches[0];
  119339. // check the intended scroll axis, and other axis
  119340. var a = scrollAxis;
  119341. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  119342. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  119343. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  119344. // if delta in the scroll axis > delta other axis, scroll instead of
  119345. // making events
  119346. ret = da >= doa;
  119347. }
  119348. this.firstXY = null;
  119349. return ret;
  119350. }
  119351. },
  119352. findTouch: function(inTL, inId) {
  119353. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  119354. if (t.identifier === inId) {
  119355. return true;
  119356. }
  119357. }
  119358. },
  119359. // In some instances, a touchstart can happen without a touchend. This
  119360. // leaves the pointermap in a broken state.
  119361. // Therefore, on every touchstart, we remove the touches that did not fire a
  119362. // touchend event.
  119363. // To keep state globally consistent, we fire a
  119364. // pointercancel for this "abandoned" touch
  119365. vacuumTouches: function(inEvent) {
  119366. var tl = inEvent.touches;
  119367. // pointermap.size should be < tl.length here, as the touchstart has not
  119368. // been processed yet.
  119369. if (pointermap$1.size >= tl.length) {
  119370. var d = [];
  119371. pointermap$1.forEach(function(value, key) {
  119372. // Never remove pointerId == 1, which is mouse.
  119373. // Touch identifiers are 2 smaller than their pointerId, which is the
  119374. // index in pointermap.
  119375. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  119376. var p = value.out;
  119377. d.push(p);
  119378. }
  119379. }, this);
  119380. d.forEach(this.cancelOut, this);
  119381. }
  119382. },
  119383. touchstart: function(inEvent) {
  119384. this.vacuumTouches(inEvent);
  119385. this.setPrimaryTouch(inEvent.changedTouches[0]);
  119386. this.dedupSynthMouse(inEvent);
  119387. if (!this.scrolling) {
  119388. this.clickCount++;
  119389. this.processTouches(inEvent, this.overDown);
  119390. }
  119391. },
  119392. overDown: function(inPointer) {
  119393. pointermap$1.set(inPointer.pointerId, {
  119394. target: inPointer.target,
  119395. out: inPointer,
  119396. outTarget: inPointer.target
  119397. });
  119398. dispatcher.enterOver(inPointer);
  119399. dispatcher.down(inPointer);
  119400. },
  119401. touchmove: function(inEvent) {
  119402. if (!this.scrolling) {
  119403. if (this.shouldScroll(inEvent)) {
  119404. this.scrolling = true;
  119405. this.touchcancel(inEvent);
  119406. } else {
  119407. inEvent.preventDefault();
  119408. this.processTouches(inEvent, this.moveOverOut);
  119409. }
  119410. }
  119411. },
  119412. moveOverOut: function(inPointer) {
  119413. var event = inPointer;
  119414. var pointer = pointermap$1.get(event.pointerId);
  119415. // a finger drifted off the screen, ignore it
  119416. if (!pointer) {
  119417. return;
  119418. }
  119419. var outEvent = pointer.out;
  119420. var outTarget = pointer.outTarget;
  119421. dispatcher.move(event);
  119422. if (outEvent && outTarget !== event.target) {
  119423. outEvent.relatedTarget = event.target;
  119424. event.relatedTarget = outTarget;
  119425. // recover from retargeting by shadow
  119426. outEvent.target = outTarget;
  119427. if (event.target) {
  119428. dispatcher.leaveOut(outEvent);
  119429. dispatcher.enterOver(event);
  119430. } else {
  119431. // clean up case when finger leaves the screen
  119432. event.target = outTarget;
  119433. event.relatedTarget = null;
  119434. this.cancelOut(event);
  119435. }
  119436. }
  119437. pointer.out = event;
  119438. pointer.outTarget = event.target;
  119439. },
  119440. touchend: function(inEvent) {
  119441. this.dedupSynthMouse(inEvent);
  119442. this.processTouches(inEvent, this.upOut);
  119443. },
  119444. upOut: function(inPointer) {
  119445. if (!this.scrolling) {
  119446. dispatcher.up(inPointer);
  119447. dispatcher.leaveOut(inPointer);
  119448. }
  119449. this.cleanUpPointer(inPointer);
  119450. },
  119451. touchcancel: function(inEvent) {
  119452. this.processTouches(inEvent, this.cancelOut);
  119453. },
  119454. cancelOut: function(inPointer) {
  119455. dispatcher.cancel(inPointer);
  119456. dispatcher.leaveOut(inPointer);
  119457. this.cleanUpPointer(inPointer);
  119458. },
  119459. cleanUpPointer: function(inPointer) {
  119460. pointermap$1.delete(inPointer.pointerId);
  119461. this.removePrimaryPointer(inPointer);
  119462. },
  119463. // prevent synth mouse events from creating pointer events
  119464. dedupSynthMouse: function(inEvent) {
  119465. var lts = mouseEvents.lastTouches;
  119466. var t = inEvent.changedTouches[0];
  119467. // only the primary finger will synth mouse events
  119468. if (this.isPrimaryTouch(t)) {
  119469. // remember x/y of last touch
  119470. var lt = { x: t.clientX, y: t.clientY };
  119471. lts.push(lt);
  119472. var fn = (function(lts, lt) {
  119473. var i = lts.indexOf(lt);
  119474. if (i > -1) {
  119475. lts.splice(i, 1);
  119476. }
  119477. }).bind(null, lts, lt);
  119478. setTimeout(fn, DEDUP_TIMEOUT);
  119479. }
  119480. }
  119481. };
  119482. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  119483. touchEvents.elementChanged, touchEvents);
  119484. var pointermap$2 = dispatcher.pointermap;
  119485. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  119486. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  119487. var msEvents = {
  119488. events: [
  119489. 'MSPointerDown',
  119490. 'MSPointerMove',
  119491. 'MSPointerUp',
  119492. 'MSPointerOut',
  119493. 'MSPointerOver',
  119494. 'MSPointerCancel',
  119495. 'MSGotPointerCapture',
  119496. 'MSLostPointerCapture'
  119497. ],
  119498. register: function(target) {
  119499. dispatcher.listen(target, this.events);
  119500. },
  119501. unregister: function(target) {
  119502. dispatcher.unlisten(target, this.events);
  119503. },
  119504. POINTER_TYPES: [
  119505. '',
  119506. 'unavailable',
  119507. 'touch',
  119508. 'pen',
  119509. 'mouse'
  119510. ],
  119511. prepareEvent: function(inEvent) {
  119512. var e = inEvent;
  119513. if (HAS_BITMAP_TYPE) {
  119514. e = dispatcher.cloneEvent(inEvent);
  119515. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  119516. }
  119517. return e;
  119518. },
  119519. cleanup: function(id) {
  119520. pointermap$2.delete(id);
  119521. },
  119522. MSPointerDown: function(inEvent) {
  119523. pointermap$2.set(inEvent.pointerId, inEvent);
  119524. var e = this.prepareEvent(inEvent);
  119525. dispatcher.down(e);
  119526. },
  119527. MSPointerMove: function(inEvent) {
  119528. var e = this.prepareEvent(inEvent);
  119529. dispatcher.move(e);
  119530. },
  119531. MSPointerUp: function(inEvent) {
  119532. var e = this.prepareEvent(inEvent);
  119533. dispatcher.up(e);
  119534. this.cleanup(inEvent.pointerId);
  119535. },
  119536. MSPointerOut: function(inEvent) {
  119537. var e = this.prepareEvent(inEvent);
  119538. dispatcher.leaveOut(e);
  119539. },
  119540. MSPointerOver: function(inEvent) {
  119541. var e = this.prepareEvent(inEvent);
  119542. dispatcher.enterOver(e);
  119543. },
  119544. MSPointerCancel: function(inEvent) {
  119545. var e = this.prepareEvent(inEvent);
  119546. dispatcher.cancel(e);
  119547. this.cleanup(inEvent.pointerId);
  119548. },
  119549. MSLostPointerCapture: function(inEvent) {
  119550. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  119551. dispatcher.dispatchEvent(e);
  119552. },
  119553. MSGotPointerCapture: function(inEvent) {
  119554. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  119555. dispatcher.dispatchEvent(e);
  119556. }
  119557. };
  119558. function applyPolyfill() {
  119559. // only activate if this platform does not have pointer events
  119560. if (!window.PointerEvent) {
  119561. window.PointerEvent = PointerEvent;
  119562. if (window.navigator.msPointerEnabled) {
  119563. var tp = window.navigator.msMaxTouchPoints;
  119564. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  119565. value: tp,
  119566. enumerable: true
  119567. });
  119568. dispatcher.registerSource('ms', msEvents);
  119569. } else {
  119570. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  119571. value: 0,
  119572. enumerable: true
  119573. });
  119574. dispatcher.registerSource('mouse', mouseEvents);
  119575. if (window.ontouchstart !== undefined) {
  119576. dispatcher.registerSource('touch', touchEvents);
  119577. }
  119578. }
  119579. dispatcher.register(document);
  119580. }
  119581. }
  119582. var n = window.navigator;
  119583. var s;
  119584. var r;
  119585. var h;
  119586. function assertActive(id) {
  119587. if (!dispatcher.pointermap.has(id)) {
  119588. var error = new Error('InvalidPointerId');
  119589. error.name = 'InvalidPointerId';
  119590. throw error;
  119591. }
  119592. }
  119593. function assertConnected(elem) {
  119594. var parent = elem.parentNode;
  119595. while (parent && parent !== elem.ownerDocument) {
  119596. parent = parent.parentNode;
  119597. }
  119598. if (!parent) {
  119599. var error = new Error('InvalidStateError');
  119600. error.name = 'InvalidStateError';
  119601. throw error;
  119602. }
  119603. }
  119604. function inActiveButtonState(id) {
  119605. var p = dispatcher.pointermap.get(id);
  119606. return p.buttons !== 0;
  119607. }
  119608. if (n.msPointerEnabled) {
  119609. s = function(pointerId) {
  119610. assertActive(pointerId);
  119611. assertConnected(this);
  119612. if (inActiveButtonState(pointerId)) {
  119613. dispatcher.setCapture(pointerId, this, true);
  119614. this.msSetPointerCapture(pointerId);
  119615. }
  119616. };
  119617. r = function(pointerId) {
  119618. assertActive(pointerId);
  119619. dispatcher.releaseCapture(pointerId, true);
  119620. this.msReleasePointerCapture(pointerId);
  119621. };
  119622. } else {
  119623. s = function setPointerCapture(pointerId) {
  119624. assertActive(pointerId);
  119625. assertConnected(this);
  119626. if (inActiveButtonState(pointerId)) {
  119627. dispatcher.setCapture(pointerId, this);
  119628. }
  119629. };
  119630. r = function releasePointerCapture(pointerId) {
  119631. assertActive(pointerId);
  119632. dispatcher.releaseCapture(pointerId);
  119633. };
  119634. }
  119635. h = function hasPointerCapture(pointerId) {
  119636. return !!dispatcher.captureInfo[pointerId];
  119637. };
  119638. function applyPolyfill$1() {
  119639. if (window.Element && !Element.prototype.setPointerCapture) {
  119640. Object.defineProperties(Element.prototype, {
  119641. 'setPointerCapture': {
  119642. value: s
  119643. },
  119644. 'releasePointerCapture': {
  119645. value: r
  119646. },
  119647. 'hasPointerCapture': {
  119648. value: h
  119649. }
  119650. });
  119651. }
  119652. }
  119653. applyAttributeStyles();
  119654. applyPolyfill();
  119655. applyPolyfill$1();
  119656. var pointerevents = {
  119657. dispatcher: dispatcher,
  119658. Installer: Installer,
  119659. PointerEvent: PointerEvent,
  119660. PointerMap: PointerMap,
  119661. targetFinding: targeting
  119662. };
  119663. return pointerevents;
  119664. }));
  119665. /***/ }),
  119666. /* 65 */
  119667. /***/ (function(module, exports, __webpack_require__) {
  119668. "use strict";
  119669. Object.defineProperty(exports, "__esModule", { value: true });
  119670. var defaultViewer_1 = __webpack_require__(8);
  119671. var mappers_1 = __webpack_require__(3);
  119672. var globals_1 = __webpack_require__(4);
  119673. /**
  119674. * Will attach an init function the the DOMContentLoaded event.
  119675. * The init function will be removed automatically after the event was triggered.
  119676. */
  119677. function initListeners() {
  119678. document.addEventListener("DOMContentLoaded", init);
  119679. function init(event) {
  119680. document.removeEventListener("DOMContentLoaded", init);
  119681. if (globals_1.viewerGlobals.disableInit)
  119682. return;
  119683. InitTags();
  119684. }
  119685. }
  119686. exports.initListeners = initListeners;
  119687. /**
  119688. * Select all HTML tags on the page that match the selector and initialize a viewer
  119689. *
  119690. * @param selector the selector to initialize the viewer on (default is 'babylon')
  119691. */
  119692. function InitTags(selector) {
  119693. if (selector === void 0) { selector = 'babylon'; }
  119694. var elements = document.querySelectorAll(selector);
  119695. for (var i = 0; i < elements.length; ++i) {
  119696. var element = elements.item(i);
  119697. // get the html configuration
  119698. var configMapper = mappers_1.mapperManager.getMapper('dom');
  119699. var config = configMapper.map(element);
  119700. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  119701. }
  119702. }
  119703. exports.InitTags = InitTags;
  119704. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQztBQUNMLENBQUM7QUFQRCxzQ0FPQztBQUVEOzs7O0dBSUc7QUFDSCxrQkFBeUIsUUFBNEI7SUFBNUIseUJBQUEsRUFBQSxvQkFBNEI7SUFDakQsSUFBSSxRQUFRLEdBQUcsUUFBUSxDQUFDLGdCQUFnQixDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQ25ELEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxRQUFRLENBQUMsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFO1FBQ3RDLElBQUksT0FBTyx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